code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
class Node {
constructor(element) {
this.element = element
this.next = null
}
}
export default Node
| lijsh/Data-Structures | linkedList/node.js | JavaScript | mit | 113 |
package com.ucloud.uvod.example.ui;
import android.content.Context;
import android.support.v7.app.ActionBar;
import android.util.AttributeSet;
import android.view.View;
import android.widget.MediaController;
import com.ucloud.uvod.IMediaController;
import java.util.ArrayList;
public class AndroidMediaController extends MediaController implements IMediaController {
private ActionBar actionBar;
private ArrayList<View> showOnceArray = new ArrayList<>();
public AndroidMediaController(Context context, AttributeSet attrs) {
super(context, attrs);
}
public AndroidMediaController(Context context, boolean useFastForward) {
super(context, useFastForward);
}
public AndroidMediaController(Context context) {
super(context);
}
public void setSupportActionBar(ActionBar actionBar) {
this.actionBar = actionBar;
if (isShowing()) {
actionBar.show();
}
else {
actionBar.hide();
}
}
@Override
public void show() {
super.show();
if (actionBar != null) {
actionBar.show();
}
}
@Override
public void hide() {
super.hide();
if (actionBar != null) {
actionBar.hide();
}
for (View view : showOnceArray) {
view.setVisibility(View.GONE);
}
showOnceArray.clear();
}
public void showOnce(View view) {
showOnceArray.add(view);
view.setVisibility(View.VISIBLE);
show();
}
}
| umdk/UCDMediaPlayer_Android | uvod-demo/src/main/java/com/ucloud/uvod/example/ui/AndroidMediaController.java | Java | mit | 1,557 |
<?php
/*
* This file is part of the Spira framework.
*
* @link https://github.com/spira/spira
*
* For the full copyright and license information, please view the LICENSE file that was distributed with this source code.
*/
namespace Spira\Auth\Driver;
use Illuminate\Http\Request;
use Spira\Auth\Token\JWTInterface;
use Spira\Auth\Token\RequestParser;
use Spira\Auth\Blacklist\Blacklist;
use Spira\Auth\Payload\PayloadFactory;
use Illuminate\Contracts\Auth\UserProvider;
use Spira\Auth\Token\TokenIsMissingException;
use Illuminate\Contracts\Auth\Authenticatable;
use Spira\Auth\Payload\PayloadValidationFactory;
use Spira\Core\Contract\Exception\NotImplementedException;
class Guard implements \Illuminate\Contracts\Auth\Guard
{
/**
* @var UserProvider
*/
protected $provider;
/**
* The currently authenticated user.
*
* @var Authenticatable
*/
protected $user;
/**
* @var bool
*/
protected $viaToken = false;
/**
* @var PayloadFactory
*/
protected $payloadFactory;
/**
* @var JWTInterface
*/
protected $tokenizer;
/**
* @var Request
*/
protected $request;
/**
* @var PayloadValidationFactory
*/
protected $validationFactory;
/**
* @var RequestParser
*/
protected $requestParser;
/**
* @var Blacklist
*/
protected $blacklist;
/**
* @param JWTInterface $tokenizer
* @param PayloadFactory $payloadFactory
* @param PayloadValidationFactory $validationFactory
* @param UserProvider $provider
* @param RequestParser $requestParser
* @param Blacklist $blacklist
*/
public function __construct(
JWTInterface $tokenizer,
PayloadFactory $payloadFactory,
PayloadValidationFactory $validationFactory,
UserProvider $provider,
RequestParser $requestParser,
Blacklist $blacklist,
Request $request
) {
$this->payloadFactory = $payloadFactory;
$this->provider = $provider;
$this->tokenizer = $tokenizer;
$this->validationFactory = $validationFactory;
$this->requestParser = $requestParser;
$this->blacklist = $blacklist;
$this->request = $request;
}
/**
* Determine if the current user is authenticated.
*
* @return bool
*/
public function check()
{
return (bool) $this->user;
}
/**
* Determine if the current user is a guest.
*
* @return bool
*/
public function guest()
{
return ! $this->check();
}
/**
* Get the currently authenticated user.
*
* @return \Illuminate\Contracts\Auth\Authenticatable|null
*/
public function user()
{
if ($this->user === false) {
return;
}
if ($this->user) {
return $this->user;
}
try {
$user = $this->getUserFromRequest();
} catch (\Exception $e) {
return;
}
if ($user) {
$this->user = $user;
$this->viaToken = true;
}
return $user;
}
/**
* {@inheritdoc}
*/
public function setUser(Authenticatable $user)
{
$this->user = $user;
}
/**
* {@inheritdoc}
*/
public function id()
{
return $this->user->getAuthIdentifier();
}
/**
* Get the token of currently authenticated user.
*
* @return string|null
*/
public function token()
{
if ($this->user) {
return $this->generateToken($this->user);
}
return;
}
/**
* @return Authenticatable|null
*/
public function getUserFromRequest()
{
$token = $this->getTokenFromRequest();
$payload = $this->getTokenizer()->decode($token);
$this->getBlacklist()->check($payload);
$this->getValidationFactory()->validatePayload($payload);
$user = $this->getProvider()->retrieveByToken(null, $payload);
return $user;
}
/**
* @return string
*/
protected function getTokenFromRequest()
{
return $this->getRequestParser()->getToken($this->getRequest());
}
/**
* Log a user into the application without token.
*
* @param array $credentials
* @return bool
*/
public function once(array $credentials = [])
{
return $this->attempt($credentials, false, true);
}
/**
* Attempt to authenticate a user using the given credentials.
*
* @param array $credentials
* @param bool $remember
* @param bool $login
* @return bool
*/
public function attempt(array $credentials = [], $remember = true, $login = true)
{
$user = $this->getProvider()->retrieveByCredentials($credentials);
if ($user && $this->getProvider()->validateCredentials($user, $credentials)) {
if ($login) {
$this->login($user);
}
return true;
}
return false;
}
/**
* Attempt to authenticate using HTTP Basic Auth.
*
* @param string $field
* @return null|\Symfony\Component\HttpFoundation\Response
* @throws NotImplementedException
*/
public function basic($field = 'email')
{
throw new NotImplementedException;
}
/**
* Perform a stateless HTTP Basic login attempt.
*
* @param string $field
* @return null|\Symfony\Component\HttpFoundation\Response
* @throws NotImplementedException
*/
public function onceBasic($field = 'email')
{
throw new NotImplementedException;
}
/**
* Validate a user's credentials.
*
* @param array $credentials
* @return bool
* @throws NotImplementedException
*/
public function validate(array $credentials = [])
{
throw new NotImplementedException;
}
/**
* Log a user into the application.
*
* @param \Illuminate\Contracts\Auth\Authenticatable $user
* @param bool $remember set or update token
* @return void
*/
public function login(Authenticatable $user, $remember = false)
{
$this->user = $user;
}
/**
* Log the given user ID into the application.
*
* @param mixed $id auth token
* @param bool $remember
* @return \Illuminate\Contracts\Auth\Authenticatable
*/
public function loginUsingId($id, $remember = false)
{
$user = $this->getProvider()->retrieveById($id);
if ($user) {
$this->login($user);
}
return $user;
}
/**
* Determine if the user was authenticated via token.
*
* @return bool
*/
public function viaRemember()
{
throw new NotImplementedException;
}
/**
* Determine if the user was authenticated via token.
*
* @return bool
*/
public function viaToken()
{
return $this->viaToken;
}
/**
* Log the user out of the application.
*
* @return void
*/
public function logout()
{
try {
$token = $this->getTokenFromRequest();
$this->getBlacklist()->add($this->getTokenizer()->decode($token));
} catch (TokenIsMissingException $e) {
}
$this->user = false;
}
/**
* @param Authenticatable $user
* @return string
*/
public function generateToken(Authenticatable $user)
{
return $this->getTokenizer()->encode($this->getPayloadFactory()->createFromUser($user));
}
/**
* Get the user provider used by the guard.
*
* @return UserProvider
*/
public function getProvider()
{
return $this->provider;
}
/**
* Set the user provider used by the guard.
*
* @param UserProvider $provider
* @return void
*/
public function setProvider(UserProvider $provider)
{
$this->provider = $provider;
}
/**
* @return JWTInterface
*/
public function getTokenizer()
{
return $this->tokenizer;
}
/**
* @return PayloadFactory
*/
public function getPayloadFactory()
{
return $this->payloadFactory;
}
/**
* @return RequestParser
*/
public function getRequestParser()
{
return $this->requestParser;
}
/**
* Get the current request instance.
*
* @return Request
*/
public function getRequest()
{
return $this->request;
}
/**
* Set the current request instance.
*
* @param Request $request
* @return $this
*/
public function setRequest(Request $request)
{
$this->request = $request;
return $this;
}
/**
* @return PayloadValidationFactory
*/
public function getValidationFactory()
{
return $this->validationFactory;
}
/**
* @return Blacklist
*/
public function getBlacklist()
{
return $this->blacklist;
}
}
| spira/spira | api/src/Auth/Driver/Guard.php | PHP | mit | 9,191 |
# Sample Bottle Application
Python bottle example from the [IBM developerWorks wiki](https://www.ibm.com/developerworks/community/wikis/home?lang=en#!/wiki/IBM%20i%20Technology%20Updates/page/Sample%20web%20application%20with%20Python)
# Installing requisites
- **ibm_db & itoolkit:** `yum install python3-ibm_db python3-itoolkit`
- **bottle:** `pip3 install bottle`
# Starting the server
python3 ./sample.py
Point your web browser to http://<systemname>:9000/sample

| Club-Seiden/python-for-IBM-i-examples | non-wheel/bottle-example/README.md | Markdown | mit | 523 |
<?php
$GLOBALS['okt_l10n']['m_lbl_nyromodal_2_menu_config'] = 'nyroModal 2';
$GLOBALS['okt_l10n']['m_lbl_nyromodal_2_config_title'] = 'Configuration nyroModal 2';
$GLOBALS['okt_l10n']['m_lbl_nyromodal_2_config_modal'] = 'Activation de la fenêtre modal ou non';
$GLOBALS['okt_l10n']['m_lbl_nyromodal_2_config_close_on_esc'] = 'Activation de la fermeture avec la touche échappe';
$GLOBALS['okt_l10n']['m_lbl_nyromodal_2_config_close_on_click'] = 'Activation de la fermeture avec le clic sur l’arrière plan';
$GLOBALS['okt_l10n']['m_lbl_nyromodal_2_config_show_close_button'] = 'Affichage du bouton de fermeture ou non';
$GLOBALS['okt_l10n']['m_lbl_nyromodal_2_config_gallery_loop'] = 'Diaporama en boucle';
$GLOBALS['okt_l10n']['m_lbl_nyromodal_2_config_gallery_counts'] = 'Affichage du compteur d’images';
| forxer/okatea | Okatea/Modules/OLD-lbl_nyromodal_2/locales/fr/admin.lang.php | PHP | mit | 814 |
using HazeltineStorage.Models;
using HazeltineStorage.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace HazeltineStorage.Controllers
{
public class ContractBuilderController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
// GET: ContractBuilder
public ActionResult Index()
{
return View();
}
//GET BuildContract
//public ActionResult BuildContract()
//{
// var viewModel = new ContractBuilderViewModel();
// return View(viewModel);
//}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
} | BrianRobertson/HazeltineStorage | HazeltineStorage/Controllers/ContractBuilderController.cs | C# | mit | 923 |
class Brief extends Array {
context?: string | HTMLElement
isBrief = true
length = 0
selector?: string
private contextElement?: HTMLElement
constructor(selector?: string, context?: string | HTMLElement) {
super()
this.selector = selector
this.context = context
if (selector || context) {
if (context) {
if (typeof context === 'string') {
const contextElement = document.querySelector(context)
if (contextElement) {
this.contextElement = contextElement as HTMLElement
}
} else {
this.contextElement = context
}
}
if (selector) {
super.push(
...(this.contextElement || document).querySelectorAll(selector)
)
}
}
}
public clone(): Brief {
const newBrief = brief()
newBrief.selector = this.selector
newBrief.context = this.context
newBrief.contextElement = this.contextElement
Array.prototype.push.apply(newBrief, this.toArray())
return newBrief
}
public toArray() {
return [...this]
}
// @ts-ignore
public push(arg: Brief | HTMLElement | HTMLElement[]): Brief {
const newBrief = this.clone()
if (argIsBrief(arg)) {
super.push.apply(newBrief, [...arg])
} else if (argIsHTMLElement(arg)) {
super.push.call(newBrief, arg)
} else {
super.push.apply(newBrief, arg)
}
return newBrief
}
// @ts-ignore
public filter(filter: string | CallBack<boolean>): Brief {
let newEls
if (typeof filter === 'string') {
newEls = Array.prototype.filter.call(this, (element: HTMLElement) =>
selectorCallback(filter, element)
)
} else {
newEls = Array.prototype.filter.call(
this,
(element: HTMLElement, index) =>
functionFilter(element, filter, index, this)
)
}
const newBrief = this.clone().empty()
super.push.apply(newBrief, newEls)
return newBrief
}
// .find does not allow the user to provide a Callback because it wouldn't make any sense.
// Possibly, we could find all children and then filter then with a Callback, but that is probably
// very bad performance wise, and unwanted most of the time
// @ts-ignore
public find(selector: string): Brief {
let newBrief = this.clone().empty()
this.forEach(element => {
super.push.apply(newBrief, brief(selector, element).toArray())
})
return newBrief
}
// @ts-ignore
public map<T>(callback: CallBack<T>): T[] {
return Array.prototype.map.call<Array<T>, any[], T[]>(
this.toArray(),
(element: HTMLElement, index: number) => callback(element, index, this)
)
}
public indexOf<T>(selector: string | CallBack<boolean>): number {
return Array.prototype.findIndex.call<Brief, any[], number>(
this,
typeof selector === 'string'
? (element: HTMLElement) => selectorCallback(selector, element)
: selector
)
}
public getAttribute(attribute: string): Nullable<string>[] {
return this.map(element => element.getAttribute(attribute))
}
public setAttribute(attribute: string, value: string): Brief {
this.forEach(element => {
element.setAttribute(attribute, value)
})
return this
}
public removeAttribute(attribute: string): Brief {
this.forEach(element => {
element.removeAttribute(attribute)
})
return this
}
public children() {
this.find('*')
}
public on<K extends keyof HTMLElementEventMap>(
type: K,
listener: (this: HTMLElement, event: HTMLElementEventMap[K]) => void
) {
this.forEach(element => {
element.addEventListener(type, listener)
})
}
public fireEvent(event: Event) {
this.forEach(element => {
element.dispatchEvent(event)
})
}
public once<K extends keyof HTMLElementEventMap>(
type: K,
callback: Function
) {
this.forEach(element => {
const listenerWrapper = (event: Event) => {
callback(event)
element.removeEventListener(type, listenerWrapper)
}
element.addEventListener(type, listenerWrapper)
})
}
public off<K extends keyof HTMLElementEventMap>(type: K, callback: Function) {
this.forEach(element => {
element.removeEventListener(type, callback)
})
}
private empty() {
this.length = 0
return this
}
}
export const brief = (selector?: string, context?: string | HTMLElement) => {
return new Brief(selector, context)
}
function selectorCallback(selector: string, element: HTMLElement) {
return element.matches(selector)
}
function functionFilter(
element: HTMLElement,
callback: CallBack<boolean>,
index: number,
brief: Brief
) {
return callback(element, index, brief)
}
type Nullable<T> = T | null
type CallBack<T> = (element: HTMLElement, index: number, brief: Brief) => T
function argIsBrief(possibleBrief: any): possibleBrief is Brief {
return 'isBrief' in possibleBrief
}
function argIsHTMLElement(
possibleHTMLElement: any
): possibleHTMLElement is HTMLElement {
return 'appendChild' in possibleHTMLElement
}
| jeffshaver/brief.js | src/index.ts | TypeScript | mit | 5,340 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>firing-squad: Not compatible</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.10.0 / firing-squad - 8.6.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
firing-squad
<small>
8.6.0
<span class="label label-info">Not compatible</span>
</small>
</h1>
<p><em><script>document.write(moment("2020-07-16 08:04:26 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-07-16 08:04:26 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-num base Num library distributed with the OCaml compiler
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
conf-m4 1 Virtual package relying on m4
coq 8.10.0 Formal proof management system
num 0 The Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.05.0 The OCaml compiler (virtual package)
ocaml-base-compiler 4.05.0 Official 4.05.0 release
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.8.1 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "[email protected]"
homepage: "https://github.com/coq-contribs/firing-squad"
license: "LGPL 2.1"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/FiringSquad"]
depends: [
"ocaml"
"coq" {>= "8.6" & < "8.7~"}
]
tags: [ "keyword: concurrency" "keyword: synchronization" "keyword: finite-state machines" "category: Computer Science/Concurrent Systems and Protocols/Correctness of specific protocols" "category: Miscellaneous/Extracted Programs/Automata and protocols" ]
authors: [ "Jean Duprat" ]
bug-reports: "https://github.com/coq-contribs/firing-squad/issues"
dev-repo: "git+https://github.com/coq-contribs/firing-squad.git"
synopsis: "Firing Squad Synchronization Problem"
description: """
This contribution is a formal verification of a solution
of the firing squad synchronization problem."""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/firing-squad/archive/v8.6.0.tar.gz"
checksum: "md5=ccd68bbd137843dc955aebfa2ee860a9"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-firing-squad.8.6.0 coq.8.10.0</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.10.0).
The following dependencies couldn't be met:
- coq-firing-squad -> coq < 8.7~ -> ocaml < 4.03.0
base of this switch (use `--unlock-base' to force)
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-firing-squad.8.6.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
<small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small>
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| coq-bench/coq-bench.github.io | clean/Linux-x86_64-4.05.0-2.0.6/released/8.10.0/firing-squad/8.6.0.html | HTML | mit | 7,112 |
using System.Reflection;
using CK.CodeGen;
using System.Collections.Generic;
using System;
namespace CK.CodeGen
{
/// <summary>
/// This class exposes the main entry points of the source code model.
/// </summary>
public static class CodeWorkspace
{
/// <summary>
/// Gets a factory of empty workspaces.
/// </summary>
public static readonly Func<ICodeWorkspace> Factory = () => Create();
/// <summary>
/// Creates a root workspace.
/// </summary>
/// <param name="initialSource">Optional initial <see cref="ICodeWorkspace.Global"/> source code.</param>
/// <param name="assembly">Optional initial <see cref="ICodeWorkspace.AssemblyReferences"/>.</param>
/// <returns>A new workspace.</returns>
public static ICodeWorkspace Create( string? initialSource = null, params Assembly[] assembly )
{
var w = new CodeWorkspaceImpl();
if( !String.IsNullOrWhiteSpace( initialSource ) ) w.Global.Append( initialSource );
foreach( var a in assembly ) w.DoEnsureAssemblyReference( a );
return w;
}
/// <summary>
/// Creates a new <see cref="ICodeProject"/> with an optional initial code.
/// </summary>
/// <param name="projectName">The project name.</param>
/// <param name="code">Optional code. When null a new empty one is created.</param>
/// <returns>A new code project.</returns>
public static ICodeProject CreateProject( string projectName, ICodeWorkspace? code = null )
{
if( String.IsNullOrWhiteSpace( projectName ) ) throw new ArgumentNullException( nameof( projectName ) );
return new CodeProjectImpl( projectName, code ?? CodeWorkspace.Create() );
}
}
}
| Invenietis/CK-CodeGen | CK.CodeGen/CodeWorkspace.cs | C# | mit | 1,830 |
% regulus2nuance.pl
% Top-level predicates for regulus2nuance
:- ensure_loaded('$REGULUS/PrologLib/compatibility').
%---------------------------------------------------------------
'LOAD_DYNAMIC_LEXICON_SUPPORT_IF_AVAILABLE'.
:- use_module('$REGULUS/Prolog/regulus_declarations').
:- use_module('$REGULUS/Prolog/regulus2nuance_main').
:- use_module('$REGULUS/Prolog/regulus_read').
:- use_module('$REGULUS/Prolog/regulus_expand').
:- use_module('$REGULUS/Prolog/ebl_postprocess').
:- use_module('$REGULUS/Prolog/regulus_utilities').
:- use_module('$REGULUS/Prolog/regulus_write_nuance').
:- use_module('$REGULUS/PrologLib/utilities').
:- use_module(library(lists)).
%---------------------------------------------------------------
declared_regulus_switch(bup_filtering, [off, naive, linear]).
declared_regulus_switch(tdown_filtering, [off, on]).
declared_regulus_switch(compaction, [off, on]).
declared_regulus_switch(filtering_language, [cpp, prolog]).
declared_regulus_switch(intermediate_rule_set_storage, [term, file]).
%---------------------------------------------------------------
regulus2nuance(InFile, OutFile) :-
regulus2nuance_specifying_grammar_tag(InFile, default, OutFile).
regulus2nuance_specifying_grammar_tag(InFile, GrammarTag, OutFile) :-
init_dynamic_lex_associations_table(OutFile),
regulus2nuance(InFile, GrammarTag, OutFile),
write_dynamic_lex_associations_table.
regulus2nuance(InFile, GrammarTag, OutFile) :-
timed_call(regulus2nuance1(InFile, GrammarTag, OutFile), TimeTaken),
format('~NCompilation finished, ~2f secs~n', [TimeTaken]).
regulus2nuance_for_multiple_grammars(BaseInFile, IgnoreFeatsFile, Tags, OutFile) :-
init_dynamic_lex_associations_table(OutFile),
regulus2nuance_for_multiple_grammars1(Tags, BaseInFile, IgnoreFeatsFile, OutFile, OutComponentFiles),
write_top_level_multiple_grammar_nuance_files(OutComponentFiles, OutFile),
write_dynamic_lex_associations_table.
%---------------------------------------------------------------
regulus2nuance_for_multiple_grammars1([], _BaseInFile, _IgnoreFeatsFile, _BaseOutFile, []).
regulus2nuance_for_multiple_grammars1([Tag | Tags], BaseInFile, IgnoreFeatsFile, BaseOutFile, [OutNuanceFile | OutNuanceFiles]) :-
regulus2nuance_for_multiple_grammars2(Tag, BaseInFile, IgnoreFeatsFile, BaseOutFile, OutNuanceFile),
!,
regulus2nuance_for_multiple_grammars1(Tags, BaseInFile, IgnoreFeatsFile, BaseOutFile, OutNuanceFiles).
regulus2nuance_for_multiple_grammars2(Tag, BaseInFile, IgnoreFeatsFile, BaseOutFile, OutFile) :-
safe_trimcore,
format('~N~n==========================================================================~n', []),
format('~N~nCompiling grammar for tag "~w"~n~n', [Tag]),
add_tag_to_files_in_list([BaseInFile, BaseOutFile], Tag, [InFile, OutFile]),
regulus2nuance([InFile, IgnoreFeatsFile], Tag, OutFile),
!.
| TeamSPoon/logicmoo_workspace | packs_sys/logicmoo_nlu/ext/regulus/Prolog/regulus2nuance.pl | Perl | mit | 2,844 |
from django.conf.urls import url
from . import views
app_name = 'core'
urlpatterns = [
url(r'^$', views.Home.as_view(), name='home'),
]
| klashxx/PyConES2017 | web/sysgate/apps/core/urls.py | Python | mit | 143 |
'use strict';
var _ = require('lodash');
var Team = require('./team.model');
// Get list of teams
exports.index = function(req, res) {
Team.find(function (err, teams) {
if(err) { return handleError(res, err); }
return res.json(200, teams);
});
};
// Get a single team
exports.show = function(req, res) {
Team.findOne({sfvId: req.params.id}, function (err, team) {
if(err) { return handleError(res, err); }
if(!team) { return res.send(404); }
return res.json(team);
});
};
// Creates a new team in the DB.
exports.create = function(req, res) {
Team.create(req.body, function(err, team) {
if(err) { return handleError(res, err); }
return res.json(201, team);
});
};
// Updates an existing team in the DB.
exports.update = function(req, res) {
if(req.body._id) { delete req.body._id; }
Team.findById(req.params.id, function (err, team) {
if (err) { return handleError(res, err); }
if(!team) { return res.send(404); }
var updated = _.merge(team, req.body);
updated.save(function (err) {
if (err) { return handleError(res, err); }
return res.json(200, team);
});
});
};
// Deletes a team from the DB.
exports.destroy = function(req, res) {
Team.findById(req.params.id, function (err, team) {
if(err) { return handleError(res, err); }
if(!team) { return res.send(404); }
team.remove(function(err) {
if(err) { return handleError(res, err); }
return res.send(204);
});
});
};
function handleError(res, err) {
return res.send(500, err);
} | patrickstubner/team-analyzer | server/api/team/team.controller.js | JavaScript | mit | 1,548 |
# Email Resource
A [Concourse](http://concourse-ci.org) resource that sends emails.
## Getting started
Add the following [Resource Type](https://concourse-ci.org/resource-types.html) to your Concourse pipeline
```yaml
resource_types:
- name: email
type: docker-image
source:
repository: pcfseceng/email-resource
```
Look at the [demo pipeline](https://github.com/pivotal-cf/email-resource/blob/master/example/demo-pipeline.yml) for a complete example.
This resource acts as an SMTP client, using `PLAIN` auth over TLS. So you need an SMTP server that supports all that.
For development, we've been using [Amazon SES](https://aws.amazon.com/ses/) with its [SMTP support](http://docs.aws.amazon.com/ses/latest/DeveloperGuide/smtp-credentials.html)
## Source Configuration
### `source`:
#### Parameters
Within smtp:
* `host`: *Required.* SMTP Host name
* `port`: *Required.* SMTP Port, must be entered as a string
* `anonymous`: *Optional.* Whether or not to require credential. true/false are valid options. If omitted default is false
* `username`: *Required, Conditionally.* Username to authenticate with. Ignored if `anonymous: true`
* `password`: *Required, Conditionally.* Password to authenticate with. Ignored if `anonymous: true`
* `skip_ssl_validation`: *Optional.* Whether or not to skip ssl validation. true/false are valid options. If omitted default is false
* `ca_cert`: *Optional.* Certificates content to verify servers with custom certificates. Only considered if `skip_ssl_validation` is `false`.
* `host_origin`: *Optional.* Host to send `Hello` from. If not provided `localhost` is used
* `login_auth`: *Optional.* This will enable the flag to use Login Auth for authenticated. true/false are valid options. If omitted default is false
Within source:
* `from`: *Required.* Email Address to be sent from.
* `to`: *Required.Conditionally.* Array of email addresses to send email to. Not required if job params contains a file reference that has to recipients.
* `cc`: *Optional* Array of email addresses to cc send email to.
* `bcc`: *Optional* Array of email addresses to bcc send email to.
An example source configuration is below.
```yaml
resources:
- name: send-an-email
type: email
source:
smtp:
host: smtp.example.com
port: "587" # this must be a string
username: a-user
password: my-password
from: [email protected]
to: [ "[email protected]", "[email protected]" ] #optional if `params.additional_recipient` is specified
```
An example source configuration is below supporting sending email when anonymous is permitted.
```yaml
resources:
- name: send-an-email
type: email
source:
smtp:
host: smtp.example.com
port: "587" # this must be a string
anonymous: true
from: [email protected]
to: [ "[email protected]", "[email protected]" ]
```
An exmaple using custom certificates:
```yaml
resources:
- name: send-an-email
type: email
source:
smtp:
host: smtp.example.com
port: "587" # this must be a string
anonymous: true
ca_cert: |
-----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE-----
from: [email protected]
to: [ "[email protected]", "[email protected]" ]
```
Note that `to` is an array, and that `port` is a string.
If you're using `fly configure` with the `--load-vars-from` (`-l`) substitutions, every `{{ variable }}`
[automatically gets converted to a string](http://concourse-ci.org/fly.html).
But for literals you need to surround it with quotes.
## Behavior
This is an output-only resource, so `check` and `in` actions are no-ops.
### `out`: Send an email
#### Parameters
* `headers`: *Optional.* Path to plain text file containing additional mail headers
* `subject`: *Optional.* Path to plain text file containing the subject. Either `subject` or `subject_text` required. `subject_text` takes precedence.
* `subject_text`: *Optional.* The subject as text. Either `subject` or `subject_text` required. `subject_text` takes precedence.
* `body`: *Optional.* Path to file containing the email body. Either `body` or `body_text` required. `body_text` takes precedence.
* `body_text`: *Optional.* The email body as text. Either `body` or `body_text` required. `body_text` takes precedence.
* `send_empty_body`: *Optional.* If true, send the email even if the body is empty (defaults to `false`).
* `to`: *Optional.* Path to plain text file containing recipients which could be determined at build time. You can run a task before, which figures out the email of the person who committed last to a git repository (`git -C $source_path --no-pager show $(git -C $source_path rev-parse HEAD) -s --format='%ae' > output/email.txt`). This file can contain `,` delimited list of email address if wanting to send to multiples.
* `to_text`: *Optional.* The `,` delimited list of to addresses. `to_text` appends to any `to` in params or source
* `cc`: *Optional.* Path to plain text file containing recipients which could be determined at build time. This file can contain `,` delimited list of email address if wanting to send to multiples.
* `cc_text`: *Optional.* The `,` delimited list of cc addresses. `cc_text` appends to any `cc` in params or source
* `bcc`: *Optional.* Path to plain text file containing recipients which could be determined at build time. This file can contain `,` delimited list of email address if wanting to send to multiples.
* `bcc_text`: *Optional.* The `,` delimited list of bcc addresses. `bcc_text` appends to any `bcc` in params or source
* `debug`: *Optional.* If set to `true` additional information send to stderr
* `attachment_globs:` *Optional.* If provided will attach any file to the email that matches the glob path(s)
For example, a build plan might contain this:
```yaml
- put: send-an-email
params:
subject: generated-subject-file
body: generated-body-file
```
For example, a build plan might contain this if using generated list of recipient(s):
```yaml
- put: send-an-email
params:
subject: generated-subject-file
body: generated-body-file
to: generated-to-file
```
You can use the values below in any of the source files or text properties to access the corresponding metadata made available by concourse, as documented [here](https://concourse-ci.org/implementing-resource-types.html)
* `${BUILD_ID}`
* `${BUILD_NAME}`
* `${BUILD_JOB_NAME}`
* `${BUILD_PIPELINE_NAME}`
* `${ATC_EXTERNAL_URL}`
* `${BUILD_TEAM_NAME}`
For example:
```yaml
- put: send-an-email
params:
subject_text: "Build finished: ${BUILD_PIPELINE_NAME}/${BUILD_JOB_NAME}/${BUILD_NAME}"
body_text: "Build finished: ${ATC_EXTERNAL_URL}/teams/main/pipelines/${BUILD_PIPELINE_NAME}/jobs/${BUILD_JOB_NAME}/builds/${BUILD_NAME}"
```
#### HTML Email
To send HTML email set the `headers` parameter to a file containing the following:
```
MIME-version: 1.0
Content-Type: text/html; charset="UTF-8"
```
## Build from the source
`email-resource` is written in [Go](https://golang.org/).
To build the binary yourself, follow these steps:
* Install `Go`.
* Install [Glide](https://github.com/Masterminds/glide), a dependency management tool for Go.
* Clone the repo:
- `mkdir -p $(go env GOPATH)/src/github.com/pivotal-cf`
- `cd $(go env GOPATH)/src/github.com/pivotal-cf`
- `git clone [email protected]:pivotal-cf/email-resource.git`
* Install dependencies:
- `cd email-resource`
- `glide install`
- `go build -o bin/check check/cmd/*.go`
- `go build -o bin/in in/cmd/*.go`
- `go build -o bin/out out/cmd/*.go`
To cross compile, set the `$GOOS` and `$GOARCH` environment variables.
For example: `GOOS=linux GOARCH=amd64 go build`.
## Testing
To run the unit tests, use `go test $(glide nv)`.
| pivotal-cf/email-resource | README.md | Markdown | mit | 7,827 |
<?php namespace Correa\Geradores;
use Correa\Geradores\Filesystem\Filesystem;
use Correa\Geradores\Compilers\TemplateCompiler;
use Correa\Geradores\Syntax\AddToTable;
use Correa\Geradores\Syntax\CreateTable;
use Correa\Geradores\Syntax\DroppedTable;
use Correa\Geradores\Syntax\RemoveFromTable;
use Exception;
class SchemaCreator {
/**
* @var Filesystem\Filesystem
*/
private $file;
/**
* @var Compilers\TemplateCompiler
*/
private $compiler;
/**
* @param Filesystem $file
* @param TemplateCompiler $compiler
*/
function __construct(Filesystem $file, TemplateCompiler $compiler)
{
$this->file = $file;
$this->compiler = $compiler;
}
/**
* Build the string for the migration file "up" method
*
* @param array $migrationData
* @param array $fields
* @throws Exception
* @return mixed|string
*/
public function up(array $migrationData, array $fields = [])
{
$this->guardAction($migrationData['action']);
$method = $migrationData['action'] . 'Factory';
return $this->$method($migrationData, $fields);
}
/**
* Build the string for the migration file "down" method
*
* @param array $migrationData
* @param array $fields
* @throws Exception
* @return array|mixed|string
*/
public function down(array $migrationData, $fields = [])
{
$this->guardAction($migrationData['action']);
$opposites = [
'delete' => 'create',
'create' => 'delete',
'remove' => 'add',
'add' => 'remove'
];
$method = $opposites[$migrationData['action']] . 'Factory';
return $this->$method($migrationData, $fields);
}
/**
* @param $action
* @throws Exception
* @internal param array $migrationData
*/
protected function guardAction($action)
{
if (!in_array($action, ['create', 'add', 'remove', 'delete']))
{
throw new InvalidMigrationName('Please rewrite your migration name to begin with "create", "add", "remove", or "delete."');
}
}
/**
* @param $migrationData
* @param $fields
* @return mixed
*/
protected function createFactory($migrationData, $fields)
{
return (new CreateTable($this->file, $this->compiler))->create($migrationData, $fields);
}
/**
* @param $migrationData
* @param $fields
* @return mixed
*/
protected function addFactory($migrationData, $fields)
{
return (new AddToTable($this->file, $this->compiler))->add($migrationData, $fields);
}
/**
* @param $migrationData
* @param $fields
* @return mixed
*/
protected function removeFactory($migrationData, $fields)
{
return (new RemoveFromTable($this->file, $this->compiler))->remove($migrationData, $fields);
}
/**
* @param $migrationData
* @param $fields
* @return string
*/
protected function deleteFactory($migrationData, $fields)
{
return (new DroppedTable)->drop($migrationData['table']);
}
} | rscorrea/Geradoges | src/Correa/Geradores/SchemaCreator.php | PHP | mit | 3,192 |
<section class="grey lighten-5 valign-wrapper content-container">
<div class="container valign">
<div class="section pt-section" data-name="About" id="about-me">
<div class="row">
<p class="col m8 l8 flow-text">Hi, my name is Matt. I'm a Frontend Developer in the <span class="special">North Dallas</span> area looking for a great place to officially start my new career. I'm also a husband, a gamer, a corgi and cat dad, a podcast junkie and a lover of good beer, coffee, tea and beverages in general. I <span class="special">love</span> to code and I love placing most of my logic on the frontend using awesome frameworks like <span class="special">Angular</span>.</p>
<img class="responsive-img circle col m4 l3 offset-l1 " src="./app/assets/img/aboutMe.jpg" alt="">
<p class="col m12 flow-text">If you'd like to talk code, share insights, tell me about a great podcast or cool meetup group, talk with me about potential work opportunities, or just say "hi" I would love to hear from you. </p>
</div>
<div class="row center">
<a du-smooth-scroll href="#contact" id="download-button" class="btn-large waves-effect waves-light amber accent-4" target="_blank">contact me</a>
</div>
</div>
</div>
</section> | mcm0027/portfolioRedesign | app/views/aboutMe.html | HTML | mit | 1,345 |
import { GameRenderer } from "render/GameRenderer";
import { MenuManager } from "menu/MenuManager";
import { MainMenu } from "menu/MainMenu";
import { Display } from "Display";
import { Input } from "Input";
export class Game {
public static GAME_RES_X = 640;
public static GAME_RES_Y = 480;
private static gameInstance: Game;
public inputSystem: Input;
public gameRenderer: GameRenderer;
public menuManager: MenuManager;
public display: Display;
public init(): void {
// Resolve canvas element
let element: HTMLElement = document.getElementById("webhexagon-canvas");
if(!(element instanceof HTMLCanvasElement)) {
throw new Error("Could not resolve game canvas element: #webhexagon-canvas");
}
// Create display
this.display = new Display(element as HTMLCanvasElement);
this.display.resize(Game.GAME_RES_X, Game.GAME_RES_Y);
// Open display (init stuff)
this.display.open();
// Create game renderer
this.gameRenderer = new GameRenderer(this.display.getGLContext());
// Create menu manager
this.menuManager = new MenuManager();
// Create input
this.inputSystem = new Input();
this.inputSystem.bindKeyInputChannel(this.display.getKeyInputChannel());
}
public start(): void {
// Focus game canvas
this.display.focus();
// Open main menu
this.menuManager.openMenu(new MainMenu());
}
public frame(): void {
// Render frame
this.gameRenderer.renderFrame();
}
public run(): void {
// Init game
this.init();
// Start game
this.start();
// Request first frame
let mainloop = () => {
this.frame();
window.requestAnimationFrame(mainloop);
};
window.requestAnimationFrame(mainloop);
}
public static main(): void {
// Instantiate game
this.gameInstance = new Game();
// Run game
this.gameInstance.run();
}
public static instance(): Game {
return this.gameInstance;
}
}
| coffeenotfound/webhexagon | src/Game.ts | TypeScript | mit | 1,983 |
#include <TestScene.hpp>
#include <Scenes.hpp>
#include <UtH/Platform/JavaFunctions.hpp>
#include <UtH/Platform/GooglePlayGameServices.hpp>
using namespace uth;
namespace
{
enum Layers
{
Default,
Other
};
}
TestScene::TestScene()
{}
TestScene::~TestScene()
{}
bool TestScene::Init()
{
// Objects
// First
{
auto child = AddChild<GameObject>();
child->AddComponent(test = new Sprite(pmath::Vec4(1,0,0,1),pmath::Vec2(128,128)));
}
// Second (ParticleSystem)
{
ParticleTemplate pt;
pt.SetLifetime(-1.f);
pt.SetSpeed(10.f, 150.f);
pt.SetTexture(uthRS.LoadTexture("particle.tga"));
auto ps = AddChild(new ParticleSystem(100));
ps->SetTemplate(pt);
Affector* aff = new Affector();
aff->SetParticleInitFunc([](Particle& particle, const ParticleTemplate& pTemplate)
{
pmath::Vec2 tvec(Randomizer::InsideCircle());
tvec /= static_cast<float>(tvec.length());
particle.direction = Randomizer::GetFloat(pTemplate.minSpeed, pTemplate.maxSpeed) * tvec;
});
aff->SetParticleUpdateFunc([](Particle& part, const ParticleTemplate& ptemp, float dt)
{
part.Move(part.direction * dt);
});
ps->AddAffector(aff);
ps->SetEmitProperties(true, 0.05f, 0.1f, 1, 5);
}
javaFunc::Vibrate(1000);
return true;
}
bool TestScene::DeInit()
{
return true;
}
void TestScene::Update(float dt)
{
if (uthInput.Common == uth::InputEvent::TAP)
{
javaFunc::Vibrate(2000);
//std::string location = uthGPGS.gps.GetCurrentLocation();
//WriteLog("Current location: %s", location.c_str());
GooglePlayGameServices::Location location = uthGPGS.gps.GetCurrentLocation();
WriteLog("Accuracy: %f", uthGPGS.gps.GetAccuracy());
WriteLog("ConvLat: %f", location.loc_latitude);
WriteLog("ConvLong: %f", location.loc_longitude);
WriteLog("ConvAcc: %f", location.loc_accuracy);
WriteLog("ConvTime: %s", location.device_time_since_reboot.c_str());
}
static float a = 0;
static float time = 0;
time += dt;
if (time < 1)
a = 1 - time;
else if (time < 2)
a = time - 1;
else
time = 0;
pmath::Vec4 color = test->GetColor();
color.a = a;
test->SetColor(color);
Scene::Update(dt);
}
//void TestScene::Draw(RenderTarget& target, RenderAttributes attributes)
//{
// Scene::Draw(target, attributes);
//}
| Eracage/ChristmasCarol | vs2013/TestProject/source/TestScene.cpp | C++ | mit | 2,425 |
import zlib as _zlib
from .abc import Codec
from .compat import ndarray_copy, ensure_contiguous_ndarray
class Zlib(Codec):
"""Codec providing compression using zlib via the Python standard library.
Parameters
----------
level : int
Compression level.
"""
codec_id = 'zlib'
def __init__(self, level=1):
self.level = level
def encode(self, buf):
# normalise inputs
buf = ensure_contiguous_ndarray(buf)
# do compression
return _zlib.compress(buf, self.level)
# noinspection PyMethodMayBeStatic
def decode(self, buf, out=None):
# normalise inputs
buf = ensure_contiguous_ndarray(buf)
if out is not None:
out = ensure_contiguous_ndarray(out)
# do decompression
dec = _zlib.decompress(buf)
# handle destination - Python standard library zlib module does not
# support direct decompression into buffer, so we have to copy into
# out if given
return ndarray_copy(dec, out)
| zarr-developers/numcodecs | numcodecs/zlib.py | Python | mit | 1,052 |
<!DOCTYPE html>
<html lang="en">
<head>
<title>Lunchbox</title>
<!-- META TAGS -->
<meta name="description" content="tktktk">
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<link rel="shortcut icon" href="http://cdn.thesn.net/20151007QJgFVV_Dcg/dist/img/favicons/favicon.ico" />
<!-- FONTS -->
<!-- Fonts -->
<script type="text/javascript" src="../js/webfont.min.js?1492105711"></script>
<script>
// Define your web fonts here.
// See https://github.com/typekit/webfontloader for documentation
</script>
<!-- CSS -->
<link rel="stylesheet" type="text/css" href="../css/app.min.css?1492105711" />
<link rel="stylesheet" type="text/css" href="../css/embeddable.min.css?1492105711" />
</head>
<body class="embeddable">
<a class="sr-only" href="#content">Skip To Content</a>
<header>
<div class="nav-links">
<a href="../quotable/index.html" >Quotable</a>
<a href="../factlist/index.html" >Factlist</a>
<a href="../waterbug/index.html" >Waterbug</a>
<a href="../embeddable/index.html" class="active" >Embeddable</a>
</div>
<a href="../index.html" class="home-link">
<h1>Lunchbox</h1>
</a>
</header>
<section id="content">
<div class="container-fluid">
<div class="wrapper">
<div class="canvas-wrapper">
<p>Copy and paste this code into a Safe Embed</p>
<div class="canvas-cell">
<textarea class="form-control" readonly rows="20" id="embeddable-output"></textarea>
</div>
</div>
<div class="form controls">
<div class="controls-wrapper">
<form autocomplete="off" id="embeddable-form">
<div class="form-group">
<label class="control-label">Embeddable Type</label>
<select class="form-control embeddable-type">
<option value="quote">Pull Quote</option>
<option value="poll">Poll</option>
<option value="media-side">Media (Sidebar)</option>
<option value="random">Rando HTML</option>
</select>
</div>
<div class="quote-container hidden">
<div class="form-group">
<label class="control-label">Quote Text</label>
<textarea rows="5" cols="20" class="form-control" id="quote-quote"></textarea>
</div>
<div class="form-group">
<label class="control-label">Quote Atribution</label>
<input type="text" class="form-control" id="quote-atribution" />
</div>
</div>
<div class="form-group poll-container hidden">
<div class="form-group">
<label class="control-label">Poll ID</label>
<input type="text" class="form-control" id="poll-id" />
<p class="help-block">Grab the poll ID by opening the poll in Gryphon and copying the number at the end of the URL</p>
</div>
</div>
<div class="form-group media-side-container hidden">
<div class="form-group">
<label class="control-label">Media Link URL</label>
<input type="text" class="form-control" id="media-side-url" />
<p class="help-block">Upload your photo to Gryphon. Then open it and click View > Preview File. Copy/paste that URL here.</p>
</div>
<div class="form-group">
<label class="control-label">Media Cutline</label>
<input type="text" class="form-control" id="media-side-cutline" />
<p class="help-block">Enter a short description or promo here</p>
</div>
<div class="form-group">
<label class="control-label">Clickthrough URL for Image and Cutline</label>
<input type="text" class="form-control" id="media-side-clickthrough" />
<p class="help-block">Enter the URL the image and cutline should click to</p>
</div>
</div>
<!-- <div class="form-group media-full-container hidden">
media-full
</div> -->
<div class="form-group random-container hidden">
<div class="form-group">
<label class="control-label">Embed HTML</label>
<textarea rows="5" cols="20" class="form-control" id="random-content"></textarea>
</div>
</div>
</form>
</div>
</div>
</div>
<script type="embeddable-template" id="quote-template">
<div class="article-embed pull-quote">
<span class="pull-quote-body">"%quote%"</span>
<hr/>
<span class="pull-quote-byline">%attribution%</span>
</div>
</script>
<script type="embeddable-template" id="poll-template">
<div class="article-embed opinion-box">
[script "http://statenews.com/poll/embed.js?id=%id%"]
<div id="gpoll-%id%" data-poll="%id%"></div>
</div>
</script>
<script type="embeddable-template" id="media-side-template">
<div class="article-embed gallery-embed">
<a href="%clickthrough%"><img src="%url%"></a>
<span><a href="%clickthrough%">%cutline%</a></span>
</div>
</script>
<script type="embeddable-template" id="random-template">
<div class="article-embed">
%content%
</div>
</script>
</div>
</section>
<script type="text/javascript" src="../js/app-footer.min.js?1492105712"></script>
<script type="text/javascript" src="../js/embeddable.min.js?1492105713"></script>
</body>
</html> | thesnews/lunchbox | www/embeddable/index.html | HTML | mit | 6,243 |
module PhotosHelper
def item_form_column(record, input_name)
file_field :record, :item
end
def item_column(record)
image_tag record.item.url(:thumb)
end
def property_id_form_column(record, input_name)
select(:record, :property_id, Property.all.collect{|p| [p.name, p.id]}, {:include_blank => 'Select One'})
end
def property_id_column(record)
if record.property_id.blank?
""
else
h(Property.find(record.property_id).name)
end
end
end
| cjwilliams/seiber | app/helpers/photos_helper.rb | Ruby | mit | 494 |
#
# Copyright (c) 2008-2021 the Urho3D project.
#
# 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.
#
# Get Urho3D library revision number
# Use the same commit-ish used by CI server to describe the repository
if (DEFINED ENV{TRAVIS_COMMIT})
set (ARG $ENV{TRAVIS_COMMIT})
elseif (DEFINED ENV{APPVEYOR})
set (ARG $ENV{APPVEYOR_REPO_COMMIT})
else ()
set (ARG --dirty)
endif ()
execute_process (COMMAND git describe ${ARG} RESULT_VARIABLE GIT_EXIT_CODE OUTPUT_VARIABLE LIB_REVISION ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE)
if (NOT GIT_EXIT_CODE EQUAL 0)
# No GIT command line tool or not a GIT repository
set (LIB_REVISION Unversioned)
endif ()
if (FILENAME)
# Output complete revision number to a file
file (WRITE ${FILENAME} "const char* revision=\"${LIB_REVISION}\";\n")
else ()
# Output just major.minor.patch number to stdout
string (REGEX MATCH "[^.]+\\.[^-]+" VERSION ${LIB_REVISION}) # Assume release tag always has major.minor format with possible pre-release identifier
if (VERSION)
string (REGEX MATCH "${VERSION}-([A-Z]+)" PRE_ID ${LIB_REVISION}) # Workaround as CMake's regex does not support look around
if (PRE_ID)
set (VERSION ${VERSION}-${CMAKE_MATCH_1})
endif ()
string (REGEX MATCH "${VERSION}-([^-]+)" PATCH ${LIB_REVISION}) # Subsequent commits count after a release tag is treated as patch number
if (PATCH)
set (VERSION ${VERSION}.${CMAKE_MATCH_1})
else ()
set (VERSION ${VERSION}.0)
endif ()
else ()
set (VERSION 0.0.0)
endif ()
execute_process (COMMAND ${CMAKE_COMMAND} -E echo ${VERSION})
endif ()
| orefkov/Urho3D | cmake/Modules/GetUrhoRevision.cmake | CMake | mit | 2,702 |
'use strict';
var config = require('../../.project/.config'),
gulp = require('gulp'),
del = require('del'),
gulpGalen = require('gulp-galenframework');
module.exports = function() {
gulp.add('test:galen', function(done) {
del.sync([config.galenReport], { force: true });
gulp.src(config.destStyleguidePath + '/**/*.test')
.pipe(gulpGalen.test({
'htmlreport': config.destGalenReportLayout,
//'parallel-tests': 3,
'properties': {
'galen.default.browser': 'chrome',
'galen.use.fail.exit.code': false,
'webdriver.chrome.driver': './node_modules/chromedriver/lib/chromedriver/chromedriver.exe',
'webdriver.gecko.driver': './webdrivers/geckodriver.exe',
'webdriver.edge.driver': './webdrivers/MicrosoftWebDriver.exe',
'webdriver.ie.driver': './node_modules/iedriver/lib/iedriver64/IEDriverServer.exe'
},
'cwd': '.'
}, done()));
});
};
| websitejs/websitejs | gulp/tasks/test-galen.js | JavaScript | mit | 1,096 |
FROM alpine:3.4
#see https://github.com/RobLoach/docker-composer/blob/master/base/php5-alpine/Dockerfile
MAINTAINER Yuriy Prokopets <[email protected]>
# Environments
ENV TIMEZONE Europe/Kiev
RUN set -x \
&& addgroup -g 82 -S www-data \
&& adduser -u 82 -D -S -G www-data www-data
# Let's roll
RUN apk update && \
apk upgrade && \
apk add --update tzdata && \
cp /usr/share/zoneinfo/${TIMEZONE} /etc/localtime && \
echo "${TIMEZONE}" > /etc/timezone && \
apk add --update \
curl \
wget \
ca-certificates \
php5-ctype \
php5-phar \
php5-zip \
php5-bz2 \
php5-apcu \
php5-curl \
php5-gd \
php5-iconv \
php5-imagick \
php5-json \
php5-intl \
php5-mcrypt \
php5-opcache \
php5-openssl \
php5-pdo \
php5-pdo_mysql \
php5-mysqli \
php5-xml \
php5-dom \
php5-zlib
#memcached
RUN \
wget -q -O /etc/apk/keys/sgerrand.rsa.pub https://raw.githubusercontent.com/sgerrand/alpine-pkg-php5-memcached/master/sgerrand.rsa.pub && \
wget https://github.com/sgerrand/alpine-pkg-php5-memcached/releases/download/2.2.0-r0/php5-memcached-2.2.0-r0.apk && \
apk add php5-memcached-2.2.0-r0.apk
RUN sed -i "s|;*date.timezone =.*|date.timezone = ${TIMEZONE}|i" /etc/php5/php.ini
###############
RUN apk add php5-cli php5-posix git openssh
###############
RUN rm -rf /var/cache/apk/* && rm -rf /tmp/*
# Register the COMPOSER_HOME environment variable
ENV COMPOSER_HOME /composer
# Add global binary directory to PATH and make sure to re-export it
ENV PATH /composer/vendor/bin:$PATH
# Memory Limit
ENV PHP_MEMORY_LIMIT 2048M
RUN sed -i "s|;*memory_limit =.*|memory_limit = ${PHP_MEMORY_LIMIT}|i" /etc/php5/php.ini
# Setup the Composer installer
RUN curl -o /tmp/composer-setup.php https://getcomposer.org/installer \
&& curl -o /tmp/composer-setup.sig https://composer.github.io/installer.sig \
&& php -r "if (hash('SHA384', file_get_contents('/tmp/composer-setup.php')) !== trim(file_get_contents('/tmp/composer-setup.sig'))) { unlink('/tmp/composer-setup.php'); echo 'Invalid installer' . PHP_EOL; exit(1); }"
# Install Composer
ENV COMPOSER_VERSION 1.2.0
RUN php /tmp/composer-setup.php --no-ansi --install-dir=/usr/local/bin --filename=composer --version=${COMPOSER_VERSION} && rm -rf /tmp/composer-setup.php
# Display version information.
RUN composer --version
RUN chown -R www-data:www-data /composer/cache
WORKDIR /data/www/site
COPY docker-entrypoint.sh /usr/local/bin/
RUN chmod +x /usr/local/bin/docker-entrypoint.sh
RUN ln -s /usr/local/bin/docker-entrypoint.sh /entrypoint.sh # backwards compat
USER www-data
CMD ["-V"]
ENTRYPOINT ["/entrypoint.sh"] | madman/tree | docker/composer/Dockerfile | Dockerfile | mit | 2,995 |
{% for director in director_dislike %}
<li class="directors" class="llistItemMovie">
<div class="listImage">
<div class="profile" style="background: url(/var/covers/small/10/100.jpg);">
<h2 class="director-name">
<a href="/info/director/{{director.code}}">{{ director.name }}</a>
{% if director.en_name != '' %}
({{ director.en_name }})
{% endif %}
<!--<a href="{{ movie.detail_url }}" title ="{{ movie.title1 }}">{{ movie.title1 }} ({{ movie.title2 }} )</a>-->
</h2>
{% if director.thumb_url %}
<img src="{{ director.thumb_url }}" onerror="directorThumbError(this);"/>
{% else %}
<img src="http://static.naver.net/movie/2012/06/dft_img120x150.png" width="111" height="139"/>
{% endif %}
{% if director.dm_list != False %}
<h3 class="major-work">대표작</h3>
<!--<div class="small_list">-->
<ol class="movie_thumb_list" id="left_thumb_list">
{% for am in director.dm_list %}
<li class="small_thumb_list_item" data-title="{{ am.title1 }}" style="display: list-item;">
<!--<div class="small_item">-->
{% if am.small_liked %}
<div class="viewport user_liked">
{% elif am.small_disliked %}
<div class="viewport user_disliked">
{% else %}
<div class="viewport">
{% endif %}
<a href="/info/movie/{{ am.code }}">
<span class="dark-background">{{ am.title1 }}</span>
<img src="{{ am.poster_url }}?type=n77_110_2" width="50" height="68"/>
</a>
</div>
</li>
{% endfor %}
<!--</div>-->
</ol>
{% else %}
<br/>
{% endif %}
{% if drector.like %}
<a href="#" class="director_liked" id="{{ director.code }}"><span></span></a>
{% else %}
<a href="#" class="director_like" id="{{ director.code }}"><span></span></a>
{% endif %}
<a href="#" class="director_like_count" id="{{ director.code }}">{{ director.like_count }}</a>
{% if director.dislike %}
<a href="#" class="director_disliked" id="{{ director.code }}"><span></span></a>
{% else %}
<a href="#" class="director_dislike" id="{{ director.code }}"><span></span></a>
{% endif %}
<a href="#" class="director_dislike_count" id="{{ drector.code }}">{{ director.dislike_count }}</a>
</div>
</div>
{% endfor %}
| carpedm20/movieduk | templates/core/director_dislike.html | HTML | mit | 2,667 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="author" content="Thiago Moraes">
<meta name="description" content="Thiago Moraes' personal website">
<meta name="keywords" content="blog,developer,personal">
<meta property="og:site_name" content="Thiago Moraes">
<meta property="og:title" content="Thiago Moraes">
<meta property="og:description" content="Thiago Moraes' personal website">
<meta property="og:type" content="website">
<meta property="og:url" content="https://thiago.cmoraes.com/">
<meta property="og:image" content="https://thiago.cmoraes.comimages/tn.png">
<meta name="twitter:card" content="summary">
<meta name="twitter:site" content="https://thiago.cmoraes.com/">
<meta name="twitter:image" content="https://thiago.cmoraes.comimages/tn.png">
<base href="https://thiago.cmoraes.com/">
<title>Thiago Moraes</title>
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-144185554-1"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag() { dataLayer.push(arguments); }
gtag('js', new Date());
gtag('config', 'UA-144185554-1');
</script>
<script>
!function (f, b, e, v, n, t, s) {
if (f.fbq) return; n = f.fbq = function () {
n.callMethod ?
n.callMethod.apply(n, arguments) : n.queue.push(arguments)
};
if (!f._fbq) f._fbq = n; n.push = n; n.loaded = !0; n.version = '2.0';
n.queue = []; t = b.createElement(e); t.async = !0;
t.src = v; s = b.getElementsByTagName(e)[0];
s.parentNode.insertBefore(t, s)
}(window, document, 'script',
'https://connect.facebook.net/en_US/fbevents.js');
fbq('init', '130757830970559');
fbq('track', 'PageView');
</script>
<noscript><img height="1" width="1" style="display:none"
src="https://www.facebook.com/tr?id=130757830970559&ev=PageView&noscript=1" /></noscript>
<link rel="canonical" href="https://thiago.cmoraes.com/">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Fira+Mono:400,700">
<link rel="stylesheet" href="https://thiago.cmoraes.com/css/normalize.min.css">
<link rel="stylesheet" href="https://thiago.cmoraes.com/css/style.min.css">
<link rel="icon" type="image/png" href="https://thiago.cmoraes.com/images/favicon-32x32.png" sizes="32x32">
<link rel="icon" type="image/png" href="https://thiago.cmoraes.com/images/favicon-16x16.png" sizes="16x16">
<link rel="alternate" href="https://thiago.cmoraes.com/index.xml" type="application/rss+xml" title="Thiago Moraes">
<link href="https://thiago.cmoraes.com/index.xml" rel="feed" type="application/rss+xml" title="Thiago Moraes" />
<meta name="generator" content="Hugo 0.74.1" />
</head>
<body class="">
<main class="wrapper">
<nav class="navigation">
<section class="container">
<a class="navigation-title" href="/">Thiago Moraes</a>
<input type="checkbox" id="menu-control"/>
<label class="menu-mobile float-right " for="menu-control">
<span class="btn-mobile float-right ">☰</span>
<ul class="navigation-list">
<li class="navigation-item align-center ">
<a class="navigation-link" href="https://thiago.cmoraes.com/about">About</a>
</li>
</ul>
</label>
</section>
</nav>
<div class="content">
<section class="container centered">
<div class="about">
<div class="avatar"><img src="https://thiago.cmoraes.com/images/headshot-square.jpg" alt="avatar"></div>
<h1>Thiago Moraes</h1>
<p>Brazilian engineer based in the Bay Area.</p>
<ul class="social-list">
<li class="social-item">
<a href="https://github.com/thiagocmoraes/" aria-label="Github" >
Github
</a>
</li>
<li class="social-item">
<a href="https://www.facebook.com/thiago.camposmoraes" aria-label="Facebook" >
Facebook
</a>
</li>
<li class="social-item">
<a href="https://www.linkedin.com/in/thiagocmoraes/" aria-label="LinkedIn" >
LinkedIn
</a>
</li>
<li class="social-item">
<a href="https://twitter.com/thiagocmoraes/" aria-label="Twitter" >
Twitter
</a>
</li>
</ul>
</div>
</section>
</div>
</main>
<script src="https://thiago.cmoraes.com/js/app.js"></script>
</body>
</html>
| thiagocmoraes/thiagocmoraes.github.com | index.html | HTML | mit | 4,829 |
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Fasterflect;
using Moonfish.Guerilla;
using Moonfish.Tags;
namespace Moonfish.Cache
{
public static class CacheExtensions
{
public static CacheKey GetKey( this ICache cache )
{
return Solution.Index.GetCacheKey( cache );
}
}
public interface ICache: IReadOnlyList<TagDatum>
{
TagDatum Add<T>( T item, string tagName ) where T : GuerillaBlock;
bool Contains<T>( T item ) where T : GuerillaBlock;
T Deserialize<T>( TagIdent ident ) where T: GuerillaBlock;
string GetStringValue( StringIdent ident );
};
public class TagCache : MemoryStream , ICache
{
Dictionary<TagIdent, GuerillaBlock> items = new Dictionary<TagIdent, GuerillaBlock>();
private List<TagDatum> tagDatums = new List<TagDatum>( );
public TagDatum Add<T>( T item, string tagName ) where T : GuerillaBlock
{
var attribute = (TagClassAttribute)item.GetType().Attribute(typeof(TagClassAttribute)) ??
(TagClassAttribute)
item.GetType().BaseType?.GetCustomAttributes(typeof(TagClassAttribute)).FirstOrDefault();
var tagDatum = new TagDatum
{
Class = attribute?.TagClass ?? TagClass.Empty,
Identifier = new TagIdent( ( short ) Count, ( short ) ~Count ),
Length = 0,
Path = tagName,
VirtualAddress = 0
};
tagDatums.Add( tagDatum );
items[tagDatum.Identifier] = item;
return tagDatum;
}
public bool Contains<T>( T item ) where T : GuerillaBlock
{
foreach ( var block in items.Values )
{
if ( block.Equals( item )) return true;
foreach ( var child in block.Children( ) )
{
if ( child.Equals( block ) ) return true;
}
}
return false;
}
public T Deserialize<T>( TagIdent ident ) where T : GuerillaBlock
{
return ( T ) items[ ident ];
}
public string GetStringValue( StringIdent ident )
{
return string.Empty;
}
public IDictionary<StringIdent, string> Strings { get; } = new Dictionary<StringIdent, string>();
public IEnumerator<TagDatum> GetEnumerator( )
{
return tagDatums.GetEnumerator( );
}
IEnumerator IEnumerable.GetEnumerator( )
{
return tagDatums.GetEnumerator();
}
public int Count
{
get { return tagDatums.Count; }
}
public TagDatum this[ int index ]
{
get { return tagDatums[ index ]; }
}
}
} | jacksoncougar/Moonfxsh | Moonfish/Cache/ICache.cs | C# | mit | 2,946 |
const explorerCli = require('../app/ui/setup');
const term = require('terminal-kit').terminal;
const setup = () => {
term.reinit();
term.height = 15;
explorerCli({
data: 'initial data'
});
};
describe('state', () => {
test('[s] should show the state', () => {
setup();
term.press('s');
expect(term.screen()).toEqual([
'{ ',
' "path": "", ',
' "map": "", ',
' "pick": "", ',
' "omit": "", ',
' "keys": false, ',
' "state": true, ',
' "offset": 0, ',
' "help": false, ',
' "rows": 15, ',
' "columns": 30, ',
' "showCache": false, ',
' "filename": "", ',
' "autosave": false ',
'} ',
]);
});
test('[s][s] should show the initial data (again)', () => {
setup();
term.press('s');
term.press('s');
expect(term.screen()).toEqual([
'"initial data" ',
' ',
' ',
' ',
' ',
' ',
' ',
' ',
' ',
' ',
' ',
' ',
' ',
' ',
' ',
]);
});
}); | andybry/explorer-cli | test/state.spec.js | JavaScript | mit | 1,967 |
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2022 *
* *
* 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. *
****************************************************************************************/
#include <modules/base/rendering/renderablemodel.h>
#include <modules/base/basemodule.h>
#include <openspace/documentation/documentation.h>
#include <openspace/documentation/verifier.h>
#include <openspace/engine/globals.h>
#include <openspace/rendering/renderengine.h>
#include <openspace/util/time.h>
#include <openspace/util/timeconversion.h>
#include <openspace/util/updatestructures.h>
#include <openspace/scene/scene.h>
#include <openspace/scene/lightsource.h>
#include <ghoul/io/model/modelgeometry.h>
#include <ghoul/filesystem/filesystem.h>
#include <ghoul/logging/logmanager.h>
#include <ghoul/misc/invariants.h>
#include <ghoul/misc/profiling.h>
#include <ghoul/opengl/openglstatecache.h>
#include <ghoul/opengl/programobject.h>
#include <filesystem>
#include <optional>
namespace {
constexpr const char* _loggerCat = "RenderableModel";
constexpr const char* ProgramName = "ModelProgram";
constexpr const int DefaultBlending = 0;
constexpr const int AdditiveBlending = 1;
constexpr const int PointsAndLinesBlending = 2;
constexpr const int PolygonBlending = 3;
constexpr const int ColorAddingBlending = 4;
std::map<std::string, int> BlendingMapping = {
{ "Default", DefaultBlending },
{ "Additive", AdditiveBlending },
{ "Points and Lines", PointsAndLinesBlending },
{ "Polygon", PolygonBlending },
{ "Color Adding", ColorAddingBlending }
};
constexpr openspace::properties::Property::PropertyInfo EnableAnimationInfo = {
"EnableAnimation",
"Enable Animation",
"Enable or disable the animation for the model if it has any"
};
constexpr const std::array<const char*, 12> UniformNames = {
"opacity", "nLightSources", "lightDirectionsViewSpace", "lightIntensities",
"modelViewTransform", "normalTransform", "projectionTransform",
"performShading", "ambientIntensity", "diffuseIntensity",
"specularIntensity", "opacityBlending"
};
constexpr openspace::properties::Property::PropertyInfo AmbientIntensityInfo = {
"AmbientIntensity",
"Ambient Intensity",
"A multiplier for ambient lighting."
};
constexpr openspace::properties::Property::PropertyInfo DiffuseIntensityInfo = {
"DiffuseIntensity",
"Diffuse Intensity",
"A multiplier for diffuse lighting."
};
constexpr openspace::properties::Property::PropertyInfo SpecularIntensityInfo = {
"SpecularIntensity",
"Specular Intensity",
"A multiplier for specular lighting."
};
constexpr openspace::properties::Property::PropertyInfo ShadingInfo = {
"PerformShading",
"Perform Shading",
"This value determines whether this model should be shaded by using the position "
"of the Sun."
};
constexpr openspace::properties::Property::PropertyInfo DisableFaceCullingInfo = {
"DisableFaceCulling",
"Disable Face Culling",
"Disable OpenGL automatic face culling optimization."
};
constexpr openspace::properties::Property::PropertyInfo ModelTransformInfo = {
"ModelTransform",
"Model Transform",
"This value specifies the model transform that is applied to the model before "
"all other transformations are applied."
};
constexpr openspace::properties::Property::PropertyInfo RotationVecInfo = {
"RotationVector",
"Rotation Vector",
"Rotation Vector using degrees"
};
constexpr openspace::properties::Property::PropertyInfo LightSourcesInfo = {
"LightSources",
"Light Sources",
"A list of light sources that this model should accept light from."
};
constexpr openspace::properties::Property::PropertyInfo DisableDepthTestInfo = {
"DisableDepthTest",
"Disable Depth Test",
"Disable Depth Testing for the Model."
};
constexpr openspace::properties::Property::PropertyInfo BlendingOptionInfo = {
"BlendingOption",
"Blending Options",
"Changes the blending function used to calculate the colors of the model with "
"respect to the opacity."
};
constexpr openspace::properties::Property::PropertyInfo EnableOpacityBlendingInfo = {
"EnableOpacityBlending",
"Enable Opacity Blending",
"Enable Opacity Blending."
};
struct [[codegen::Dictionary(RenderableModel)]] Parameters {
// The file or files that should be loaded in this RenderableModel. The file can
// contain filesystem tokens. This specifies the model that is rendered by
// the Renderable.
std::filesystem::path geometryFile;
enum class [[codegen::map(openspace::DistanceUnit)]] ScaleUnit {
Nanometer,
Micrometer,
Millimeter,
Centimeter,
Decimeter,
Meter,
Kilometer,
// Weird units
Thou,
Inch,
Foot,
Yard,
Chain,
Furlong,
Mile
};
// The scale of the model. For example if the model is in centimeters
// then ModelScale = Centimeter or ModelScale = 0.01
std::optional<std::variant<ScaleUnit, double>> modelScale;
// By default the given ModelScale is used to scale the model down,
// by setting this setting to true the model is instead scaled up with the
// given ModelScale
std::optional<bool> invertModelScale;
// Set if invisible parts (parts with no textures or materials) of the model
// should be forced to render or not.
std::optional<bool> forceRenderInvisible;
// [[codegen::verbatim(EnableAnimationInfo.description)]]
std::optional<bool> enableAnimation;
// The date and time that the model animation should start.
// In format 'YYYY MM DD hh:mm:ss'.
std::optional<std::string> animationStartTime [[codegen::datetime()]];
enum class [[codegen::map(openspace::TimeUnit)]] AnimationTimeUnit {
Nanosecond,
Microsecond,
Millisecond,
Second,
Minute
};
// The time scale for the animation relative to seconds.
// Ex, if animation is in milliseconds then AnimationTimeScale = 0.001 or
// AnimationTimeScale = Millisecond, default is Second
std::optional<std::variant<AnimationTimeUnit, float>> animationTimeScale;
enum class AnimationMode {
Once,
LoopFromStart,
LoopInfinitely,
BounceFromStart,
BounceInfinitely
};
// The mode of how the animation should be played back.
// Default is animation is played back once at the start time.
// For a more detailed description see:
// http://wiki.openspaceproject.com/docs/builders/model-animation
std::optional<AnimationMode> animationMode;
// [[codegen::verbatim(AmbientIntensityInfo.description)]]
std::optional<float> ambientIntensity;
// [[codegen::verbatim(DiffuseIntensityInfo.description)]]
std::optional<float> diffuseIntensity;
// [[codegen::verbatim(SpecularIntensityInfo.description)]]
std::optional<float> specularIntensity;
// [[codegen::verbatim(ShadingInfo.description)]]
std::optional<bool> performShading;
// [[codegen::verbatim(DisableFaceCullingInfo.description)]]
std::optional<bool> disableFaceCulling;
// [[codegen::verbatim(ModelTransformInfo.description)]]
std::optional<glm::dmat3x3> modelTransform;
// [[codegen::verbatim(RotationVecInfo.description)]]
std::optional<glm::dvec3> rotationVector;
// [[codegen::verbatim(LightSourcesInfo.description)]]
std::optional<std::vector<ghoul::Dictionary>> lightSources
[[codegen::reference("core_light_source")]];
// [[codegen::verbatim(DisableDepthTestInfo.description)]]
std::optional<bool> disableDepthTest;
// [[codegen::verbatim(BlendingOptionInfo.description)]]
std::optional<std::string> blendingOption;
// [[codegen::verbatim(EnableOpacityBlendingInfo.description)]]
std::optional<bool> enableOpacityBlending;
// The path to the vertex shader program that is used instead of the default
// shader.
std::optional<std::filesystem::path> vertexShader;
// The path to the fragment shader program that is used instead of the default
// shader.
std::optional<std::filesystem::path> fragmentShader;
};
#include "renderablemodel_codegen.cpp"
} // namespace
namespace openspace {
documentation::Documentation RenderableModel::Documentation() {
return codegen::doc<Parameters>("base_renderable_model");
}
RenderableModel::RenderableModel(const ghoul::Dictionary& dictionary)
: Renderable(dictionary)
, _enableAnimation(EnableAnimationInfo, false)
, _ambientIntensity(AmbientIntensityInfo, 0.2f, 0.f, 1.f)
, _diffuseIntensity(DiffuseIntensityInfo, 1.f, 0.f, 1.f)
, _specularIntensity(SpecularIntensityInfo, 1.f, 0.f, 1.f)
, _performShading(ShadingInfo, true)
, _disableFaceCulling(DisableFaceCullingInfo, false)
, _modelTransform(
ModelTransformInfo,
glm::dmat3(1.0),
glm::dmat3(-1.0),
glm::dmat3(1.0)
)
, _rotationVec(RotationVecInfo, glm::dvec3(0.0), glm::dvec3(0.0), glm::dvec3(360.0))
, _disableDepthTest(DisableDepthTestInfo, false)
, _enableOpacityBlending(EnableOpacityBlendingInfo, false)
, _blendingFuncOption(
BlendingOptionInfo,
properties::OptionProperty::DisplayType::Dropdown
)
, _lightSourcePropertyOwner({ "LightSources", "Light Sources" })
{
const Parameters p = codegen::bake<Parameters>(dictionary);
addProperty(_opacity);
registerUpdateRenderBinFromOpacity();
if (p.forceRenderInvisible.has_value()) {
_forceRenderInvisible = *p.forceRenderInvisible;
if (!_forceRenderInvisible) {
// Asset file have specifically said to not render invisible parts,
// do not notify in the log if invisible parts are detected and dropped
_notifyInvisibleDropped = false;
}
}
std::string file = absPath(p.geometryFile.string()).string();
_geometry = ghoul::io::ModelReader::ref().loadModel(
file,
ghoul::io::ModelReader::ForceRenderInvisible(_forceRenderInvisible),
ghoul::io::ModelReader::NotifyInvisibleDropped(_notifyInvisibleDropped)
);
_invertModelScale = p.invertModelScale.value_or(_invertModelScale);
if (p.modelScale.has_value()) {
if (std::holds_alternative<Parameters::ScaleUnit>(*p.modelScale)) {
Parameters::ScaleUnit scaleUnit =
std::get<Parameters::ScaleUnit>(*p.modelScale);
DistanceUnit distanceUnit = codegen::map<DistanceUnit>(scaleUnit);
_modelScale = toMeter(distanceUnit);
}
else if (std::holds_alternative<double>(*p.modelScale)) {
_modelScale = std::get<double>(*p.modelScale);
}
else {
throw ghoul::MissingCaseException();
}
if (_invertModelScale) {
_modelScale = 1.0 / _modelScale;
}
}
if (p.animationStartTime.has_value()) {
if (!_geometry->hasAnimation()) {
LWARNING("Animation start time given to model without animation");
}
_animationStart = *p.animationStartTime;
}
if (p.enableAnimation.has_value()) {
if (!_geometry->hasAnimation()) {
LWARNING("Attempting to enable animation for a model that does not have any");
}
else if (*p.enableAnimation && _animationStart.empty()) {
LWARNING("Cannot enable animation without a given start time");
}
else {
_enableAnimation = *p.enableAnimation;
_geometry->enableAnimation(_enableAnimation);
}
}
if (p.animationTimeScale.has_value()) {
if (!_geometry->hasAnimation()) {
LWARNING("Animation time scale given to model without animation");
}
else if (std::holds_alternative<float>(*p.animationTimeScale)) {
_geometry->setTimeScale(std::get<float>(*p.animationTimeScale));
}
else if (std::holds_alternative<Parameters::AnimationTimeUnit>(
*p.animationTimeScale)
)
{
Parameters::AnimationTimeUnit animationTimeUnit =
std::get<Parameters::AnimationTimeUnit>(*p.animationTimeScale);
TimeUnit timeUnit = codegen::map<TimeUnit>(animationTimeUnit);
_geometry->setTimeScale(static_cast<float>(
convertTime(1.0, timeUnit, TimeUnit::Second))
);
}
else {
throw ghoul::MissingCaseException();
}
}
if (p.animationMode.has_value()) {
if (!_geometry->hasAnimation()) {
LWARNING("Animation mode given to model without animation");
}
switch (*p.animationMode) {
case Parameters::AnimationMode::LoopFromStart:
_animationMode = AnimationMode::LoopFromStart;
break;
case Parameters::AnimationMode::LoopInfinitely:
_animationMode = AnimationMode::LoopInfinitely;
break;
case Parameters::AnimationMode::BounceFromStart:
_animationMode = AnimationMode::BounceFromStart;
break;
case Parameters::AnimationMode::BounceInfinitely:
_animationMode = AnimationMode::BounceInfinitely;
break;
case Parameters::AnimationMode::Once:
_animationMode = AnimationMode::Once;
break;
default:
throw ghoul::MissingCaseException();
}
}
if (p.modelTransform.has_value()) {
_modelTransform = *p.modelTransform;
}
_ambientIntensity = p.ambientIntensity.value_or(_ambientIntensity);
_diffuseIntensity = p.diffuseIntensity.value_or(_diffuseIntensity);
_specularIntensity = p.specularIntensity.value_or(_specularIntensity);
_performShading = p.performShading.value_or(_performShading);
_disableDepthTest = p.disableDepthTest.value_or(_disableDepthTest);
_disableFaceCulling = p.disableFaceCulling.value_or(_disableFaceCulling);
if (p.vertexShader.has_value()) {
_vertexShaderPath = p.vertexShader->string();
}
if (p.fragmentShader.has_value()) {
_fragmentShaderPath = p.fragmentShader->string();
}
if (p.lightSources.has_value()) {
std::vector<ghoul::Dictionary> lightsources = *p.lightSources;
for (const ghoul::Dictionary& lsDictionary : lightsources) {
std::unique_ptr<LightSource> lightSource =
LightSource::createFromDictionary(lsDictionary);
_lightSourcePropertyOwner.addPropertySubOwner(lightSource.get());
_lightSources.push_back(std::move(lightSource));
}
}
if (_geometry->hasAnimation()) {
addProperty(_enableAnimation);
}
addPropertySubOwner(_lightSourcePropertyOwner);
addProperty(_ambientIntensity);
addProperty(_diffuseIntensity);
addProperty(_specularIntensity);
addProperty(_performShading);
addProperty(_disableFaceCulling);
addProperty(_disableDepthTest);
addProperty(_modelTransform);
addProperty(_rotationVec);
_rotationVec.onChange([this]() {
_modelTransform = glm::mat4_cast(glm::quat(glm::radians(_rotationVec.value())));
});
_enableAnimation.onChange([this]() {
if (!_geometry->hasAnimation()) {
LWARNING("Attempting to enable animation for a model that does not have any");
}
else if (_enableAnimation && _animationStart.empty()) {
LWARNING("Cannot enable animation without a given start time");
_enableAnimation = false;
}
else {
_geometry->enableAnimation(_enableAnimation);
}
});
if (p.rotationVector.has_value()) {
_rotationVec = *p.rotationVector;
}
_blendingFuncOption.addOption(DefaultBlending, "Default");
_blendingFuncOption.addOption(AdditiveBlending, "Additive");
_blendingFuncOption.addOption(PointsAndLinesBlending, "Points and Lines");
_blendingFuncOption.addOption(PolygonBlending, "Polygon");
_blendingFuncOption.addOption(ColorAddingBlending, "Color Adding");
addProperty(_blendingFuncOption);
if (p.blendingOption.has_value()) {
const std::string blendingOpt = *p.blendingOption;
_blendingFuncOption.set(BlendingMapping[blendingOpt]);
}
_enableOpacityBlending = p.enableOpacityBlending.value_or(_enableOpacityBlending);
addProperty(_enableOpacityBlending);
}
bool RenderableModel::isReady() const {
return _program;
}
void RenderableModel::initialize() {
ZoneScoped
if (_geometry->hasAnimation() && _enableAnimation && _animationStart.empty()) {
LWARNING("Model with animation not given any start time");
}
else if (_geometry->hasAnimation() && !_enableAnimation) {
LINFO("Model with deactivated animation was found. "
"The animation can be activated by entering a start time in the asset file"
);
}
for (const std::unique_ptr<LightSource>& ls : _lightSources) {
ls->initialize();
}
}
void RenderableModel::initializeGL() {
ZoneScoped
std::string program = ProgramName;
if (!_vertexShaderPath.empty()) {
program += "|vs=" + _vertexShaderPath;
}
if (!_fragmentShaderPath.empty()) {
program += "|fs=" + _fragmentShaderPath;
}
_program = BaseModule::ProgramObjectManager.request(
program,
[&]() -> std::unique_ptr<ghoul::opengl::ProgramObject> {
std::filesystem::path vs =
_vertexShaderPath.empty() ?
absPath("${MODULE_BASE}/shaders/model_vs.glsl") :
std::filesystem::path(_vertexShaderPath);
std::filesystem::path fs =
_fragmentShaderPath.empty() ?
absPath("${MODULE_BASE}/shaders/model_fs.glsl") :
std::filesystem::path(_fragmentShaderPath);
return global::renderEngine->buildRenderProgram(ProgramName, vs, fs);
}
);
// We don't really know what kind of shader the user provides us with, so we can't
// make the assumption that we are going to use all uniforms
_program->setIgnoreUniformLocationError(
ghoul::opengl::ProgramObject::IgnoreError::Yes
);
ghoul::opengl::updateUniformLocations(*_program, _uniformCache, UniformNames);
_geometry->initialize();
_geometry->calculateBoundingRadius();
}
void RenderableModel::deinitializeGL() {
_geometry->deinitialize();
_geometry.reset();
std::string program = ProgramName;
if (!_vertexShaderPath.empty()) {
program += "|vs=" + _vertexShaderPath;
}
if (!_fragmentShaderPath.empty()) {
program += "|fs=" + _fragmentShaderPath;
}
BaseModule::ProgramObjectManager.release(
program,
[](ghoul::opengl::ProgramObject* p) {
global::renderEngine->removeRenderProgram(p);
}
);
_program = nullptr;
}
void RenderableModel::render(const RenderData& data, RendererTasks&) {
const double distanceToCamera = glm::distance(
data.camera.positionVec3(),
data.modelTransform.translation
);
// This distance will be enough to render the model as one pixel if the field of
// view is 'fov' radians and the screen resolution is 'res' pixels.
// Formula from RenderableGlobe
constexpr double tfov = 0.5773502691896257;
constexpr int res = 2880;
const double maxDistance = res * boundingSphere() / tfov;
if (distanceToCamera < maxDistance) {
_program->activate();
_program->setUniform(_uniformCache.opacity, _opacity);
// Model transform and view transform needs to be in double precision
const glm::dmat4 modelTransform =
glm::translate(glm::dmat4(1.0), data.modelTransform.translation) *
glm::dmat4(data.modelTransform.rotation) *
glm::scale(glm::dmat4(1.0), glm::dvec3(data.modelTransform.scale)) *
glm::scale(_modelTransform.value(), glm::dvec3(_modelScale));
const glm::dmat4 modelViewTransform = data.camera.combinedViewMatrix() *
modelTransform;
int nLightSources = 0;
_lightIntensitiesBuffer.resize(_lightSources.size());
_lightDirectionsViewSpaceBuffer.resize(_lightSources.size());
for (const std::unique_ptr<LightSource>& lightSource : _lightSources) {
if (!lightSource->isEnabled()) {
continue;
}
_lightIntensitiesBuffer[nLightSources] = lightSource->intensity();
_lightDirectionsViewSpaceBuffer[nLightSources] =
lightSource->directionViewSpace(data);
++nLightSources;
}
_program->setUniform(
_uniformCache.nLightSources,
nLightSources
);
_program->setUniform(
_uniformCache.lightIntensities,
_lightIntensitiesBuffer
);
_program->setUniform(
_uniformCache.lightDirectionsViewSpace,
_lightDirectionsViewSpaceBuffer
);
_program->setUniform(
_uniformCache.modelViewTransform,
glm::mat4(modelViewTransform)
);
glm::dmat4 normalTransform = glm::transpose(glm::inverse(modelViewTransform));
_program->setUniform(
_uniformCache.normalTransform,
glm::mat4(normalTransform)
);
_program->setUniform(
_uniformCache.projectionTransform,
data.camera.projectionMatrix()
);
_program->setUniform(_uniformCache.ambientIntensity, _ambientIntensity);
_program->setUniform(_uniformCache.diffuseIntensity, _diffuseIntensity);
_program->setUniform(_uniformCache.specularIntensity, _specularIntensity);
_program->setUniform(_uniformCache.performShading, _performShading);
_program->setUniform(_uniformCache.opacityBlending, _enableOpacityBlending);
if (_disableFaceCulling) {
glDisable(GL_CULL_FACE);
}
glEnablei(GL_BLEND, 0);
switch (_blendingFuncOption) {
case DefaultBlending:
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
break;
case AdditiveBlending:
glBlendFunc(GL_ONE, GL_ONE);
break;
case PointsAndLinesBlending:
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
break;
case PolygonBlending:
glBlendFunc(GL_SRC_ALPHA_SATURATE, GL_ONE);
break;
case ColorAddingBlending:
glBlendFunc(GL_SRC_COLOR, GL_DST_COLOR);
break;
};
if (_disableDepthTest) {
glDisable(GL_DEPTH_TEST);
}
_geometry->render(*_program);
if (_disableFaceCulling) {
glEnable(GL_CULL_FACE);
}
global::renderEngine->openglStateCache().resetBlendState();
if (_disableDepthTest) {
glEnable(GL_DEPTH_TEST);
}
_program->deactivate();
}
}
void RenderableModel::update(const UpdateData& data) {
if (_program->isDirty()) {
_program->rebuildFromFile();
ghoul::opengl::updateUniformLocations(*_program, _uniformCache, UniformNames);
}
setBoundingSphere(_geometry->boundingRadius() * _modelScale *
glm::compMax(data.modelTransform.scale)
);
if (_geometry->hasAnimation() && !_animationStart.empty()) {
double relativeTime;
double now = data.time.j2000Seconds();
double startTime = data.time.convertTime(_animationStart);
double duration = _geometry->animationDuration();
// The animation works in a time range 0 to duration where 0 in the animation is
// the given _animationStart time in OpenSpace. The time in OpenSpace then has to
// be converted to the animation time range, so the animation knows which
// keyframes it should interpolate between for each frame. The conversion is
// done in different ways depending on the animation mode.
// Explanation: s indicates start time, / indicates animation is played once
// forwards, \ indicates animation is played once backwards, time moves to the
// right.
switch (_animationMode) {
case AnimationMode::LoopFromStart:
// Start looping from the start time
// s//// ...
relativeTime = std::fmod(now - startTime, duration);
break;
case AnimationMode::LoopInfinitely:
// Loop both before and after the start time where the model is
// in the initial position at the start time. std::fmod is not a
// true modulo function, it just calculates the remainder of the division
// which can be negative. To make it true modulo it is bumped up to
// positive values when it is negative
// //s// ...
relativeTime = std::fmod(now - startTime, duration);
if (relativeTime < 0.0) {
relativeTime += duration;
}
break;
case AnimationMode::BounceFromStart:
// Bounce from the start position. Bounce means to do the animation
// and when it ends, play the animation in reverse to make sure the model
// goes back to its initial position before starting again. Avoids a
// visible jump from the last position to the first position when loop
// starts again
// s/\/\/\/\ ...
relativeTime =
duration - abs(fmod(now - startTime, 2 * duration) - duration);
break;
case AnimationMode::BounceInfinitely: {
// Bounce both before and after the start time where the model is
// in the initial position at the start time
// /\/\s/\/\ ...
double modulo = fmod(now - startTime, 2 * duration);
if (modulo < 0.0) {
modulo += 2 * duration;
}
relativeTime = duration - abs(modulo - duration);
break;
}
case AnimationMode::Once:
// Play animation once starting from the start time and stay at the
// animation's last position when animation is over
// s/
relativeTime = now - startTime;
if (relativeTime > duration) {
relativeTime = duration;
}
break;
default:
throw ghoul::MissingCaseException();
}
_geometry->update(relativeTime);
}
}
} // namespace openspace
| OpenSpace/OpenSpace | modules/base/rendering/renderablemodel.cpp | C++ | mit | 29,543 |
/*
* Copyright (c) 2014 Benjamim Sonntag
*
* Permission is hereby granted, free of charge,
* to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package pt.uminho.di.cesium.jdbcforzombies.models;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
/**
* Zombie
*
* @author Benjamim Sonntag
*/
public class Zombie {
private long id = -1;
private String name;
private String graveyard;
private final Set<Tweet> tweets = new HashSet<>();
public Zombie() {
}
public Zombie(String name, String graveyard) {
this.name = name;
this.graveyard = graveyard;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGraveyard() {
return graveyard;
}
public void setGraveyard(String graveyard) {
this.graveyard = graveyard;
}
public Collection<Tweet> getTweets() {
return Collections.<Tweet>unmodifiableCollection(tweets);
}
public boolean addTweet(Tweet tweet) {
if(tweets.contains(tweet)) {
return false;
}
else {
tweet.setZombie(this);
tweets.add(tweet);
return true;
}
}
public boolean removeTweet(Tweet tweet) {
if(tweets.contains(tweet)) {
tweets.remove(tweet);
tweet.setZombie(null);
return false;
}
else {
return false;
}
}
@Override
public int hashCode() {
int hash = 17 + (int) (this.id ^ (this.id >>> 32));
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
else if (getClass() != obj.getClass()) {
return false;
}
else {
final Zombie other = (Zombie) obj;
return this.id == other.id;
}
}
@Override
public String toString() {
return "Zombie{id=" + id + ", name=" + name + ", graveyard=" + graveyard + '}';
}
}
| bsonntag/JDBCForZombies | JDBCForZombies_v2/src/main/java/pt/uminho/di/cesium/jdbcforzombies/models/Zombie.java | Java | mit | 3,310 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace TmxMapperPCL
{
public class Property
{
// name
[XmlAttribute(DataType = "string", AttributeName = "name")]
public string Name { get; set; }
// value
[XmlAttribute(DataType = "string", AttributeName = "value")]
public string Value { get; set; }
}
}
| aalmik/tmx-mapper-pcl | TmxMapperPCL/TmxMapperPCL/Property.cs | C# | mit | 481 |
const gulp = require('gulp');
const $ = require('gulp-load-plugins')();
const fs = require('fs');
const del = require('del');
const glob = require('glob');
const path = require('path');
const mkdirp = require('mkdirp');
const babelify = require('babelify');
const isparta = require('isparta');
const esperanto = require('esperanto');
const browserify = require('browserify');
const runSequence = require('run-sequence');
const source = require('vinyl-source-stream');
const manifest = require('./package.json');
const config = manifest.babelBoilerplateOptions;
const mainFile = manifest.main;
const destinationFolder = path.dirname(mainFile);
const exportFileName = path.basename(mainFile, path.extname(mainFile));
// Remove the built files
gulp.task('clean', function(cb) {
del([destinationFolder], cb);
});
// Remove our temporary files
gulp.task('clean-tmp', function(cb) {
del(['tmp'], cb);
});
// Send a notification when JSRC fails,
// so that you know your changes didn't build
function jscsNotify(file) {
if (!file.jscs) { return; }
return file.jscs.success ? false : 'JSRC failed';
}
function createLintTask(taskName, files) {
gulp.task(taskName, function() {
return gulp.src(files)
.pipe($.plumber())
.pipe($.eslint())
.pipe($.eslint.format())
.pipe($.eslint.failOnError())
.pipe($.jscs())
.pipe($.notify(jscsNotify));
});
}
// Lint our source code
createLintTask('lint-src', ['src/**/*.js']);
// Lint our test code
createLintTask('lint-test', ['test/**/*.js']);
// Build two versions of the library
gulp.task('build', ['lint-src', 'clean'], function(done) {
esperanto.bundle({
base: 'src',
entry: config.entryFileName
}).then(function(bundle) {
var res = bundle.toUmd({
strict: true,
sourceMap: true,
sourceMapSource: config.entryFileName + '.js',
sourceMapFile: exportFileName + '.js',
name: config.exportVarName
});
// Write the generated sourcemap
mkdirp.sync(destinationFolder);
fs.writeFileSync(path.join(destinationFolder, exportFileName + '.js'), res.map.toString());
$.file(exportFileName + '.js', res.code, { src: true })
.pipe($.plumber())
.pipe($.sourcemaps.init({ loadMaps: true }))
.pipe($.babel({ blacklist: ['useStrict'] }))
.pipe($.sourcemaps.write('./', {addComment: false}))
.pipe(gulp.dest(destinationFolder))
.pipe($.filter(['*', '!**/*.js.map']))
.pipe($.rename(exportFileName + '.min.js'))
.pipe($.sourcemaps.init({ loadMaps: true }))
.pipe($.uglify())
.pipe($.sourcemaps.write('./'))
.pipe(gulp.dest(destinationFolder))
.on('end', done);
})
.catch(done);
});
gulp.task('serve', ['build'], function () {
gulp.watch('src/**/*.js', ['build']);
});
// Bundle our app for our unit tests
gulp.task('browserify', function() {
var testFiles = glob.sync('./test/unit/**/*');
var allFiles = ['./test/setup/browserify.js'].concat(testFiles);
var bundler = browserify(allFiles);
bundler.transform(babelify.configure({
sourceMapRelative: __dirname + '/src',
blacklist: ['useStrict']
}));
return bundler.bundle()
.on('error', function(err){
console.log(err.message);
this.emit('end');
})
.pipe($.plumber())
.pipe(source('./tmp/__spec-build.js'))
.pipe(gulp.dest(''))
.pipe($.livereload());
});
function test() {
return gulp.src(['test/setup/node.js', 'test/unit/**/*.js'], {read: false})
.pipe($.mocha({reporter: 'dot', globals: config.mochaGlobals}));
}
gulp.task('coverage', ['lint-src', 'lint-test'], function(done) {
require('babel/register');
gulp.src(['src/**/*.js'])
.pipe($.istanbul({ instrumenter: isparta.Instrumenter }))
.pipe($.istanbul.hookRequire())
.on('finish', function() {
return test()
.pipe($.istanbul.writeReports())
.on('end', done);
});
});
// Lint and run our tests
gulp.task('test', ['lint-src', 'lint-test'], function() {
require('babel/register');
return test();
});
// Ensure that linting occurs before browserify runs. This prevents
// the build from breaking due to poorly formatted code.
gulp.task('build-in-sequence', function(callback) {
runSequence(['lint-src', 'lint-test'], 'browserify', callback);
});
const watchFiles = ['src/**/*', 'test/**/*', 'package.json', '**/.eslintrc', '.jscsrc'];
// Run the headless unit tests as you make changes.
gulp.task('watch', function() {
gulp.watch(watchFiles, ['test']);
});
// Set up a livereload environment for our spec runner
gulp.task('test-browser', ['build-in-sequence'], function() {
$.livereload.listen({port: 35729, host: 'localhost', start: true});
return gulp.watch(watchFiles, ['build-in-sequence']);
});
// An alias of test
gulp.task('default', ['test']);
| Edools/bamboo-linter | gulpfile.js | JavaScript | mit | 4,793 |
require File.expand_path(File.dirname(__FILE__) + "/lib/insert_commands.rb")
class MonkeyNotificationGenerator < Rails::Generator::Base
def add_options!(opt)
opt.on('-k', '--api-url=url', String, "Your Monkey URL") {|v| options[:api_url] = v}
end
def manifest
record do |m|
m.directory 'lib/tasks'
m.file 'monkey_notification_tasks.rake', 'lib/tasks/monkey_notification_tasks.rake'
if ['config/deploy.rb', 'Capfile'].all? { |file| File.exists?(file) }
m.append_to 'config/deploy.rb', capistrano_hook
end
if options[:api_url] && !api_url_configured?
m.template 'initializer.rb', 'config/initializers/monkey_notification.rb',
:assigns => {:api_url => api_url_expression}
end
end
end
def api_url_configured?
File.exists?('config/initializers/monkey_notification.rb')
end
def api_url_expression
"'#{options[:api_url]}'"
end
def capistrano_hook
IO.read(source_path('capistrano_hook.rb'))
end
end | le0pard/monkey_notification | generators/monkey_notification/monkey_notification_generator.rb | Ruby | mit | 1,047 |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="format-detection" content="telephone=no">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<script type="text/javascript">
// This automatically sets the right viewport scale on mobile devices
(function() {
var scale = 1 / window.devicePixelRatio
var viewport = "width=device-width, height=device-height, initial-scale=" + scale + ", maximum-scale=" + scale + ", user-scalable=no"
var iOS = /iPad|iPhone|iPod/.test(navigator.platform)
if (iOS) { viewport += ", shrink-to-fit=no" }
document.write("<meta name=\"viewport\" content=\"" + viewport + "\">")
})()
</script>
<link rel="stylesheet" type="text/css" href="/style.css">
<script src="/framer.js"></script>
<script src="/framer.alive.js"></script>
<script src="/framer.init.js"></script>
</head>
<body>
</body>
</html>
| tomger/alive-server | framer/framer.html | HTML | mit | 974 |
# map.gionsai.yeno.net
木更津高専祇園祭Webサイト <http://map.gionsai.yeno.net> のソースコード
## 本アプリケーションについて
[Wiki中](http://github.com/enotai/map.gionsai.yeno.net/wiki/map)で概要を紹介しています
* APIドキュメント(暫定) : <http://map.gionsai.yeno.net/docs>
* 来年度の祇園祭実行委員会広報部へ : [Wiki](http://github.com/enotai/map.gionsai.yeno.net/wiki)に2015年度の業務内容をまとめました
| enotai/map.gionsai.yeno.net | README.md | Markdown | mit | 486 |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Admin extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->helper('url');
$this->load->model('admin_model');
$this->load->model('participant_model');
$this->load->model('team_model');
}
public function index()
{
if($this->is_login() == true){
$data['participants']=$this->participant_model->get_all_participants();
$this->load->view('templates/header-dashboard');
$this->load->view('admin/participant',$data);
$this->load->view('templates/footer-dashboard');
}else{
redirect('admin/login');
}
}
public function login()
{
//form validation
$this->form_validation->set_rules('username', 'Username', 'required|alpha');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run() == FALSE){
$this->load->view('admin/login');
}else{
$this->check();
}
}
public function is_login(){
if(isset($this->session->userdata['logged_in'])){
return true;
}else{
return false;
}
}
public function dashboard()
{
if($this->is_login() == true){
$data['teams']=$this->team_model->get_all_team();
$this->load->view('templates/header-dashboard');
$this->load->view('admin/team',$data);
$this->load->view('templates/footer-dashboard');
}else{
redirect('admin/login');
}
}
public function manage_team()
{
if(isset($this->session->userdata['logged_in'])){
$data['teams']=$this->team_model->get_all_team();
$this->load->view('templates/header-dashboard');
$this->load->view('admin/team',$data);
$this->load->view('templates/footer-dashboard');
}else{
redirect('admin/login');
}
}
public function manage_proposal()
{
if(isset($this->session->userdata['logged_in'])){
$this->load->view('admin/proposal');
}else{
redirect('admin/login');
}
}
public function logout()
{
$session_data = array(
'username' => '',
);
$this->session->unset_userdata('logged_in',$session_data);
redirect('/admin/login');
}
public function add()
{
$username = $this->input->post('username');
$password = $this->input->post('password');
$data = array(
'username' => $username,
'password' => MD5($password),
'status' => '1',
);
$insert = $this->admin_model->auth_add($data);
if($insert == true){
$data = json_encode(array(
'status' => 0,
'message' => 'ADD_USER_AUTH_SUCCESS',
'data' => []
));
}else{
$data = json_encode(array(
'status' => 0,
'message' => 'ADD_USER_AUTH_FAILED',
'data' => 'DUPLICATE_USERNAME'
));
}
return $this->output
->set_content_type('application/json')
->set_status_header(200)
->set_output($data);
}
public function check()
{
$username = $this->input->post('username');
$password = $this->input->post('password');
if($this->is_login() == true){
redirect('/admin/dashboard', 'refresh');
}else{
$data = array(
'username' =>$username,
'password' =>MD5($password),
'status' => '0',
);
$result = $this->admin_model->auth_check($data);
if($result == true){
$session_data = array(
'username' => 'ADMIN',
);
$this->session->set_userdata('logged_in', $session_data);
redirect('/admin/dashboard', 'refresh');
}else{
$view['error_msg'] = 'Incorrect Login';
}
$this->load->view('admin/login',$view);
}
}
public function get_participant($id){
$participant_data = $this->participant_model->get_by_id($id);
$fk_team = $participant_data->fk_team;
$team_data = $this->team_model->get_by_fk($fk_team);
$data = json_encode(array(
'status' => 0,
'message' => 'GET_PARTICIPANT_SUCCESS',
'data_participant' => $participant_data,
'data_team' => $team_data
));
return $this->output
->set_content_type('application/json')
->set_status_header(200)
->set_output($data);
}
}
| vousmeevoyez/ci-event | application/controllers/Admin.php | PHP | mit | 4,220 |
<HTML><HEAD>
<TITLE>Review for Jui kuen II (1994)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1 ALIGN="CENTER" CLASS="title"><A HREF="/Title?0111512">Jui kuen II (1994)</A></H1><H3 ALIGN=CENTER>reviewed by<BR><A HREF="/ReviewsBy?Steve+Rhodes">Steve Rhodes</A></H3><HR WIDTH="40%" SIZE="4">
<PRE>
THE LEGEND OF DRUNKEN MASTER
A film review by Steve Rhodes
Copyright 2000 Steve Rhodes
RATING (0 TO ****): **</PRE>
<P>This is the first time that I've ever started off a review by telling
you what film I'm not reviewing. This is not a review of THE LEGEND OF
DRUNKEN MASTER (1994), starring the lovable Jackie Chan. The 1994
version was in the original Chinese and came with English subtitles. I
have a critic-friend well versed in Hong Kong cinema, who claims the
1994 version is a classic martial arts picture of the comedic action
genre. I came late to the Jackie Chan admiration society. Although I'm
a fan now, with my favorite being his recent SHANGHAI NOON, I haven't
seen any of his early films such as this movie.</P>
<P>In order to capitalize on the Chan phenomenon and knowing that American
audiences are generally too lazy to read, the studio has released a poor
and awkwardly dubbed reissue of the original. This review is strictly
for the dubbed version. How these thoughts would apply to the original,
I have no idea. I absolutely shudder to think what my second favorite
film of last year, RUN LOLA RUN, would sound like dubbed into English.</P>
<P>Chan stars in a picture with a remarkably thin plot. As usual he does
everything himself from getting beaten up to falling on burning coals.
Is there no limit to the pain he has to endure for his craft? In his
normal outtakes shown during the closing credits, he proves to us yet
again that he does do all of his own stunts, risking his life and limb. </P>
<P>His schtick this time is that he is a master of the art of drunken
fighting. Tanked up with lots of booze, which he guzzles during the
bouts, he bobs and weaves so that hitting him is like trying to strike
blowing grass in a strong wind. As almost an afterthought, the story
lets us know that even a drunken master can over imbibe, rendering him
more of a fool than a master.</P>
<P>The beauty of Chan's films is due as much to the ballet-quality
choreography that he brings to kung fu as to the humor that permeates
everything that he does. In a nutshell, the problem with THE LEGEND OF
DRUNKEN MASTER is that there is too much fighting gymnastics and too
little of the story development. This means that the story dissolves
into little more than slapstick and highly repetitive fight sequences.
I wanted more than this and left the theater feeling cheated. This was
one of the unusual Chan movies in which I didn't have much fun. Maybe
you will. Or maybe you'll avoid this theatrical version entirely and go
rent the subtitled one instead.</P>
<P>THE LEGEND OF DRUNKEN MASTER runs 1:42. It is rated R for violent
content and would be acceptable for teenagers.</P>
<P>Email: <A HREF="mailto:[email protected]">[email protected]</A>
Web: <A HREF="http://www.InternetReviews.com">http://www.InternetReviews.com</A></P>
<HR><P CLASS=flush><SMALL>The review above was posted to the
<A HREF="news:rec.arts.movies.reviews">rec.arts.movies.reviews</A> newsgroup (<A HREF="news:de.rec.film.kritiken">de.rec.film.kritiken</A> for German reviews).<BR>
The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.<BR>
Please direct comments/criticisms of the review to relevant newsgroups.<BR>
Broken URLs inthe reviews are the responsibility of the author.<BR>
The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.
</SMALL></P>
<P ALIGN=CENTER>Related links: <A HREF="/Reviews/">index of all rec.arts.movies.reviews reviews</A></P>
</P></BODY></HTML>
| xianjunzhengbackup/code | data science/machine_learning_for_the_web/chapter_4/movie/26548.html | HTML | mit | 4,150 |
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import * as path from 'path';
import slash = require('slash');
import glob = require('glob');
import {Config} from '@jest/types';
export const findSiblingsWithFileExtension = (
moduleFileExtensions: Config.ProjectConfig['moduleFileExtensions'],
from: Config.Path,
moduleName: string,
): string => {
if (!path.isAbsolute(moduleName) && path.extname(moduleName) === '') {
const dirname = path.dirname(from);
const pathToModule = path.resolve(dirname, moduleName);
try {
const slashedDirname = slash(dirname);
const matches = glob
.sync(`${pathToModule}.*`)
.map(match => slash(match))
.map(match => {
const relativePath = path.posix.relative(slashedDirname, match);
return path.posix.dirname(match) === slashedDirname
? `./${relativePath}`
: relativePath;
})
.map(match => `\t'${match}'`)
.join('\n');
if (matches) {
const foundMessage = `\n\nHowever, Jest was able to find:\n${matches}`;
const mappedModuleFileExtensions = moduleFileExtensions
.map(ext => `'${ext}'`)
.join(', ');
return (
foundMessage +
"\n\nYou might want to include a file extension in your import, or update your 'moduleFileExtensions', which is currently " +
`[${mappedModuleFileExtensions}].\n\nSee https://jestjs.io/docs/en/configuration#modulefileextensions-array-string`
);
}
} catch (ignored) {}
}
return '';
};
| ide/jest | packages/jest-runtime/src/helpers.ts | TypeScript | mit | 1,733 |
require File.dirname(__FILE__) + '/test_helper'
class Universe; end
class UniversesController < InheritedResources::Base
defaults :singleton => true, :route_instance_name => 'universum'
end
class House; end
class HousesController < InheritedResources::Base
end
class Backpack; end
module Admin; end
class Admin::BackpacksController < InheritedResources::Base
defaults :route_collection_name => 'tour_backpacks'
end
class Table; end
class TablesController < InheritedResources::Base
belongs_to :house
end
class RoomsController < InheritedResources::Base
belongs_to :house, :route_name => 'big_house'
end
class ChairsController < InheritedResources::Base
belongs_to :house do
belongs_to :table
end
end
class OwnersController < InheritedResources::Base
singleton_belongs_to :house
end
class Bed; end
class BedsController < InheritedResources::Base
optional_belongs_to :house, :building
end
class Desk; end
module Admin
class DesksController < InheritedResources::Base
optional_belongs_to :house
end
end
class Dish; end
class DishesController < InheritedResources::Base
belongs_to :house do
polymorphic_belongs_to :table, :kitchen
end
end
class Center; end
class CentersController < InheritedResources::Base
acts_as_singleton!
belongs_to :house do
belongs_to :table, :kitchen, :polymorphic => true
end
end
# Create a TestHelper module with some helpers
class UrlHelpersTest < ActiveSupport::TestCase
def test_url_helpers_on_simple_inherited_resource
controller = HousesController.new
controller.instance_variable_set('@house', :house)
[:url, :path].each do |path_or_url|
controller.expects("houses_#{path_or_url}").with({}).once
controller.send("collection_#{path_or_url}")
controller.expects("house_#{path_or_url}").with(:house, {}).once
controller.send("resource_#{path_or_url}")
controller.expects("new_house_#{path_or_url}").with({}).once
controller.send("new_resource_#{path_or_url}")
controller.expects("edit_house_#{path_or_url}").with(:house, {}).once
controller.send("edit_resource_#{path_or_url}")
# With arg
controller.expects("house_#{path_or_url}").with(:arg, {}).once
controller.send("resource_#{path_or_url}", :arg)
controller.expects("house_#{path_or_url}").with(:arg, {}).once
controller.send("resource_#{path_or_url}", :arg)
# With options
controller.expects("house_#{path_or_url}").with(:arg, :page => 1).once
controller.send("resource_#{path_or_url}", :arg, :page => 1)
end
end
def test_url_helpers_on_simple_inherited_namespaced_resource
controller = Admin::BackpacksController.new
controller.instance_variable_set('@backpack', :backpack)
assert_equal 'admin', controller.class.resources_configuration[:self][:route_prefix]
[:url, :path].each do |path_or_url|
controller.expects("admin_tour_backpacks_#{path_or_url}").with({}).once
controller.send("collection_#{path_or_url}")
controller.expects("admin_backpack_#{path_or_url}").with(:backpack, {}).once
controller.send("resource_#{path_or_url}")
controller.expects("new_admin_backpack_#{path_or_url}").with({}).once
controller.send("new_resource_#{path_or_url}")
controller.expects("edit_admin_backpack_#{path_or_url}").with(:backpack, {}).once
controller.send("edit_resource_#{path_or_url}")
# With arg
controller.expects("admin_backpack_#{path_or_url}").with(:arg, {}).once
controller.send("resource_#{path_or_url}", :arg)
controller.expects("admin_backpack_#{path_or_url}").with(:arg, {}).once
controller.send("resource_#{path_or_url}", :arg)
# With options
controller.expects("admin_backpack_#{path_or_url}").with(:arg, :page => 1).once
controller.send("resource_#{path_or_url}", :arg, :page => 1)
end
end
def test_url_helpers_on_simple_inherited_singleton_resource
controller = UniversesController.new
controller.instance_variable_set('@universe', :universe)
[:url, :path].each do |path_or_url|
controller.expects("root_#{path_or_url}").with({}).once
controller.send("collection_#{path_or_url}")
controller.expects("universum_#{path_or_url}").with({}).once
controller.send("resource_#{path_or_url}")
controller.expects("new_universum_#{path_or_url}").with({}).once
controller.send("new_resource_#{path_or_url}")
controller.expects("edit_universum_#{path_or_url}").with({}).once
controller.send("edit_resource_#{path_or_url}")
# With options
# Also tests that argument sent are not used
controller.expects("universum_#{path_or_url}").with(:page => 1).once
controller.send("resource_#{path_or_url}", :arg, :page => 1)
end
end
def test_url_helpers_on_belongs_to
controller = TablesController.new
controller.instance_variable_set('@house', :house)
controller.instance_variable_set('@table', :table)
[:url, :path].each do |path_or_url|
controller.expects("house_tables_#{path_or_url}").with(:house, {}).once
controller.send("collection_#{path_or_url}")
controller.expects("house_table_#{path_or_url}").with(:house, :table, {}).once
controller.send("resource_#{path_or_url}")
controller.expects("new_house_table_#{path_or_url}").with(:house, {}).once
controller.send("new_resource_#{path_or_url}")
controller.expects("edit_house_table_#{path_or_url}").with(:house, :table, {}).once
controller.send("edit_resource_#{path_or_url}")
# With arg
controller.expects("house_table_#{path_or_url}").with(:house, :arg, {}).once
controller.send("resource_#{path_or_url}", :arg)
controller.expects("edit_house_table_#{path_or_url}").with(:house, :arg, {}).once
controller.send("edit_resource_#{path_or_url}", :arg)
# With options
controller.expects("house_table_#{path_or_url}").with(:house, :arg, :page => 1).once
controller.send("resource_#{path_or_url}", :arg, :page => 1)
end
end
def test_url_helpers_on_not_default_belongs_to
controller = RoomsController.new
controller.instance_variable_set('@house', :house)
controller.instance_variable_set('@room', :room)
[:url, :path].each do |path_or_url|
controller.expects("big_house_rooms_#{path_or_url}").with(:house, {}).once
controller.send("collection_#{path_or_url}")
controller.expects("big_house_room_#{path_or_url}").with(:house, :room, {}).once
controller.send("resource_#{path_or_url}")
controller.expects("new_big_house_room_#{path_or_url}").with(:house, {}).once
controller.send("new_resource_#{path_or_url}")
controller.expects("edit_big_house_room_#{path_or_url}").with(:house, :room, {}).once
controller.send("edit_resource_#{path_or_url}")
# With args
controller.expects("big_house_room_#{path_or_url}").with(:house, :arg, {}).once
controller.send("resource_#{path_or_url}", :arg)
controller.expects("edit_big_house_room_#{path_or_url}").with(:house, :arg, {}).once
controller.send("edit_resource_#{path_or_url}", :arg)
# With options
controller.expects("big_house_room_#{path_or_url}").with(:house, :arg, :page => 1).once
controller.send("resource_#{path_or_url}", :arg, :page => 1)
end
end
def test_url_helpers_on_nested_belongs_to
controller = ChairsController.new
controller.instance_variable_set('@house', :house)
controller.instance_variable_set('@table', :table)
controller.instance_variable_set('@chair', :chair)
[:url, :path].each do |path_or_url|
controller.expects("house_table_chairs_#{path_or_url}").with(:house, :table, {}).once
controller.send("collection_#{path_or_url}")
controller.expects("house_table_chair_#{path_or_url}").with(:house, :table, :chair, {}).once
controller.send("resource_#{path_or_url}")
controller.expects("new_house_table_chair_#{path_or_url}").with(:house, :table, {}).once
controller.send("new_resource_#{path_or_url}")
controller.expects("edit_house_table_chair_#{path_or_url}").with(:house, :table, :chair, {}).once
controller.send("edit_resource_#{path_or_url}")
# With args
controller.expects("edit_house_table_chair_#{path_or_url}").with(:house, :table, :arg, {}).once
controller.send("edit_resource_#{path_or_url}", :arg)
controller.expects("house_table_chair_#{path_or_url}").with(:house, :table, :arg, {}).once
controller.send("resource_#{path_or_url}", :arg)
# With options
controller.expects("edit_house_table_chair_#{path_or_url}").with(:house, :table, :arg, :page => 1).once
controller.send("edit_resource_#{path_or_url}", :arg, :page => 1)
end
end
def test_url_helpers_on_singletons_with_belongs_to
controller = OwnersController.new
controller.instance_variable_set('@house', :house)
controller.instance_variable_set('@owner', :owner)
[:url, :path].each do |path_or_url|
controller.expects("house_#{path_or_url}").with(:house, {}).once
controller.send("collection_#{path_or_url}")
controller.expects("house_owner_#{path_or_url}").with(:house, {}).once
controller.send("resource_#{path_or_url}")
controller.expects("new_house_owner_#{path_or_url}").with(:house, {}).once
controller.send("new_resource_#{path_or_url}")
controller.expects("edit_house_owner_#{path_or_url}").with(:house, {}).once
controller.send("edit_resource_#{path_or_url}")
# With options
# Also tests that argument sent are not used
controller.expects("house_owner_#{path_or_url}").with(:house, :page => 1).once
controller.send("resource_#{path_or_url}", :arg, :page => 1)
end
end
def test_url_helpers_on_polymorphic_belongs_to
house = House.new
bed = Bed.new
new_bed = Bed.new
Bed.stubs(:new).returns(new_bed)
new_bed.stubs(:new_record?).returns(true)
controller = BedsController.new
controller.instance_variable_set('@parent_type', :house)
controller.instance_variable_set('@house', house)
controller.instance_variable_set('@bed', bed)
[:url, :path].each do |path_or_url|
controller.expects("house_beds_#{path_or_url}").with(house).once
controller.send("collection_#{path_or_url}")
controller.expects("house_bed_#{path_or_url}").with(house, bed).once
controller.send("resource_#{path_or_url}")
controller.expects("new_house_bed_#{path_or_url}").with(house).once
controller.send("new_resource_#{path_or_url}")
controller.expects("edit_house_bed_#{path_or_url}").with(house, bed).once
controller.send("edit_resource_#{path_or_url}")
end
# With options
controller.expects("house_bed_url").with(house, bed, :page => 1).once
controller.send("resource_url", :page => 1)
# With args
controller.expects("polymorphic_url").with([:arg, new_bed], {}).once
controller.send("collection_url", :arg)
controller.expects("polymorphic_url").with([house, :arg], {}).once
controller.send("resource_url", :arg)
controller.expects("edit_polymorphic_url").with([house, :arg], {}).once
controller.send("edit_resource_url", :arg)
end
def test_url_helpers_on_namespaced_polymorphic_belongs_to
house = House.new
desk = Desk.new
new_desk = Desk.new
Desk.stubs(:new).returns(new_desk)
new_desk.stubs(:new_record?).returns(true)
controller = Admin::DesksController.new
controller.instance_variable_set('@parent_type', :house)
controller.instance_variable_set('@house', house)
controller.instance_variable_set('@desk', desk)
[:url, :path].each do |path_or_url|
controller.expects("admin_house_desks_#{path_or_url}").with(house).once
controller.send("collection_#{path_or_url}")
controller.expects("admin_house_desk_#{path_or_url}").with(house, desk).once
controller.send("resource_#{path_or_url}")
controller.expects("new_admin_house_desk_#{path_or_url}").with(house).once
controller.send("new_resource_#{path_or_url}")
controller.expects("edit_admin_house_desk_#{path_or_url}").with(house, desk).once
controller.send("edit_resource_#{path_or_url}")
end
# With options
controller.expects("admin_house_desk_url").with(house, desk, :page => 1).once
controller.send("resource_url", :page => 1)
# With args
controller.expects("polymorphic_url").with(['admin', :arg, new_desk], {}).once
controller.send("collection_url", :arg)
controller.expects("polymorphic_url").with(['admin', house, :arg], {}).once
controller.send("resource_url", :arg)
controller.expects("edit_polymorphic_url").with(['admin', house, :arg], {}).once
controller.send("edit_resource_url", :arg)
end
def test_url_helpers_on_nested_polymorphic_belongs_to
house = House.new
table = Table.new
dish = Dish.new
new_dish = Dish.new
Dish.stubs(:new).returns(new_dish)
new_dish.stubs(:new_record?).returns(true)
controller = DishesController.new
controller.instance_variable_set('@parent_type', :table)
controller.instance_variable_set('@house', house)
controller.instance_variable_set('@table', table)
controller.instance_variable_set('@dish', dish)
[:url, :path].each do |path_or_url|
controller.expects("house_table_dishes_#{path_or_url}").with(house, table).once
controller.send("collection_#{path_or_url}")
controller.expects("house_table_dish_#{path_or_url}").with(house, table, dish).once
controller.send("resource_#{path_or_url}")
controller.expects("new_house_table_dish_#{path_or_url}").with(house, table).once
controller.send("new_resource_#{path_or_url}")
controller.expects("edit_house_table_dish_#{path_or_url}").with(house, table, dish).once
controller.send("edit_resource_#{path_or_url}")
end
# With options
controller.expects("house_table_dish_url").with(house, table, dish, :page => 1).once
controller.send("resource_url", :page => 1)
# With args
controller.expects("polymorphic_url").with([house, table, :arg], {}).once
controller.send("resource_url", :arg)
controller.expects("edit_polymorphic_url").with([house, table, :arg], {}).once
controller.send("edit_resource_url", :arg)
end
def test_url_helpers_on_singleton_nested_polymorphic_belongs_to
# This must not be usefull in singleton controllers...
# Center.new
house = House.new
table = Table.new
controller = CentersController.new
controller.instance_variable_set('@parent_type', :table)
controller.instance_variable_set('@house', house)
controller.instance_variable_set('@table', table)
# This must not be useful in singleton controllers...
# controller.instance_variable_set('@center', :center)
[:url, :path].each do |path_or_url|
controller.expects("house_table_#{path_or_url}").with(house, table).once
controller.send("collection_#{path_or_url}")
controller.expects("house_table_center_#{path_or_url}").with(house, table).once
controller.send("resource_#{path_or_url}")
controller.expects("new_house_table_center_#{path_or_url}").with(house, table).once
controller.send("new_resource_#{path_or_url}")
controller.expects("edit_house_table_center_#{path_or_url}").with(house, table).once
controller.send("edit_resource_#{path_or_url}")
end
# With options
controller.expects("house_table_center_url").with(house, table, :page => 1)
controller.send("resource_url", :page => 1)
# With args
controller.expects("polymorphic_url").with([house, table, :center], {}).once
controller.send("resource_url", :arg)
end
def test_url_helpers_on_optional_polymorphic_belongs_to
bed = Bed.new
new_bed = Bed.new
Bed.stubs(:new).returns(new_bed)
new_bed.stubs(:new_record?).returns(true)
controller = BedsController.new
controller.instance_variable_set('@parent_type', nil)
controller.instance_variable_set('@bed', bed)
[:url, :path].each do |path_or_url|
controller.expects("beds_#{path_or_url}").with().once
controller.send("collection_#{path_or_url}")
controller.expects("bed_#{path_or_url}").with(bed).once
controller.send("resource_#{path_or_url}")
controller.expects("new_bed_#{path_or_url}").with().once
controller.send("new_resource_#{path_or_url}")
controller.expects("edit_bed_#{path_or_url}").with(bed).once
controller.send("edit_resource_#{path_or_url}")
end
# With options
controller.expects("bed_url").with(bed, :page => 1).once
controller.send("resource_url", :page => 1)
# With args
controller.expects("polymorphic_url").with([:arg], {}).once
controller.send("resource_url", :arg)
controller.expects("edit_polymorphic_url").with([:arg], {}).once
controller.send("edit_resource_url", :arg)
end
end
| brontes3d/tribute | vendor/plugins/inherited_resources/test/url_helpers_test.rb | Ruby | mit | 17,050 |
const logging = require('@tryghost/logging');
const ObjectId = require('bson-objectid').default;
module.exports = {
config: {
transaction: true
},
async up(config) {
const knex = config.transacting;
const defaultOperations = [{
key: 'stripe_connect_publishable_key'
}, {
key: 'stripe_connect_secret_key'
}, {
key: 'stripe_connect_livemode'
}, {
key: 'stripe_connect_display_name'
}, {
key: 'stripe_connect_account_id'
}];
for (const operation of defaultOperations) {
logging.info(`Updating ${operation.key} setting group,type,flags`);
await knex('settings')
.where({
key: operation.key
})
.update({
group: 'members',
flags: '',
type: 'members'
});
}
const stripeConnectIntegrationJSON = await knex('settings')
.select('value')
.where('key', 'stripe_connect_integration')
.first();
if (!stripeConnectIntegrationJSON) {
logging.warn(`Could not find stripe_connect_integration - using default values`);
return;
}
const stripeConnectIntegration = JSON.parse(stripeConnectIntegrationJSON.value);
const valueOperations = [{
key: 'stripe_connect_publishable_key',
value: stripeConnectIntegration.public_key || ''
}, {
key: 'stripe_connect_secret_key',
value: stripeConnectIntegration.secret_key || ''
}, {
key: 'stripe_connect_livemode',
value: stripeConnectIntegration.livemode || ''
}, {
key: 'stripe_connect_display_name',
value: stripeConnectIntegration.display_name || ''
}, {
key: 'stripe_connect_account_id',
value: stripeConnectIntegration.account_id || ''
}];
for (const operation of valueOperations) {
logging.info(`Updating ${operation.key} setting value`);
await knex('settings')
.where({
key: operation.key
})
.update({
value: operation.value
});
}
logging.info(`Deleting stripe_connect_integration setting`);
await knex('settings')
.where('key', 'stripe_connect_integration')
.del();
},
async down(config) {
const knex = config.transacting;
const getSetting = key => knex.select('value').from('settings').where('key', key).first();
const accountId = await getSetting('stripe_connect_account_id');
const displayName = await getSetting('stripe_connect_display_name');
const livemode = await getSetting('stripe_connect_livemode');
const publishableKey = await getSetting('stripe_connect_publishable_key');
const secretKey = await getSetting('stripe_connect_secret_key');
const stripeConnectIntegration = {
account_id: accountId ? accountId.value : null,
display_name: displayName ? displayName.value : null,
livemode: livemode ? livemode.value : null,
public_key: publishableKey ? publishableKey.value : null,
secret_key: secretKey ? secretKey.value : null
};
const now = knex.raw('CURRENT_TIMESTAMP');
logging.info(`Inserting stripe_connect_integration setting`);
await knex('settings')
.insert({
id: ObjectId().toHexString(),
key: 'stripe_connect_integration',
value: JSON.stringify(stripeConnectIntegration),
group: 'members',
type: 'members',
flags: '',
created_at: now,
created_by: 1,
updated_at: now,
updated_by: 1
});
const settingsToDelete = [
'stripe_connect_account_id',
'stripe_connect_display_name',
'stripe_connect_livemode',
'stripe_connect_publishable_key',
'stripe_connect_secret_key'
];
logging.info(`Deleting ${settingsToDelete.join(', ')} settings`);
await knex('settings').whereIn('key', settingsToDelete).del();
}
};
| janvt/Ghost | core/server/data/migrations/versions/3.22/06-migrate-stripe-connect-settings.js | JavaScript | mit | 4,468 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="es">
<head>
<!-- Generated by javadoc (1.8.0_131) on Wed Oct 04 21:39:26 COT 2017 -->
<title>Uses of Class rest.MenuServices</title>
<meta name="date" content="2017-10-04">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class rest.MenuServices";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../rest/MenuServices.html" title="class in rest">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../index-files/index-1.html">Index</a></li>
<li><a href="../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../index.html?rest/class-use/MenuServices.html" target="_top">Frames</a></li>
<li><a href="MenuServices.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class rest.MenuServices" class="title">Uses of Class<br>rest.MenuServices</h2>
</div>
<div class="classUseContainer">No usage of rest.MenuServices</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../rest/MenuServices.html" title="class in rest">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../index-files/index-1.html">Index</a></li>
<li><a href="../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../index.html?rest/class-use/MenuServices.html" target="_top">Frames</a></li>
<li><a href="MenuServices.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| Juanpablor5/RotondAndes | Docs/JavaDoc/rest/class-use/MenuServices.html | HTML | mit | 4,024 |
/* ###################################################################
** This component module is generated by Processor Expert. Do not modify it.
** Filename : gpio_pins.c
** Project : twrk60D100m-pin
** Processor : MK60DN512VMD10
** Component : fsl_gpio
** Version : Component 01.106, Driver 01.00, CPU db: 3.00.000
** Compiler : GNU C Compiler
** Date/Time : 2014-06-08, 17:51, # CodeGen: 7
**
** Copyright : 1997 - 2014 Freescale Semiconductor, Inc.
** All Rights Reserved.
**
** Redistribution and use in source and binary forms, with or without modification,
** are permitted provided that the following conditions are met:
**
** o Redistributions of source code must retain the above copyright notice, this list
** of conditions and the following disclaimer.
**
** o Redistributions in binary form must reproduce the above copyright notice, this
** list of conditions and the following disclaimer in the documentation and/or
** other materials provided with the distribution.
**
** o Neither the name of Freescale Semiconductor, Inc. nor the names of its
** contributors may be used to endorse or promote products derived from this
** software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
** ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
** ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
** http: www.freescale.com
** mail: [email protected]
** ###################################################################*/
/*!
** @file gpio_pins.c
** @version 01.00
*/
/*!
** @addtogroup gpio_pins_module gpio_pins module documentation
** @{
*/
/* MODULE gpio_pins. */
#include "gpio_pins.h"
#include <stdbool.h>
gpio_input_pin_user_config_t switchPins[] = {
{
.pinName = kGpioSW1,
.config.isPullEnable = true,
.config.pullSelect = kPortPullUp,
.config.isPassiveFilterEnabled = false,
.config.interrupt = kPortIntDisabled
},
{
.pinName = kGpioSW2,
.config.isPullEnable = true,
.config.pullSelect = kPortPullUp,
.config.isPassiveFilterEnabled = false,
.config.interrupt = kPortIntDisabled
},
{
.pinName = GPIO_PINS_OUT_OF_RANGE,
}
};
const gpio_input_pin_user_config_t sdhcCdPin[] = {
{
.pinName = kGpioSdhc0Cd,
.config.isPullEnable = true,
.config.pullSelect = kPortPullUp,
.config.isPassiveFilterEnabled = false,
.config.interrupt = kPortIntEitherEdge
},
{
.pinName = GPIO_PINS_OUT_OF_RANGE,
}
};
const gpio_output_pin_user_config_t ledPins[] = {
{
.pinName = kGpioLED1,
.config.outputLogic = 1,
.config.slewRate = kPortSlowSlewRate,
.config.isOpenDrainEnabled = false,
.config.driveStrength = kPortLowDriveStrength,
},
{
.pinName = kGpioLED2,
.config.outputLogic = 1,
.config.slewRate = kPortSlowSlewRate,
.config.isOpenDrainEnabled = false,
.config.driveStrength = kPortLowDriveStrength,
},
{
.pinName = kGpioLED3,
.config.outputLogic = 1,
.config.slewRate = kPortSlowSlewRate,
.config.isOpenDrainEnabled = false,
.config.driveStrength = kPortLowDriveStrength,
},
{
.pinName = kGpioLED4,
.config.outputLogic = 1,
.config.slewRate = kPortSlowSlewRate,
.config.isOpenDrainEnabled = false,
.config.driveStrength = kPortLowDriveStrength,
},
{
.pinName = GPIO_PINS_OUT_OF_RANGE,
}
};
/* END gpio_pins. */
/*!
** @}
*/
/*
** ###################################################################
**
** This file was created by Processor Expert 10.4 [05.10]
** for the Freescale Kinetis series of microcontrollers.
**
** ###################################################################
*/
| linwenjian/Quadcopter_Will | Software/SDK1_1/demos/apps_sdk1.2/twrk60d100m/gpio_pins.c | C | mit | 4,513 |
package routes
import (
"fmt"
"log"
"net/http"
"sync"
"strings"
"encoding/json"
"github.com/PuerkitoBio/goquery"
"github.com/gorilla/mux"
"models"
)
// FeaturedStats will scrape Blizzard's Overwatch user profile page for that account's
// featured statistics and add the data to the featuredStatsObject slice.
//
// Parameters:
// wg - A pointer to a wait group that will allow both goroutines to finish before creating the player object
// featuredStatsObject - A pointer to the object that will be used when creating the player object
// doc - The document body that GoQuery will be scraping from
// gameMode - The game mode that should be searched for in the DOM
func FeaturedStats(wg *sync.WaitGroup, featuredStatsObject *[]models.Stat, doc *goquery.Document, gameMode string, statNameParam string) {
featuredStats := make([]models.Stat, 0, 0)
doc.Find("#" + gameMode + " div.card").Each(func(index int, item *goquery.Selection) {
// Scrape data
statIcon, _ := item.Find("div.bg-icon").Html()
statName := item.Find("div.card-content p.card-copy").Text()
statValue := item.Find("div.card-content h3.card-heading").Text()
if (statNameParam != "" && strings.ToLower(statNameParam) == strings.ToLower(statName)) || statNameParam == "" {
// Create stat struct
s := models.Stat{statName, statValue, statIcon}
featuredStats = append(featuredStats, s)
}
})
*featuredStatsObject = featuredStats
defer wg.Done()
}
// CareerStats will scrape Blizzard's Overwatch user profile page for that account's
// career statistics and add the data to the careerStatsObject slice.
//
// Parameters:
// wg - A pointer to a wait group that will allow both goroutines to finish before creating the player object
// featuredStatsObject - A pointer to the object that will be used when creating the player object
// doc - The document body that GoQuery will be scraping from
// gameMode - The game mode that should be searched for in the DOM
func CareerStats(wg *sync.WaitGroup, careerStatsObject *[]models.StatCategory, doc *goquery.Document, gameMode string, statNameParam string) {
careerStats := make([]models.StatCategory, 0, 0)
doc.Find("#" + gameMode + " div.card-stat-block").Each(func(index int, item *goquery.Selection) {
// Scrape category info
categoryName := item.Find("thead th span.stat-title").Text()
categoryIcon, _ := item.Find("thead th svg").Html()
// Loop through stats and scrape
categoryStats := make([]models.Stat, 0, 0)
item.Find("tbody tr").Each(func(index int, statItem *goquery.Selection) {
// Scrape
statName := statItem.Find("td").First().Text()
statValue := statItem.Find("td").Last().Text()
if (statNameParam != "" && strings.ToLower(statNameParam) == strings.ToLower(statName)) || statNameParam == "" {
// Create stat struct
s := models.Stat{statName, statValue, ""}
categoryStats = append(categoryStats, s)
}
})
if len(categoryStats) > 0 {
// Create stat category struct
sc := models.StatCategory{categoryName, categoryIcon, categoryStats}
careerStats = append(careerStats, sc)
}
})
*careerStatsObject = careerStats
defer wg.Done()
}
// HeroComparison will scrape Blizzard's Overwatch user profile page for that account's
// hero comparison metrics, such as played time, games won, etc. This will return an
// object that contains all available metrics for the specified game type
//
// Parameters:
// wg - A pointer to a wait group that will allow both goroutines to finish before creating the player object
// featuredStatsObject - A pointer to the object that will be used when creating the player object
// doc - The document body that GoQuery will be scraping from
// gameMode - The game mode that should be searched for in the DOM
func HeroComparison(wg *sync.WaitGroup, heroComparisonMetricsObject *[]models.HeroComparisonMetric, doc *goquery.Document, gameMode string, statNameParam string, heroNameParam string) {
// Loop through the available metrics
heroComparisonMetrics := make([]models.HeroComparisonMetric, 0, 0)
doc.Find("#" + gameMode + " select[data-group-id='comparisons'] option").Each(func(index int, item *goquery.Selection) {
// Get the identifier for each metric from the dropdown and loop through the
// container for that identifier
overwatchGuid, _ := item.Attr("value")
metricName := item.Text()
heroComparisonHeroes := make([]models.HeroComparisonHero, 0, 0)
hch := models.HeroComparisonHero{"", "", "", ""}
if strings.ToLower(statNameParam) == strings.ToLower(metricName) || statNameParam == "" {
doc.Find("#" + gameMode + " div[data-category-id='" + overwatchGuid + "'] div.progress-category-item").Each(func(index int, progressItem *goquery.Selection) {
// Scrape the stats from the specified container
heroName := progressItem.Find("div.bar-text div.title").Text()
metricValue := progressItem.Find("div.bar-text div.description").Text()
heroImage, _ := progressItem.Find("img").Attr("src")
metricPercent, _ := progressItem.Attr("data-overwatch-progress-percent")
if strings.ToLower(heroNameParam) == strings.ToLower(heroName) || heroNameParam == "" {
// Create a hero object and store the values,
// then append the object to the slice of heroes
hch = models.HeroComparisonHero{heroName, metricValue, heroImage, metricPercent}
heroComparisonHeroes = append(heroComparisonHeroes, hch)
}
})
}
// Add the metric to the slice of metrics and add the metric
// to the slice of metrics
if len(heroComparisonHeroes) > 0 {
hcm := models.HeroComparisonMetric{metricName, heroComparisonHeroes}
heroComparisonMetrics = append(heroComparisonMetrics, hcm)
}
})
*heroComparisonMetricsObject = heroComparisonMetrics
defer wg.Done()
}
// PlayerDetail will combine a user's featured stats, career stats, hero played time, into a JSON object and
// print the result to the browser
// URL: /players/{platform}/{region}/{gameMode}/{battleTag} (only us and eu are currently supported for region)
func PlayerDetail(w http.ResponseWriter, r *http.Request) {
// Create workgroup to wait for all goroutines to finish
var wg sync.WaitGroup
// Define constants
vars := mux.Vars(r)
battleTag := vars["battleTag"]
region := vars["region"]
platform := vars["platform"]
gameMode := vars["gameMode"]
url := "https://playoverwatch.com/en-us/career/" + platform + "/" + region + "/" + battleTag
// Check cache before making request
cachedData := readCache("PlayerDetail", "players-" + platform + "-" + region + "-" + gameMode + "-" + battleTag)
if cachedData != "" {
fmt.Fprintln(w, cachedData)
return;
}
// Fetch document body
doc, err := goquery.NewDocument(url)
if err != nil {
log.Fatal(err)
res, _ := json.Marshal(models.Response{"500", "heroDetail", "error with request"})
fmt.Fprintln(w, string(res))
return
}
// Player profile stats
playerName := doc.Find("div.masthead h1.header-masthead").Text()
playerPortrait, _ := doc.Find("div.masthead img.player-portrait").Attr("src")
playerRankIcon, _ := doc.Find("div.masthead div.competitive-rank img").Attr("src")
playerRankNumber := doc.Find("div.masthead div.competitive-rank div.h6").First().Text()
playerRank := [2]string{playerRankIcon, playerRankNumber}
// Featured Stats
wg.Add(1)
featuredStatsObject := make([]models.Stat, 0, 0)
go FeaturedStats(&wg, &featuredStatsObject, doc, gameMode, "")
// Career stats
wg.Add(1)
careerStatsObject := make([]models.StatCategory, 0, 0)
go CareerStats(&wg, &careerStatsObject, doc, gameMode, "")
// Hero Comparison Metrics
wg.Add(1)
heroComparisonMetricsObject := make([]models.HeroComparisonMetric, 0, 0)
go HeroComparison(&wg, &heroComparisonMetricsObject, doc, gameMode, "", "")
// Create player struct
wg.Wait()
p := models.Player{playerName, battleTag, playerPortrait, playerRank, featuredStatsObject, careerStatsObject, heroComparisonMetricsObject}
// Create response struct
res, _ := json.Marshal(models.Response{"200", "PlayerDetail", p})
fmt.Fprintln(w, string(res))
// Cache response for future use
cache("PlayerDetail", "players-" + platform + "-" + region + "-" + gameMode + "-" + battleTag, string(res))
}
// FeaturedStatsDetail will return a list of a user's featured stats, or an individual featured stat
// print the result to the browser
// URL: /players/{platform}/{region}/{gameMode}/{battleTag}/featuredStats/{statName?} (only us and eu are currently supported for region)
func FeaturedStatsDetail(w http.ResponseWriter, r *http.Request) {
// Create workgroup to wait for all goroutines to finish
var wg sync.WaitGroup
// Define constants
vars := mux.Vars(r)
battleTag := vars["battleTag"]
region := vars["region"]
platform := vars["platform"]
gameMode := vars["gameMode"]
statNameParam := vars["statName"]
url := "https://playoverwatch.com/en-us/career/" + platform + "/" + region + "/" + battleTag
// Check cache before making request
cachedData := readCache("FeaturedStatsDetail", "players-" + platform + "-" + region + "-" + gameMode + "-" + battleTag + "|stat=" + statNameParam)
if cachedData != "" {
fmt.Fprintln(w, cachedData)
return;
}
// Fetch document body
doc, err := goquery.NewDocument(url)
if err != nil {
log.Fatal(err)
res, _ := json.Marshal(models.Response{"500", "heroDetail", "error with request"})
fmt.Fprintln(w, string(res))
return
}
// Featured Stats
wg.Add(1)
featuredStatsObject := make([]models.Stat, 0, 0)
go FeaturedStats(&wg, &featuredStatsObject, doc, gameMode, statNameParam)
wg.Wait()
res, _ := json.Marshal(models.Response{"200", "FeaturedStatsDetail", featuredStatsObject})
fmt.Fprintln(w, string(res))
cache("FeaturedStatsDetail", "players-" + platform + "-" + region + "-" + gameMode + "-" + battleTag + "|stat=" + statNameParam, string(res))
}
// CareerStatsDetail will return a list of a user's career stats, or an individual career stat
// print the result to the browser
// URL: /players/{platform}/{region}/{gameMode}/{battleTag}/careerStats/{statName?} (only us and eu are currently supported for region)
func CareerStatsDetail(w http.ResponseWriter, r *http.Request) {
// Create workgroup to wait for all goroutines to finish
var wg sync.WaitGroup
// Define constants
vars := mux.Vars(r)
battleTag := vars["battleTag"]
region := vars["region"]
platform := vars["platform"]
gameMode := vars["gameMode"]
statNameParam := vars["statName"]
url := "https://playoverwatch.com/en-us/career/" + platform + "/" + region + "/" + battleTag
// Check cache before making request
cachedData := readCache("CareerStatsDetail", "players-" + platform + "-" + region + "-" + gameMode + "-" + battleTag + "|stat=" + statNameParam)
if cachedData != "" {
fmt.Fprintln(w, cachedData)
return;
}
// Fetch document body
doc, err := goquery.NewDocument(url)
if err != nil {
log.Fatal(err)
res, _ := json.Marshal(models.Response{"500", "heroDetail", "error with request"})
fmt.Fprintln(w, string(res))
return
}
// Career stats
wg.Add(1)
careerStatsObject := make([]models.StatCategory, 0, 0)
go CareerStats(&wg, &careerStatsObject, doc, gameMode, statNameParam)
wg.Wait()
res, _ := json.Marshal(models.Response{"200", "CareerStatsDetail", careerStatsObject})
fmt.Fprintln(w, string(res))
cache("CareerStatsDetail", "players-" + platform + "-" + region + "-" + gameMode + "-" + battleTag + "|stat=" + statNameParam, string(res))
}
// HeroComparisonDetail will return a list of metrics by which a player's hero performance is measured for each hero and values
// associated with each metric. This request can be limited to a single hero, a single stat, or a single stat FOR a single hero
// print the result to the browser
// URL: /players/{platform}/{region}/{gameMode}/{battleTag}/heroComparison/[hero/{heroName},stat/{statName},hero/{heroName}/stat/{statName}]? (only us and eu are currently supported for region)
func HeroComparisonDetail(w http.ResponseWriter, r *http.Request) {
// Create workgroup to wait for all goroutines to finish
var wg sync.WaitGroup
// Define constants
vars := mux.Vars(r)
battleTag := vars["battleTag"]
region := vars["region"]
platform := vars["platform"]
gameMode := vars["gameMode"]
heroNameParam := vars["heroName"]
statNameParam := vars["statName"]
url := "https://playoverwatch.com/en-us/career/" + platform + "/" + region + "/" + battleTag
// Check cache before making request
cachedData := readCache("HeroComparisonDetail", "players-" + platform + "-" + region + "-" + gameMode + "-" + battleTag + "|hero=" + heroNameParam + "|stat=" + statNameParam)
if cachedData != "" {
fmt.Fprintln(w, cachedData)
return;
}
// Fetch document body
doc, err := goquery.NewDocument(url)
if err != nil {
log.Fatal(err)
res, _ := json.Marshal(models.Response{"404", "HeroComparisonDetail", "error with this request"})
fmt.Fprintln(w, string(res))
return
}
// Hero Comparison Metrics
wg.Add(1)
heroComparisonMetricsObject := make([]models.HeroComparisonMetric, 0, 0)
go HeroComparison(&wg, &heroComparisonMetricsObject, doc, gameMode, statNameParam, heroNameParam)
wg.Wait()
res, _ := json.Marshal(models.Response{"200", "HeroComparisonDetail", heroComparisonMetricsObject})
fmt.Fprintln(w, string(res))
cache("HeroComparisonDetail", "players-" + platform + "-" + region + "-" + gameMode + "-" + battleTag + "|hero=" + heroNameParam + "|stat=" + statNameParam, string(res))
} | GethosTheWalrus/Goverwatch | routes/routes.Player.Detail.go | GO | mit | 13,547 |
module Vmail
module AddressQuoter
def quote_addresses(input)
parts = input.split /\s*,\s*/
addrs = []
savebin = ""
#Group the parts together
parts.each do |part|
if part.include? "@"
addrs << savebin + part
savebin = ""
else
savebin = part + ", "
end
end
#Quote the names
addrs.map { |addr|
# a little hackish
if addr =~ /"/
addr
else
addr.gsub(/^(.*) (<.*)/, '"\1" \2')
end
}.join(', ')
end
end
end
| danchoi/min_mail | lib/min_mail/address_quoter.rb | Ruby | mit | 589 |
<?php
namespace Pagekit\Package;
use Pagekit\Package\Exception\LogicException;
use Pagekit\Package\Repository\RepositoryInterface;
class Package implements PackageInterface
{
protected $name;
protected $version;
protected $type;
protected $title;
protected $description;
protected $keywords;
protected $homepage;
protected $license = [];
protected $authors;
protected $extra = [];
protected $releaseDate;
protected $installationSource;
protected $sourceType;
protected $sourceUrl;
protected $distType;
protected $distUrl;
protected $distSha1Checksum;
protected $repository;
protected $autoload = [];
protected $resources = [];
/**
* Creates a new package.
*
* @param string $name
* @param string $version
*/
public function __construct($name, $version)
{
$this->name = strtolower($name);
$this->title = $this->name;
$this->version = $version;
}
/**
* {@inheritdoc}
*/
public function getName()
{
return $this->name;
}
/**
* {@inheritdoc}
*/
public function getVersion()
{
return $this->version;
}
/**
* {@inheritdoc}
*/
public function getType()
{
return $this->type;
}
/**
* @param string $type
*/
public function setType($type)
{
$this->type = $type;
}
/**
* {@inheritdoc}
*/
public function getTitle()
{
return $this->title;
}
/**
* Set the title
*
* @param string $title
*/
public function setTitle($title)
{
$this->title = $title;
}
/**
* {@inheritdoc}
*/
public function getDescription()
{
return $this->description;
}
/**
* Set the description
*
* @param string $description
*/
public function setDescription($description)
{
$this->description = $description;
}
/**
* {@inheritdoc}
*/
public function getKeywords()
{
return (array) $this->keywords;
}
/**
* Set the keywords
*
* @param array $keywords
*/
public function setKeywords(array $keywords)
{
$this->keywords = $keywords;
}
/**
* {@inheritdoc}
*/
public function getHomepage()
{
return $this->homepage;
}
/**
* Set the homepage
*
* @param string $homepage
*/
public function setHomepage($homepage)
{
$this->homepage = $homepage;
}
/**
* {@inheritdoc}
*/
public function getLicense()
{
return $this->license;
}
/**
* Set the license
*
* @param array $license
*/
public function setLicense(array $license)
{
$this->license = $license;
}
/**
* {@inheritdoc}
*/
public function getAuthor()
{
if ($this->authors) {
return current($this->authors);
}
}
/**
* {@inheritdoc}
*/
public function getAuthors()
{
return $this->authors;
}
/**
* Set the authors
*
* @param array $authors
*/
public function setAuthors(array $authors)
{
$this->authors = $authors;
}
/**
* {@inheritdoc}
*/
public function getExtra()
{
return $this->extra;
}
/**
* @param array $extra
*/
public function setExtra(array $extra)
{
$this->extra = $extra;
}
/**
* {@inheritdoc}
*/
public function getReleaseDate()
{
return $this->releaseDate;
}
/**
* Set the releaseDate
*
* @param \DateTime $releaseDate
*/
public function setReleaseDate(\DateTime $releaseDate)
{
$this->releaseDate = $releaseDate;
}
/**
* {@inheritdoc}
*/
public function getInstallationSource()
{
return $this->installationSource;
}
/**
* {@inheritdoc}
*/
public function setInstallationSource($type)
{
$this->installationSource = $type;
}
/**
* {@inheritdoc}
*/
public function getSourceType()
{
return $this->sourceType;
}
/**
* @param string $type
*/
public function setSourceType($type)
{
$this->sourceType = $type;
}
/**
* {@inheritdoc}
*/
public function getSourceUrl()
{
return $this->sourceUrl;
}
/**
* @param string $url
*/
public function setSourceUrl($url)
{
$this->sourceUrl = $url;
}
/**
* {@inheritdoc}
*/
public function getDistType()
{
return $this->distType;
}
/**
* @param string $type
*/
public function setDistType($type)
{
$this->distType = $type;
}
/**
* {@inheritdoc}
*/
public function getDistUrl()
{
return $this->distUrl;
}
/**
* @param string $url
*/
public function setDistUrl($url)
{
$this->distUrl = $url;
}
/**
* {@inheritdoc}
*/
public function getDistSha1Checksum()
{
return $this->distSha1Checksum;
}
/**
* @param string $sha1checksum
*/
public function setDistSha1Checksum($sha1checksum)
{
$this->distSha1Checksum = $sha1checksum;
}
/**
* {@inheritdoc}
*/
public function getRepository()
{
return $this->repository;
}
/**
* {@inheritdoc}
*/
public function setRepository(RepositoryInterface $repository)
{
if ($this->repository) {
throw new LogicException('A package can only be added to one repository');
}
$this->repository = $repository;
}
/**
* Returns the autoload namespace => directory mapping
*/
public function getAutoload()
{
return $this->autoload;
}
/**
* Set the autoload namespace => directory mapping
*
* @param array $autoload
*/
public function setAutoload($autoload)
{
$this->autoload = $autoload;
}
/**
* Returns the resources scheme => path(s)
*/
public function getResources()
{
return $this->resources;
}
/**
* Set the resources scheme => path(s)
*
* @param array $resources
*/
public function setResources(array $resources = [])
{
$this->resources = $resources;
}
/**
* {@inheritdoc}
*/
public function getUniqueName()
{
return sprintf('%s-%s', $this->getName(), $this->getVersion());
}
/**
* {@inheritdoc}
*/
public function compare(PackageInterface $package, $operator = '==')
{
return strtolower($this->getName()) === strtolower($package->getName()) &&
version_compare(strtolower($this->getVersion()), strtolower($package->getVersion()), $operator);
}
/**
* {@inheritdoc}
*/
public function __toString()
{
return $this->getUniqueName();
}
}
| HostSpectr/pagekit | extensions/system/modules/package/src/Package.php | PHP | mit | 7,173 |
"use strict";
let domain = require('domain');
let co = require('co');
let debug = require("debug")("camfree:controller:socket");
let Socket = module.exports = {};
function domainRun(socket) {
var d = domain.create();
d.on('error', function(er) {
debug('error', er.stack);
try {
var killtimer = setTimeout(function() {
process.exit(1);
}, 30000);
killtimer.unref();
} catch (er2) {
debug('Error sending 500!', er2.stack);
}
});
d.add(socket);
// Now run the handler function in the domain.
d.run(function() {
let handler = new camfree.service.SocketHandler(socket);
co.wrap(handler.run).call(handler);
});
}
Socket.camfree = function() {
domainRun(this);
};
| sochea09/CamFreeService | app/controller/Socket.js | JavaScript | mit | 807 |
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
# Adds additional error checking when serving assets at runtime.
# Checks for improperly declared sprockets dependencies.
# Raises helpful error messages.
config.assets.raise_runtime_errors = true
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
# Set default url option for Devise
config.action_mailer.default_url_options = { :host => 'localhost:3000' }
end
| ygoto3/artwork_manager | config/environments/development.rb | Ruby | mit | 1,714 |
<?php
return [
'add_to_cart' => 'Lägg till i varukorg',
'avg_dist' => 'Snittsavstånd<br><span class="small">producent - nod</span>',
'clear_date' => '(rensa datum)',
'contact' => 'Kontakta nodadmin på ',
'filters' => 'Filter',
'find_communication' => 'Hitta till vår kommunikationsgrupp',
'find_producer_communication' => 'Hitta till vår kommunikationsgrupp för producenter',
'from' => 'Från',
'how_many' => 'Hur många till varje utlämning?',
'images' => 'Bilder',
'info' => 'Info',
'join' => 'Gå med i nod',
'km' => 'km',
'leave' => 'Gå ur nod',
'locals' => 'Locals',
'login_needed' => 'Logga in för att fortsätta',
'no_products' => 'Det finns inga produkter tillgängliga.',
'order' => 'Bokning',
'pick_up_order' => 'Utlämningsplats',
'pickup' => 'Utlämning',
'placeholder_qty' => 'Välj antal',
'product' => 'Produkt',
'products' => 'Produkter',
'producers' => 'Producenter',
'select_variant' => 'Välj variant',
'select_pickup' => 'Välj utlämningsdatum',
'share' => 'Dela',
'switch_product_view' => 'Visa alla produkter',
'switch_weekly_view' => 'Visa per utlämningsdatum',
'tags' => 'Taggar',
];
| localfoodnodes/localfoodnodes | resources/lang/sv/public/node.php | PHP | mit | 1,240 |
#ifndef AY38912_H_
#define AY38912_H_
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
#define AY_CH_A_FINETUNE 0
#define AY_CH_A_COARSETUNE 1
#define AY_CH_B_FINETUNE 2
#define AY_CH_B_COARSETUNE 3
#define AY_CH_C_FINETUNE 4
#define AY_CH_C_COARSETUNE 5
#define AY_NOISE_PERIOD 6
#define AY_ENABLE 7
#define AY_CH_A_AMPLITUDE 8
#define AY_CH_B_AMPLITUDE 9
#define AY_CH_C_AMPLITUDE 10
#define AY_ENVELOPE_FINE 11
#define AY_ENVELOPE_COARSE 12
#define AY_ENVELOPE_SHAPE 13
#define AY_PORTA 14
#define AY_PORTB 15
void AyRegister(uint8_t address, uint8_t value);
void AyPort(uint8_t value);
void AyPortBit0(uint8_t bitNo);
void AyPortBit1(uint8_t bitNo);
#ifdef __cplusplus
}
#endif
#endif
| SmallRoomLabs/BEEPoo | Firmware/BEEPoo/ay38912.h | C | mit | 769 |
/***************************************************************************/
/* */
/* ftdebug.c */
/* */
/* Debugging and logging component (body). */
/* */
/* Copyright 1996-2001, 2002, 2004, 2008, 2013 by */
/* David Turner, Robert Wilhelm, and Werner Lemberg. */
/* */
/* This file is part of the FreeType project, and may only be used, */
/* modified, and distributed under the terms of the FreeType project */
/* license, LICENSE.TXT. By continuing to use, modify, or distribute */
/* this file you indicate that you have read the license and */
/* understand and accept it fully. */
/* */
/***************************************************************************/
/*************************************************************************/
/* */
/* This component contains various macros and functions used to ease the */
/* debugging of the FreeType engine. Its main purpose is in assertion */
/* checking, tracing, and error detection. */
/* */
/* There are now three debugging modes: */
/* */
/* - trace mode */
/* */
/* Error and trace messages are sent to the log file (which can be the */
/* standard error output). */
/* */
/* - error mode */
/* */
/* Only error messages are generated. */
/* */
/* - release mode: */
/* */
/* No error message is sent or generated. The code is free from any */
/* debugging parts. */
/* */
/*************************************************************************/
#include <XMFreeType/ft2build.h>
#include <XMFreeType/freetype.h>
#include <internal/ftdebug.h>
#ifdef FT_DEBUG_LEVEL_ERROR
/* documentation is in ftdebug.h */
FT_BASE_DEF( void )
FT_Message( const char* fmt,
... )
{
va_list ap;
va_start( ap, fmt );
vfprintf( stderr, fmt, ap );
va_end( ap );
}
/* documentation is in ftdebug.h */
FT_BASE_DEF( void )
FT_Panic( const char* fmt,
... )
{
va_list ap;
va_start( ap, fmt );
vfprintf( stderr, fmt, ap );
va_end( ap );
exit( EXIT_FAILURE );
}
/* documentation is in ftdebug.h */
FT_BASE_DEF( int )
FT_Throw( FT_Error error,
int line,
const char* file )
{
FT_UNUSED( error );
FT_UNUSED( line );
FT_UNUSED( file );
return 0;
}
#endif /* FT_DEBUG_LEVEL_ERROR */
#ifdef FT_DEBUG_LEVEL_TRACE
/* array of trace levels, initialized to 0 */
int ft_trace_levels[trace_count];
/* define array of trace toggle names */
#define FT_TRACE_DEF( x ) #x ,
static const char* ft_trace_toggles[trace_count + 1] =
{
#include <internal/fttrace.h>
NULL
};
#undef FT_TRACE_DEF
/* documentation is in ftdebug.h */
FT_BASE_DEF( FT_Int )
FT_Trace_Get_Count( void )
{
return trace_count;
}
/* documentation is in ftdebug.h */
FT_BASE_DEF( const char * )
FT_Trace_Get_Name( FT_Int idx )
{
int max = FT_Trace_Get_Count();
if ( idx < max )
return ft_trace_toggles[idx];
else
return NULL;
}
/*************************************************************************/
/* */
/* Initialize the tracing sub-system. This is done by retrieving the */
/* value of the `FT2_DEBUG' environment variable. It must be a list of */
/* toggles, separated by spaces, `;', or `,'. Example: */
/* */
/* export FT2_DEBUG="any:3 memory:7 stream:5" */
/* */
/* This requests that all levels be set to 3, except the trace level for */
/* the memory and stream components which are set to 7 and 5, */
/* respectively. */
/* */
/* See the file <include/internal/fttrace.h> for details of the */
/* available toggle names. */
/* */
/* The level must be between 0 and 7; 0 means quiet (except for serious */
/* runtime errors), and 7 means _very_ verbose. */
/* */
FT_BASE_DEF( void )
ft_debug_init( void )
{
const char* ft2_debug = getenv( "FT2_DEBUG" );
if ( ft2_debug )
{
const char* p = ft2_debug;
const char* q;
for ( ; *p; p++ )
{
/* skip leading whitespace and separators */
if ( *p == ' ' || *p == '\t' || *p == ',' || *p == ';' || *p == '=' )
continue;
/* read toggle name, followed by ':' */
q = p;
while ( *p && *p != ':' )
p++;
if ( !*p )
break;
if ( *p == ':' && p > q )
{
FT_Int n, i, len = (FT_Int)( p - q );
FT_Int level = -1, found = -1;
for ( n = 0; n < trace_count; n++ )
{
const char* toggle = ft_trace_toggles[n];
for ( i = 0; i < len; i++ )
{
if ( toggle[i] != q[i] )
break;
}
if ( i == len && toggle[i] == 0 )
{
found = n;
break;
}
}
/* read level */
p++;
if ( *p )
{
level = *p - '0';
if ( level < 0 || level > 7 )
level = -1;
}
if ( found >= 0 && level >= 0 )
{
if ( found == trace_any )
{
/* special case for `any' */
for ( n = 0; n < trace_count; n++ )
ft_trace_levels[n] = level;
}
else
ft_trace_levels[found] = level;
}
}
}
}
}
#else /* !FT_DEBUG_LEVEL_TRACE */
FT_BASE_DEF( void )
ft_debug_init( void )
{
/* nothing */
}
FT_BASE_DEF( FT_Int )
FT_Trace_Get_Count( void )
{
return 0;
}
FT_BASE_DEF( const char * )
FT_Trace_Get_Name( FT_Int idx )
{
FT_UNUSED( idx );
return NULL;
}
#endif /* !FT_DEBUG_LEVEL_TRACE */
/* END */
| mcodegeeks/OpenKODE-Framework | 01_Develop/libXMFreeType/Source/base/ftdebug.c | C | mit | 7,943 |
body {
background-color: hsl(0,0%,95%);
line-height: 150%;
}
p {
background: url('');
}
#description {
margin: auto;
/*width: 60%;*/
font-family: "Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif;
font-size: 14px;
text-shadow: hsla(0,0%,40%,0.5) 0 -1px 0, hsla(0,0%,100%,.6) 0 2px 1px;
text-align: center;
}
#services {
margin: auto;
margin-top: 10px;
margin-bottom: 10px;
width: 60%;
line-height: 150%;
border: 1px solid #999;
-webkit-box-shadow: 0px 0px 8px rgba(0, 0, 0, 0.3);
-moz-box-shadow: 0px 0px 8px rgba(0, 0, 0, 0.3);
box-shadow: 0px 0px 8px rgba(0, 0, 0, 0.3);
border-radius: 10px;
padding: 10px 50px 15px 50px;
background-color: hsl(0,0%,90%);
text-align: left;
font-size: 13.5px;
}
#links {
margin-left: 50px;
border-radius: 10px;
border-left: 1px solid #999;
padding-left: 10px;
margin-bottom: 10px;
}
img {
border-radius: 5px;
}
#howto {
margin-left: 15%;
text-align: left;
}
h3 {
font-family: "Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif;
text-shadow: hsla(0,0%,40%,0.5) 0 -1px 0, hsla(0,0%,100%,.6) 0 2px 1px;
text-align: center;
margin-bottom: 7px;
margin-top: 5px;
}
#exp {
text-align: center;
font-size: 13px;
margin-bottom: 5px;
}
#footer,#ins {
display: block;
margin-top: 0px;
font-size: 11px;
}
#footer {
text-align: center;
}
hr {
color: white;
border: 0;
height: 1px;
background-image: -webkit-linear-gradient(left, rgba(0,0,0,0), rgba(0,0,0,0.3), rgba(0,0,0,0));
background-image: -moz-linear-gradient(left, rgba(0,0,0,0), rgba(0,0,0,0.3), rgba(0,0,0,0));
background-image: -ms-linear-gradient(left, rgba(0,0,0,0), rgba(0,0,0,0.3), rgba(0,0,0,0));
background-image: -o-linear-gradient(left, rgba(0,0,0,0), rgba(0,0,0,0.3), rgba(0,0,0,0));
}
h1 {
text-align: center;
margin-bottom: 5px;
text-shadow: hsla(0,0%,40%,0.5) 0 -1px 0, hsla(0,0%,100%,.6) 0 2px 1px;
}
input {
height: 17px;
border: 1px solid white;
border-radius: 5px;
margin-left: 2px;
-webkit-box-shadow: 0px 0px 8px rgba(0, 0, 0, 0.3);
-moz-box-shadow: 0px 0px 8px rgba(0, 0, 0, 0.3);
box-shadow: 0px 0px 8px rgba(0, 0, 0, 0.3);
font-family: "Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif;
font-size: 15px;
text-shadow: hsla(0,0%,40%,0.5) 0 -1px 0, hsla(0,0%,100%,.6) 0 2px 1px;
}
a:link {
color: #800000;
}
a:visited {
color: #696969;
}
#response {
border-radius: 10px;
background-color: hsl(0,0%,90%);
padding: 35px;
border: 1px solid #999;
line-height: 100%;
width: 70%;
-webkit-box-shadow: 0px 0px 8px rgba(0, 0, 0, 0.3);
-moz-box-shadow: 0px 0px 8px rgba(0, 0, 0, 0.3);
box-shadow: 0px 0px 8px rgba(0, 0, 0, 0.3);
font-family:"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif;
font-size:13px;
margin: auto;
text-align: left;
text-shadow: hsla(0,0%,40%,.5) 0 -1px 0, hsla(0,0%,100%,.6) 0 2px 1px;
}
#inner {
border-radius: 10px;
background-color: hsl(0,0%,90%);
padding: 5px;
border-left: 1px solid #999;
width: 90%;
/*-webkit-box-shadow: -5px 0px 1px rgba(0, 0, 0, 0.3);
-moz-box-shadow: -5px 0px 1px rgba(0, 0, 0, 0.3);
box-shadow: -5px 0px 1px rgba(0, 0, 0, 0.3);*/
font-family:"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif;
font-size: 13px;
margin: auto;
margin-top: 10px;
margin-bottom: 10px;
text-align: left;
text-shadow: hsla(0,0%,40%,.5) 0 -1px 0, hsla(0,0%,100%,.6) 0 2px 1px;
}
#widget {
display: table;
margin: 0 auto;
}
| pranavrc/smaw | res/index.css | CSS | mit | 3,492 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.11"/>
<title>My Project: src/utils/chunk.h File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { init_search(); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">My Project
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.11 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="annotated.html"><span>Classes</span></a></li>
<li class="current"><a href="files.html"><span>Files</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="files.html"><span>File List</span></a></li>
<li><a href="globals.html"><span>File Members</span></a></li>
</ul>
</div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="dir_68267d1309a1af8e8297ef4c3efbcdba.html">src</a></li><li class="navelem"><a class="el" href="dir_313caf1132e152dd9b58bea13a4052ca.html">utils</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="summary">
<a href="#func-members">Functions</a> </div>
<div class="headertitle">
<div class="title">chunk.h File Reference</div> </div>
</div><!--header-->
<div class="contents">
<div class="textblock"><code>#include <stddef.h></code><br />
<code>#include "<a class="el" href="int_8h_source.html">int.h</a>"</code><br />
</div><div class="textblock"><div class="dynheader">
Include dependency graph for chunk.h:</div>
<div class="dyncontent">
<div class="center"><img src="chunk_8h__incl.png" border="0" usemap="#src_2utils_2chunk_8h" alt=""/></div>
<map name="src_2utils_2chunk_8h" id="src_2utils_2chunk_8h">
<area shape="rect" id="node3" href="int_8h.html" title="int.h" alt="" coords="99,80,145,107"/>
</map>
</div>
</div><div class="textblock"><div class="dynheader">
This graph shows which files directly or indirectly include this file:</div>
<div class="dyncontent">
<div class="center"><img src="chunk_8h__dep__incl.png" border="0" usemap="#src_2utils_2chunk_8hdep" alt=""/></div>
<map name="src_2utils_2chunk_8hdep" id="src_2utils_2chunk_8hdep">
<area shape="rect" id="node2" href="chunkref_8h.html" title="src/utils/chunkref.h" alt="" coords="1513,80,1647,107"/>
<area shape="rect" id="node8" href="global_8c.html" title="src/core/global.c" alt="" coords="4417,435,4535,461"/>
<area shape="rect" id="node50" href="chunk_8c.html" title="src/utils/chunk.c" alt="" coords="5149,80,5267,107"/>
<area shape="rect" id="node3" href="msg_8h.html" title="src/utils/msg.h" alt="" coords="1598,163,1705,189"/>
<area shape="rect" id="node48" href="rep_8c.html" title="src/protocols/reqrep\l/rep.c" alt="" coords="1278,155,1415,197"/>
<area shape="rect" id="node49" href="chunkref_8c.html" title="src/utils/chunkref.c" alt="" coords="1440,163,1573,189"/>
<area shape="rect" id="node4" href="transport_8h.html" title="src/transport.h" alt="" coords="2156,253,2263,280"/>
<area shape="rect" id="node44" href="protocol_8h.html" title="src/protocol.h" alt="" coords="3611,253,3712,280"/>
<area shape="rect" id="node45" href="task_8h.html" title="src/protocols/reqrep\l/task.h" alt="" coords="222,246,359,287"/>
<area shape="rect" id="node10" href="sock_8c.html" title="src/core/sock.c" alt="" coords="3405,435,3517,461"/>
<area shape="rect" id="node46" href="msgqueue_8h.html" title="src/transports/inproc\l/msgqueue.h" alt="" coords="5,246,147,287"/>
<area shape="rect" id="node21" href="sinproc_8h.html" title="src/transports/inproc\l/sinproc.h" alt="" coords="140,337,281,378"/>
<area shape="rect" id="node22" href="sipc_8h.html" title="src/transports/ipc\l/sipc.h" alt="" coords="389,427,512,469"/>
<area shape="rect" id="node25" href="slibfabric_8h.html" title="src/transports/libfabric\l/slibfabric.h" alt="" coords="803,427,953,469"/>
<area shape="rect" id="node27" href="stcp_8h.html" title="src/transports/tcp\l/stcp.h" alt="" coords="978,427,1101,469"/>
<area shape="rect" id="node29" href="stcpmux_8h.html" title="src/transports/tcpmux\l/stcpmux.h" alt="" coords="1127,427,1276,469"/>
<area shape="rect" id="node39" href="sws_8h.html" title="src/transports/ws/sws.h" alt="" coords="2252,435,2415,461"/>
<area shape="rect" id="node47" href="src_2utils_2msg_8c.html" title="src/utils/msg.c" alt="" coords="3737,253,3844,280"/>
<area shape="rect" id="node5" href="ep_8c.html" title="src/core/ep.c" alt="" coords="3541,435,3640,461"/>
<area shape="rect" id="node6" href="ep_8h.html" title="src/core/ep.h" alt="" coords="3597,344,3696,371"/>
<area shape="rect" id="node11" href="sock_8h.html" title="src/core/sock.h" alt="" coords="3720,344,3832,371"/>
<area shape="rect" id="node7" href="epbase_8c.html" title="src/core/epbase.c" alt="" coords="3665,435,3791,461"/>
<area shape="rect" id="node12" href="transports_2inproc_2inproc_8h.html" title="src/transports/inproc\l/inproc.h" alt="" coords="4008,337,4149,378"/>
<area shape="rect" id="node13" href="transports_2ipc_2ipc_8h.html" title="src/transports/ipc\l/ipc.h" alt="" coords="4173,337,4296,378"/>
<area shape="rect" id="node14" href="transports_2libfabric_2libfabric_8h.html" title="src/transports/libfabric\l/libfabric.h" alt="" coords="4321,337,4471,378"/>
<area shape="rect" id="node15" href="transports_2tcp_2tcp_8h.html" title="src/transports/tcp\l/tcp.h" alt="" coords="4495,337,4619,378"/>
<area shape="rect" id="node16" href="transports_2ws_2ws_8h.html" title="src/transports/ws/ws.h" alt="" coords="4644,344,4799,371"/>
<area shape="rect" id="node17" href="transports_2tcpmux_2tcpmux_8h.html" title="src/transports/tcpmux\l/tcpmux.h" alt="" coords="4823,337,4972,378"/>
<area shape="rect" id="node9" href="pipe_8c.html" title="src/core/pipe.c" alt="" coords="3815,435,3923,461"/>
<area shape="rect" id="node18" href="ins_8h.html" title="src/transports/inproc\l/ins.h" alt="" coords="637,337,779,378"/>
<area shape="rect" id="node19" href="binproc_8h.html" title="src/transports/inproc\l/binproc.h" alt="" coords="637,427,779,469"/>
<area shape="rect" id="node20" href="cinproc_8h.html" title="src/transports/inproc\l/cinproc.h" alt="" coords="224,427,365,469"/>
<area shape="rect" id="node24" href="streamhdr_8h.html" title="src/transports/utils\l/streamhdr.h" alt="" coords="955,337,1085,378"/>
<area shape="rect" id="node23" href="aipc_8h.html" title="src/transports/ipc\l/aipc.h" alt="" coords="439,518,561,559"/>
<area shape="rect" id="node31" href="bipc_8h.html" title="src/transports/ipc\l/bipc.h" alt="" coords="1312,337,1435,378"/>
<area shape="rect" id="node32" href="cipc_8h.html" title="src/transports/ipc\l/cipc.h" alt="" coords="1459,337,1581,378"/>
<area shape="rect" id="node26" href="alibfabric_8h.html" title="src/transports/libfabric\l/alibfabric.h" alt="" coords="695,518,845,559"/>
<area shape="rect" id="node33" href="blibfabric_8h.html" title="src/transports/libfabric\l/blibfabric.h" alt="" coords="1707,337,1857,378"/>
<area shape="rect" id="node34" href="clibfabric_8h.html" title="src/transports/libfabric\l/clibfabric.h" alt="" coords="1882,337,2032,378"/>
<area shape="rect" id="node28" href="atcp_8h.html" title="src/transports/tcp\l/atcp.h" alt="" coords="1114,518,1237,559"/>
<area shape="rect" id="node35" href="btcp_8h.html" title="src/transports/tcp\l/btcp.h" alt="" coords="2226,337,2349,378"/>
<area shape="rect" id="node36" href="ctcp_8h.html" title="src/transports/tcp\l/ctcp.h" alt="" coords="2374,337,2497,378"/>
<area shape="rect" id="node30" href="atcpmux_8h.html" title="src/transports/tcpmux\l/atcpmux.h" alt="" coords="1407,518,1556,559"/>
<area shape="rect" id="node37" href="btcpmux_8h.html" title="src/transports/tcpmux\l/btcpmux.h" alt="" coords="2573,337,2723,378"/>
<area shape="rect" id="node38" href="ctcpmux_8h.html" title="src/transports/tcpmux\l/ctcpmux.h" alt="" coords="2747,337,2896,378"/>
<area shape="rect" id="node41" href="ws__handshake_8h.html" title="src/transports/ws/ws\l_handshake.h" alt="" coords="2057,337,2201,378"/>
<area shape="rect" id="node40" href="aws_8h.html" title="src/transports/ws/aws.h" alt="" coords="1724,525,1887,552"/>
<area shape="rect" id="node42" href="bws_8h.html" title="src/transports/ws/bws.h" alt="" coords="2971,344,3133,371"/>
<area shape="rect" id="node43" href="cws_8h.html" title="src/transports/ws/cws.h" alt="" coords="3157,344,3320,371"/>
</map>
</div>
</div>
<p><a href="chunk_8h_source.html">Go to the source code of this file.</a></p>
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="func-members"></a>
Functions</h2></td></tr>
<tr class="memitem:a5880eec9e3ff367b028ddbf6bc9c489b"><td class="memItemLeft" align="right" valign="top">int </td><td class="memItemRight" valign="bottom"><a class="el" href="chunk_8h.html#a5880eec9e3ff367b028ddbf6bc9c489b">nn_chunk_alloc</a> (size_t size, int type, void **result)</td></tr>
<tr class="separator:a5880eec9e3ff367b028ddbf6bc9c489b"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ad08bb84f9736073d6b07aa965119fb80"><td class="memItemLeft" align="right" valign="top">int </td><td class="memItemRight" valign="bottom"><a class="el" href="chunk_8h.html#ad08bb84f9736073d6b07aa965119fb80">nn_chunk_realloc</a> (size_t size, void **chunk)</td></tr>
<tr class="separator:ad08bb84f9736073d6b07aa965119fb80"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a56c9113d6f6f59fdc7b401500428ef8c"><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="chunk_8h.html#a56c9113d6f6f59fdc7b401500428ef8c">nn_chunk_free</a> (void *<a class="el" href="jquery_8js.html#a2335e57f79b6acfb6de59c235dc8a83e">p</a>)</td></tr>
<tr class="separator:a56c9113d6f6f59fdc7b401500428ef8c"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a2d4f65ea6ec606640b2180c9c3395f86"><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="chunk_8h.html#a2d4f65ea6ec606640b2180c9c3395f86">nn_chunk_addref</a> (void *<a class="el" href="jquery_8js.html#a2335e57f79b6acfb6de59c235dc8a83e">p</a>, uint32_t n)</td></tr>
<tr class="separator:a2d4f65ea6ec606640b2180c9c3395f86"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:adc70f5d49891f6106301d697e41958c7"><td class="memItemLeft" align="right" valign="top">size_t </td><td class="memItemRight" valign="bottom"><a class="el" href="chunk_8h.html#adc70f5d49891f6106301d697e41958c7">nn_chunk_size</a> (void *<a class="el" href="jquery_8js.html#a2335e57f79b6acfb6de59c235dc8a83e">p</a>)</td></tr>
<tr class="separator:adc70f5d49891f6106301d697e41958c7"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a350644fc39959f8da85676bfc1a2bda4"><td class="memItemLeft" align="right" valign="top">void * </td><td class="memItemRight" valign="bottom"><a class="el" href="chunk_8h.html#a350644fc39959f8da85676bfc1a2bda4">nn_chunk_trim</a> (void *<a class="el" href="jquery_8js.html#a2335e57f79b6acfb6de59c235dc8a83e">p</a>, size_t n)</td></tr>
<tr class="separator:a350644fc39959f8da85676bfc1a2bda4"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<h2 class="groupheader">Function Documentation</h2>
<a class="anchor" id="a2d4f65ea6ec606640b2180c9c3395f86"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void nn_chunk_addref </td>
<td>(</td>
<td class="paramtype">void * </td>
<td class="paramname"><em>p</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">uint32_t </td>
<td class="paramname"><em>n</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</div><div class="memdoc">
</div>
</div>
<a class="anchor" id="a5880eec9e3ff367b028ddbf6bc9c489b"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">int nn_chunk_alloc </td>
<td>(</td>
<td class="paramtype">size_t </td>
<td class="paramname"><em>size</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">int </td>
<td class="paramname"><em>type</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">void ** </td>
<td class="paramname"><em>result</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</div><div class="memdoc">
</div>
</div>
<a class="anchor" id="a56c9113d6f6f59fdc7b401500428ef8c"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void nn_chunk_free </td>
<td>(</td>
<td class="paramtype">void * </td>
<td class="paramname"><em>p</em></td><td>)</td>
<td></td>
</tr>
</table>
</div><div class="memdoc">
</div>
</div>
<a class="anchor" id="ad08bb84f9736073d6b07aa965119fb80"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">int nn_chunk_realloc </td>
<td>(</td>
<td class="paramtype">size_t </td>
<td class="paramname"><em>size</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">void ** </td>
<td class="paramname"><em>chunk</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</div><div class="memdoc">
</div>
</div>
<a class="anchor" id="adc70f5d49891f6106301d697e41958c7"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">size_t nn_chunk_size </td>
<td>(</td>
<td class="paramtype">void * </td>
<td class="paramname"><em>p</em></td><td>)</td>
<td></td>
</tr>
</table>
</div><div class="memdoc">
</div>
</div>
<a class="anchor" id="a350644fc39959f8da85676bfc1a2bda4"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void* nn_chunk_trim </td>
<td>(</td>
<td class="paramtype">void * </td>
<td class="paramname"><em>p</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">size_t </td>
<td class="paramname"><em>n</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</div><div class="memdoc">
</div>
</div>
</div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.11
</small></address>
</body>
</html>
| lalazari/Nanomsg-Libf | html/chunk_8h.html | HTML | mit | 17,752 |
class UsersController < ApplicationController
cache_sweeper :profile_sweeper, :only => [:update_bio]
cache_sweeper :user_sweeper, :only => [:create, :link_user_accounts]
###before_filter :ensure_authenticated_to_facebook, :only => :link_user_accounts
before_filter :find_page_user, :only => [:edit, :update]
before_filter :set_ad_layout, :only => [:index, :show]
before_filter :enable_iframe_urls, :only => [:current]
before_filter :set_meta_klass, :only => [:index]
access_control do
allow all, :to => [:index, :show, :feed, :account_menu, :current, :new, :create]
# HACK:: use current_user.is_admin? rather than current_user.has_role?(:admin)
# FIXME:: get admins switched over to using :admin role
allow :admin, :of => :current_user
allow :admin
allow logged_in, :to => [:update_bio, :dont_ask_me_for_email, :dont_ask_me_invite_friends, :invite]
allow :identity_user, :of => :page_user, :to => [:edit, :update]
end
def index
@page = params[:page].present? ? (params[:page].to_i < 3 ? "page_#{params[:page]}_" : "") : "page_1_"
case params[:top]
when 'daily'
@scores = Score.daily_scores
@current_sub_tab = 'daily'
when 'weekly'
@scores = Score.weekly_scores
@current_sub_tab = 'weekly'
when 'monthly'
@scores = Score.monthly_scores
@current_sub_tab = 'monthly'
when 'yearly'
@scores = Score.yearly_scores
@current_sub_tab = 'yearly'
when 'alltime'
@scores = Score.alltime_scores
@current_sub_tab = 'alltime'
else
@scores = Score.weekly_scores
@current_sub_tab = 'weekly'
end
respond_to do |format|
format.html { @paginate = false }
format.json { @users = User.refine(params) }
end
end
def edit
@user = current_user
end
def update
@user = User.active.find(params[:id])
if @user.user_profile.update_attributes(params[:user][:user_profile]) and @user.update_attributes(params[:user])
flash[:success] = "Successfully updated your settings."
redirect_to user_path(@user)
else
flash[:error] = "Could not update your settings as requested. Please try again."
render :edit
end
end
def feed
render :partial => "pfeeds/pfeed_list", :locals => {:feed_collection => current_user.pfeed_inbox}, :layout => 'application'
end
def new
store_location params[:return_to] if params[:return_to]
@user = User.new
end
def create
unless params[:user].present?
@user = User.new
render :new
return false
end
logout_keeping_session!
@user = User.new(params[:user])
success = @user && @user.save
if success && @user.errors.empty?
# Protects against session fixation attacks, causes request forgery
# protection if visitor resubmits an earlier form using back
# button. Uncomment if you understand the tradeoffs.
# reset session
self.current_user = @user # !! now logged in
redirect_back_or_default(root_url)
flash[:notice] = "Thanks for signing up! We're sending you an email with your activation code."
else
flash[:error] = "We couldn't set up that account, sorry. Please try again, or contact an admin (link is above)."
render :action => 'new'
end
end
def link_user_accounts
if self.current_user.nil?
#register with fb
set_facebook_session unless facebook_session.present?
User.create_from_fb_connect(facebook_session.user)
else
#connect accounts
self.current_user.link_fb_connect(facebook_session.user.id) unless self.current_user.fb_user_id == facebook_session.user.id
end
if canvas?
redirect_top session[:return_to] || root_url(:canvas => true)
session[:return_to] = nil
else
redirect_back_or_default(root_url)
end
end
def show
@user = User.active.find(params[:id])
@activities = ItemAction.newest_for_user(@user, 10)
@articles = @user.articles.active.published.paginate :page => params[:page], :per_page => 10, :order => "created_at desc"
@paginate = true
@is_owner = current_user && (@user.id == current_user.id)
set_current_meta_item @user
respond_to do |format|
format.html
format.atom { @actions = @user.newest_actions }
end
end
def invite
flash[:error] = "User invites is currently disabled"
redirect_to root_url and return
@success = false
if request.post?
if params['action'] == 'invite' and params['ids'].present?
flash[:notice] = "Successfully invited your friends."
@fb_user_ids = params['ids']
@success = true
end
end
end
def dont_ask_me_for_email
if current_user_profile.update_attribute( :dont_ask_me_for_email, true)
flash[:success] = "We will no longer ask you to enable email notifications."
redirect_to root_url
else
flash[:error] = "Could not update your notification settings"
redirect_to root_url
end
end
def dont_ask_me_invite_friends
if current_user_profile.update_attribute( :dont_ask_me_invite_friends, true)
flash[:success] = "We will no longer ask you to invite your friends."
redirect_to root_url
else
flash[:error] = "Could not update your reminder setting for invite friends"
redirect_to root_url
end
end
def update_bio
if request.post?
@profile = current_user_profile
@profile.bio = view_context.linkify view_context.sanitize_user_bio params['bio']
if @profile.save
flash[:success] = "Successfully edited your bio."
redirect_to user_path(@profile.user)
else
flash[:error] = "Could not update your bio."
redirect_to user_path(@profile.user)
end
end
end
def account_menu
respond_to do |format|
format.js
format.html { redirect_to current_user }
end
end
def current
respond_to do |format|
format.js
end
end
def link_twitter_account
end
def set_auto_discovery_rss
unless params[:id].nil?
@user = User.active.find(params[:id])
@auto_discovery_rss = user_path(@user, :format => :atom)
else
@auto_discovery_rss = stories_path(:format => :atom)
end
end
private
def check_valid_user
redirect_to root_url and return false unless current_user == User.active.find(params[:id])
end
def find_page_user
@page_user ||= User.active.find(params[:id])
end
def set_meta_klass
set_current_meta_klass User
end
end
| newscloud/n2 | app/controllers/users_controller.rb | Ruby | mit | 6,571 |
namespace LionFire.Instantiating
{
public interface ITemplateInstance<TemplateType, ParametersType> : ITemplateInstance<TemplateType>
where TemplateType : class, ITemplate
where ParametersType : ITemplateParameters
{
ITemplateParameters Parameters { get; set; }
}
}
| jaredthirsk/Core | src/LionFire.Instantiating.Abstractions/Instantiating/Parameters/ITemplateInstance.Parameterized.cs | C# | mit | 310 |
using System;
using NUnit.Framework;
using System.Collections.Generic;
using System.Linq;
using MSBuild.SCM.Tasks.Git.Client;
using System.IO;
namespace MSBuild.SCM.Tasks.Git.Test
{
[TestFixture]
public class StatusTest
{
private static string dummyRepo = Environment.ExpandEnvironmentVariables("%HOMEDRIVE%%HOMEPATH%") + "\\DummyRepo_Status2";
[OneTimeSetUp]
public static void CreateDummyRepo()
{
if (Directory.Exists(dummyRepo))
{
TasksHelper.DeleteDirectory(dummyRepo, true);
}
Directory.CreateDirectory(dummyRepo);
Directory.SetCurrentDirectory(dummyRepo);
//init empty repo
ClientGit.Instance.ExecCommand("init " + dummyRepo);
}
[Test]
public void LibraryTest()
{
List<string> output = Status.ExecCommand();
Assert.IsTrue(output.Single(s => s != null && s.Contains("On branch master"))!=null);
Assert.IsTrue(output.Single(s => s != null && s.Contains("Initial commit")) != null);
Assert.IsTrue(output.Single(s => s != null && s.Contains("nothing to commit")) != null);
}
[Test]
public void TaskStatusTest()
{
GitStatus t = new GitStatus();
t.BuildEngine = new DummyBuildEngine();
bool result = t.Execute();
Assert.IsTrue(result, "Execution failed");
}
}
}
| giovanebribeiro/msbuildscmtasks | MSBuild.SCM.Tasks.Git.Test/StatusTest.cs | C# | mit | 1,488 |
# StatTracker
A simple web site to track and graph a simple number, like weight.
It will have visualizations using D3.js | ekepes/StatTracker | README.md | Markdown | mit | 121 |
require File.expand_path(File.dirname(__FILE__) + "/../spec_helper")
describe "fills_in" do
before do
@session = Webrat::TestSession.new
end
it "should work with textareas" do
@session.response_body = <<-EOS
<form method="post" action="/login">
<label for="user_text">User Text</label>
<textarea id="user_text" name="user[text]"></textarea>
<input type="submit" />
</form>
EOS
@session.expects(:post).with("/login", "user" => {"text" => "filling text area"})
@session.fills_in "User Text", :with => "filling text area"
@session.clicks_button
end
it "should work with password fields" do
@session.response_body = <<-EOS
<form method="post" action="/login">
<input id="user_text" name="user[text]" type="password" />
<input type="submit" />
</form>
EOS
@session.expects(:post).with("/login", "user" => {"text" => "pass"})
@session.fills_in "user_text", :with => "pass"
@session.clicks_button
end
it "should fail if input not found" do
@session.response_body = <<-EOS
<form method="get" action="/login">
</form>
EOS
lambda { @session.fills_in "Email", :with => "[email protected]" }.should raise_error
end
it "should allow overriding default form values" do
@session.response_body = <<-EOS
<form method="post" action="/login">
<label for="user_email">Email</label>
<input id="user_email" name="user[email]" value="[email protected]" type="text" />
<input type="submit" />
</form>
EOS
@session.expects(:post).with("/login", "user" => {"email" => "[email protected]"})
@session.fills_in "user[email]", :with => "[email protected]"
@session.clicks_button
end
it "should choose the shortest label match" do
@session.response_body = <<-EOS
<form method="post" action="/login">
<label for="user_mail1">Some other mail</label>
<input id="user_mail1" name="user[mail1]" type="text" />
<label for="user_mail2">Some mail</label>
<input id="user_mail2" name="user[mail2]" type="text" />
<input type="submit" />
</form>
EOS
@session.expects(:post).with("/login", "user" => {"mail1" => "", "mail2" => "value"})
@session.fills_in "Some", :with => "value"
@session.clicks_button
end
it "should choose the first label match if closest is a tie" do
@session.response_body = <<-EOS
<form method="post" action="/login">
<label for="user_mail1">Some mail one</label>
<input id="user_mail1" name="user[mail1]" type="text" />
<label for="user_mail2">Some mail two</label>
<input id="user_mail2" name="user[mail2]" type="text" />
<input type="submit" />
</form>
EOS
@session.expects(:post).with("/login", "user" => {"mail1" => "value", "mail2" => ""})
@session.fills_in "Some mail", :with => "value"
@session.clicks_button
end
it "should anchor label matches to start of label" do
@session.response_body = <<-EOS
<form method="post" action="/login">
<label for="user_email">Some mail</label>
<input id="user_email" name="user[email]" value="[email protected]" type="text" />
</form>
EOS
lambda { @session.fills_in "mail", :with => "value" }.should raise_error
end
it "should anchor label matches to word boundaries" do
@session.response_body = <<-EOS
<form method="post" action="/login">
<label for="user_email">Emailtastic</label>
<input id="user_email" name="user[email]" value="[email protected]" type="text" />
</form>
EOS
lambda { @session.fills_in "Email", :with => "value" }.should raise_error
end
it "should work with inputs nested in labels" do
@session.response_body = <<-EOS
<form method="post" action="/login">
<label>
Email
<input id="user_email" name="user[email]" value="[email protected]" type="text" />
</label>
<input type="submit" />
</form>
EOS
@session.expects(:post).with("/login", "user" => {"email" => "[email protected]"})
@session.fills_in "Email", :with => "[email protected]"
@session.clicks_button
end
it "should work with full input names" do
@session.response_body = <<-EOS
<form method="post" action="/login">
<input id="user_email" name="user[email]" type="text" />
<input type="submit" />
</form>
EOS
@session.expects(:post).with("/login", "user" => {"email" => "[email protected]"})
@session.fills_in "user[email]", :with => "[email protected]"
@session.clicks_button
end
it "should work with symbols" do
@session.response_body = <<-EOS
<form method="post" action="/login">
<label for="user_email">Email</label>
<input id="user_email" name="user[email]" type="text" />
<input type="submit" />
</form>
EOS
@session.expects(:post).with("/login", "user" => {"email" => "[email protected]"})
@session.fills_in :email, :with => "[email protected]"
@session.clicks_button
end
end
| ismasan/webrat | spec/api/fills_in_spec.rb | Ruby | mit | 5,158 |
//
// CCGeoHelper.h
// Tracker
//
// Created by apple on 13-12-30.
// Copyright (c) 2013年 Capcare. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "BMapKit.h"
@protocol CCGeoHelperDelegate <NSObject>
-(void) onGetAddress:(NSString*)address;
@end
@interface CCGeoQueryPrams : NSObject
@property (nonatomic, strong) id<CCGeoHelperDelegate> delegate;
@property (nonatomic, assign) CLLocationCoordinate2D coord;
@end
@interface ZWL_GeoHelper : NSObject //<BMKSearchDelegate>
//@property (nonatomic, strong) BMKSearch* search;
//@property (nonatomic, strong) NSMutableDictionary* geoCache;
//@property (nonatomic, strong) NSMutableArray* queryList;
//
//+ (ZWL_GeoHelper *)sharedClient;
//
//-(NSString*) getAddress:(CLLocationCoordinate2D)coord delegate:(id)delegate;
//
//-(void) cleanQueryList;
//- (void)clean;
@end
| MJHelloWorld/KBLove | KBLove/Classes/MapRelated/ZWL_GeoHelper.h | C | mit | 848 |
<form name="$ctrl.testForm" novalidate ng-submit="$ctrl.sendToServer()">
<div>
<fieldset>
<legend>Anrede:</legend>
<label ng-repeat="title in $ctrl.titles" for="{{title}}">
{{title}}
<input type="radio" id="{{title}}" name="title" ng-value="title" ng-model="$ctrl.user.title"/>
</label>
</fieldset>
</div>
<div>
<fieldset>
<legend>Sprache:</legend>
<label ng-repeat="lang in $ctrl.languages" for="{{lang.id}}">
{{lang.long}}
<input type="radio" id="{{lang.id}}" name="lang" ng-value="lang" ng-model="$ctrl.user.lang"/>
</label>
</fieldset>
</div>
<div>
<label for="living">Wohnort:
<select id="living" name="living" id="living" ng-options="city as city.name for city in $ctrl.cities track by city.id"
ng-model="$ctrl.user.living">
<option value="">Stadt auswählen</option>
</select>
</label>
</div>
<div>
<label for="happy">Glücklich?
<input type="checkbox" id="happy" name="happy" ng-model="$ctrl.user.happy" ng-true-value="'yes'"
ng-false-value="'no'"/>
</label>
</div>
<div>
<label for="happyDropdown">Glücklich?
<select id="happyDropdown" name="happyDropdown">
<option ng-selected="$ctrl.user.happy === ''">Noch nicht ausgewählt</option>
<option ng-selected="$ctrl.user.happy === 'yes'">Glücklich</option>
<option ng-selected="$ctrl.user.happy === 'no'">Nicht Glücklich</option>
</select>
</label>
</div>
<div>
<label for="firstName">Vorname:
<input id="firstName" type="text" name="firstName" ng-model="$ctrl.user.firstName"/>
</label>
</div>
<div>
<label for="lastName">Nachname:
<input id="lastName" type="text" name="lastName" ng-model="$ctrl.user.lastName"/>
</label>
</div>
<div>
<label for="age">Alter:
<input id="age" type="number" name="age" ng-model="$ctrl.user.age"/>
</label>
</div>
<button type="submit">Speichern</button>
</form>
| jsperts/workshop_unterlagen | angularjs/examples/10-Forms/app/main.component.html | HTML | mit | 2,034 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SuperMarket.SQLServer.Models
{
public class Expense
{
public int Id { get; set; }
public int VendorId { get; set; }
public Vendor Vendor { get; set; }
public DateTime Month { get; set; }
public decimal ExpenseValue { get; set; }
}
}
| niki-funky/Telerik_Academy | Programming/Database/Teamwork SuperMarket/SuperMarket.SQLServer.Models/Expense.cs | C# | mit | 415 |
import numpy
from baseZhang import calcMFCC, wavread
from pydub import AudioSegment
lab = '01 - 01 Les Jardins Japonais.lab'
label = open(lab, 'r')
labels = label.readlines()
label.close()
# print labels[0]
startTime, endTime, labelY = labels[0].split(' ')
startTime = float(startTime)
endTime = float(endTime)
labelY = labelY[:-1]
# print labelY
song = AudioSegment.from_file(lab.replace('.lab', '.ogg'))
song.set_channels(1)
song = song.export(lab.replace('.lab', '.wav'), 'wav')
audioData, fs = wavread(lab.replace('.lab', '.wav'))
# print len(audioData)
# print fs
part1 = audioData[int(startTime * fs):int(endTime * fs)]
mfcc = calcMFCC(part1, fs)
print numpy.shape(mfcc)
| TheaGao/SklearnModel | ProWav.py | Python | mit | 679 |
<!DOCTYPE html>
<html class="light page-tagsnode">
<head>
<meta charset="utf-8">
<title>Tag: node | Wind</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="keywords" content="ZZR-china,前端,设计,张子锐的博客,前端爱好者,Hexo主题,前端开发,用户体验,nodejs,JavaScript,express,Express" />
<meta property="og:type" content="website">
<meta property="og:title" content="Wind">
<meta property="og:url" content="http://zhangzirui.com/tags/node/index.html">
<meta property="og:site_name" content="Wind">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Wind">
<link rel="icon" href="/images/favicon.ico">
<link href="/css/styles.css?v=028c63b1" rel="stylesheet">
<link rel="stylesheet" href="/css/my.css">
</head>
<body>
<span id="toolbox-mobile" class="toolbox-mobile">盒子</span>
<div class="content content-tag">
<div class="page-header">
<div class="breadcrumb">
<div class="location">标签</div>
<i class="icon-location"></i>
</div>
<div class="toolbox">
<a class="toolbox-entry" href="/">
<span class="toolbox-entry-text">盒子</span>
<i class="icon-angle-down"></i>
<i class="icon-home"></i>
</a>
<ul class="list-toolbox">
<li class="item-toolbox">
<a
class="CIRCLE"
href="/archives/"
target="_self"
>
博客
</a>
</li>
<li class="item-toolbox">
<a
class="CIRCLE"
href="/category/"
target="_self"
>
分类
</a>
</li>
<li class="item-toolbox">
<a
class="CIRCLE"
href="/tag/"
target="_self"
>
标签
</a>
</li>
<li class="item-toolbox">
<a
class="CIRCLE"
href="/link/"
target="_self"
>
友链
</a>
</li>
<li class="item-toolbox">
<a
class="CIRCLE"
href="/about/"
target="_self"
>
关于
</a>
</li>
<li class="item-toolbox">
<a
class="CIRCLE"
href="/atom.xml"
target="_blank"
>
RSS
</a>
</li>
<li class="item-toolbox">
<a
class="CIRCLE"
href="/search/"
target="_self"
>
搜索
</a>
</li>
</ul>
</div>
<div class="box-blog-info">
<a class="avatar" href="/">
<img src="/images/avatar.png" alt="" />
</a>
<div class="info">
<h3 class="name" style="font-family: calligraffittiregular">
Wind
</h3>
<div class="slogan">
Find mean of life
</div>
</div>
</div>
</div>
<section class="tag-box">
<div class="tag-title">标签</div>
<div class="tag-list">
<a class="tag-item" href="#Hexo">
<span class="tag-name">Hexo</span>
<span class="tag-size">( 2 )</span>
</a>
<a class="tag-item" href="#blog">
<span class="tag-name">blog</span>
<span class="tag-size">( 2 )</span>
</a>
<a class="tag-item" href="#css">
<span class="tag-name">css</span>
<span class="tag-size">( 4 )</span>
</a>
<a class="tag-item" href="#es6">
<span class="tag-name">es6</span>
<span class="tag-size">( 1 )</span>
</a>
<a class="tag-item" href="#express">
<span class="tag-name">express</span>
<span class="tag-size">( 2 )</span>
</a>
<a class="tag-item" href="#famous">
<span class="tag-name">famous</span>
<span class="tag-size">( 1 )</span>
</a>
<a class="tag-item" href="#flex">
<span class="tag-name">flex</span>
<span class="tag-size">( 1 )</span>
</a>
<a class="tag-item" href="#git">
<span class="tag-name">git</span>
<span class="tag-size">( 1 )</span>
</a>
<a class="tag-item" href="#hapi">
<span class="tag-name">hapi</span>
<span class="tag-size">( 1 )</span>
</a>
<a class="tag-item" href="#jekyll">
<span class="tag-name">jekyll</span>
<span class="tag-size">( 1 )</span>
</a>
<a class="tag-item" href="#jquery">
<span class="tag-name">jquery</span>
<span class="tag-size">( 1 )</span>
</a>
<a class="tag-item" href="#js">
<span class="tag-name">js</span>
<span class="tag-size">( 9 )</span>
</a>
<a class="tag-item" href="#leancloud">
<span class="tag-name">leancloud</span>
<span class="tag-size">( 1 )</span>
</a>
<a class="tag-item" href="#mean">
<span class="tag-name">mean</span>
<span class="tag-size">( 1 )</span>
</a>
<a class="tag-item" href="#mongodb">
<span class="tag-name">mongodb</span>
<span class="tag-size">( 6 )</span>
</a>
<a class="tag-item" href="#mysql">
<span class="tag-name">mysql</span>
<span class="tag-size">( 1 )</span>
</a>
<a class="tag-item" href="#node">
<span class="tag-name">node</span>
<span class="tag-size">( 4 )</span>
</a>
<a class="tag-item" href="#promise">
<span class="tag-name">promise</span>
<span class="tag-size">( 2 )</span>
</a>
<a class="tag-item" href="#request">
<span class="tag-name">request</span>
<span class="tag-size">( 1 )</span>
</a>
<a class="tag-item" href="#restful">
<span class="tag-name">restful</span>
<span class="tag-size">( 2 )</span>
</a>
<a class="tag-item" href="#search">
<span class="tag-name">search</span>
<span class="tag-size">( 1 )</span>
</a>
<a class="tag-item" href="#theme">
<span class="tag-name">theme</span>
<span class="tag-size">( 1 )</span>
</a>
<a class="tag-item" href="#vue">
<span class="tag-name">vue</span>
<span class="tag-size">( 2 )</span>
</a>
<a class="tag-item" href="#windows">
<span class="tag-name">windows</span>
<span class="tag-size">( 1 )</span>
</a>
<a class="tag-item" href="#三栏布局">
<span class="tag-name">三栏布局</span>
<span class="tag-size">( 1 )</span>
</a>
<a class="tag-item" href="#全栈">
<span class="tag-name">全栈</span>
<span class="tag-size">( 1 )</span>
</a>
<a class="tag-item" href="#教程">
<span class="tag-name">教程</span>
<span class="tag-size">( 2 )</span>
</a>
<a class="tag-item" href="#日记">
<span class="tag-name">日记</span>
<span class="tag-size">( 1 )</span>
</a>
<a class="tag-item" href="#翻译">
<span class="tag-name">翻译</span>
<span class="tag-size">( 1 )</span>
</a>
</div>
</section>
<ul class="list-post"><li id="Hexo" class="item-category-name item-title item-title-0">
<!--
<a href="" class="text-year">
-->
Hexo
<span class="category-count">( 2 )</span>
<!--
</a>
-->
</li>
<li class="item-post item">
<span class="post-date">2016-08-31</span>
<a class="post-title" href="/2016/08/31/2016/08/fexo-theme/">使用fexo主题并添加分页</a>
</li>
<li class="item-post item">
<span class="post-date">2016-08-31</span>
<a class="post-title" href="/2016/08/31/2016/08/hexo-blog/">使用Hexo搭建自己的博客</a>
</li>
<li id="blog" class="item-category-name item-title item-title-1">
<!--
<a href="" class="text-year">
-->
blog
<span class="category-count">( 2 )</span>
<!--
</a>
-->
</li>
<li class="item-post item">
<span class="post-date">2016-08-31</span>
<a class="post-title" href="/2016/08/31/2016/08/fexo-theme/">使用fexo主题并添加分页</a>
</li>
<li class="item-post item">
<span class="post-date">2016-08-31</span>
<a class="post-title" href="/2016/08/31/2016/08/hexo-blog/">使用Hexo搭建自己的博客</a>
</li>
<li id="css" class="item-category-name item-title item-title-2">
<!--
<a href="" class="text-year">
-->
css
<span class="category-count">( 4 )</span>
<!--
</a>
-->
</li>
<li class="item-post item">
<span class="post-date">2016-01-29</span>
<a class="post-title" href="/2016/01/29/2016/01/sudoku-color-change/">颜色变化的九宫格</a>
</li>
<li class="item-post item">
<span class="post-date">2016-03-14</span>
<a class="post-title" href="/2016/03/14/2016/03/css-flex-step1-task10/">FlexBox布局学习总结</a>
</li>
<li class="item-post item">
<span class="post-date">2016-03-15</span>
<a class="post-title" href="/2016/03/15/2016/03/css-three-layout-task3/">三栏式布局学习总结</a>
</li>
<li class="item-post item">
<span class="post-date">2016-09-19</span>
<a class="post-title" href="/2016/09/19/2016/09/applebannerdemo/">苹果首页轮播案例实现</a>
</li>
<li id="es6" class="item-category-name item-title item-title-3">
<!--
<a href="" class="text-year">
-->
es6
<span class="category-count">( 1 )</span>
<!--
</a>
-->
</li>
<li class="item-post item">
<span class="post-date">2016-10-25</span>
<a class="post-title" href="/2016/10/25/2016/10/promise-bluebird/">promise--save you from callback</a>
</li>
<li id="express" class="item-category-name item-title item-title-4">
<!--
<a href="" class="text-year">
-->
express
<span class="category-count">( 2 )</span>
<!--
</a>
-->
</li>
<li class="item-post item">
<span class="post-date">2016-09-08</span>
<a class="post-title" href="/2016/09/08/2016/09/express(1)/">express开发(一)简介与搭建</a>
</li>
<li class="item-post item">
<span class="post-date">2016-09-09</span>
<a class="post-title" href="/2016/09/09/2016/09/express(2)/">express开发(二)引入handlebars</a>
</li>
<li id="famous" class="item-category-name item-title item-title-0">
<!--
<a href="" class="text-year">
-->
famous
<span class="category-count">( 1 )</span>
<!--
</a>
-->
</li>
<li class="item-post item">
<span class="post-date">2015-12-16</span>
<a class="post-title" href="/2015/12/16/2015/Aaron Swartz/">亚伦·斯沃茨( Aaron Swartz)</a>
</li>
<li id="flex" class="item-category-name item-title item-title-1">
<!--
<a href="" class="text-year">
-->
flex
<span class="category-count">( 1 )</span>
<!--
</a>
-->
</li>
<li class="item-post item">
<span class="post-date">2016-03-14</span>
<a class="post-title" href="/2016/03/14/2016/03/css-flex-step1-task10/">FlexBox布局学习总结</a>
</li>
<li id="git" class="item-category-name item-title item-title-2">
<!--
<a href="" class="text-year">
-->
git
<span class="category-count">( 1 )</span>
<!--
</a>
-->
</li>
<li class="item-post item">
<span class="post-date">2015-12-16</span>
<a class="post-title" href="/2015/12/16/2015/Git study/">我的常用Git命令</a>
</li>
<li id="hapi" class="item-category-name item-title item-title-3">
<!--
<a href="" class="text-year">
-->
hapi
<span class="category-count">( 1 )</span>
<!--
</a>
-->
</li>
<li class="item-post item">
<span class="post-date">2016-10-27</span>
<a class="post-title" href="/2016/10/27/2016/10/hapi-first/">HAPI--build reusable api</a>
</li>
<li id="jekyll" class="item-category-name item-title item-title-4">
<!--
<a href="" class="text-year">
-->
jekyll
<span class="category-count">( 1 )</span>
<!--
</a>
-->
</li>
<li class="item-post item">
<span class="post-date">2015-09-12</span>
<a class="post-title" href="/2015/09/12/2015/create-my-blog-with-jekyll1/">Jekyll 搭建静态博客</a>
</li>
<li id="jquery" class="item-category-name item-title item-title-0">
<!--
<a href="" class="text-year">
-->
jquery
<span class="category-count">( 1 )</span>
<!--
</a>
-->
</li>
<li class="item-post item">
<span class="post-date">2016-02-28</span>
<a class="post-title" href="/2016/02/28/2016/02/The Dangers of Stopping Event Propagation/">The Dangers of Stopping Event Propagation</a>
</li>
<li id="js" class="item-category-name item-title item-title-1">
<!--
<a href="" class="text-year">
-->
js
<span class="category-count">( 9 )</span>
<!--
</a>
-->
</li>
<li class="item-post item">
<span class="post-date">2016-09-19</span>
<a class="post-title" href="/2016/09/19/2016/09/applebannerdemo/">苹果首页轮播案例实现</a>
</li>
<li class="item-post item">
<span class="post-date">2016-09-24</span>
<a class="post-title" href="/2016/09/24/2016/09/interviewquestion(1)/">面试(一)</a>
</li>
<li class="item-post item">
<span class="post-date">2016-09-26</span>
<a class="post-title" href="/2016/09/26/2016/09/make es6 in es5/">es6代码的es5实现(转载)</a>
</li>
<li class="item-post item">
<span class="post-date">2016-09-02</span>
<a class="post-title" href="/2016/09/02/2016/09/studyvue1/">学习Vue(一)</a>
</li>
<li class="item-post item">
<span class="post-date">2016-09-20</span>
<a class="post-title" href="/2016/09/20/2016/09/studyvue2/">学习Vue(一)</a>
</li>
<li class="item-post item">
<span class="post-date">2016-09-27</span>
<a class="post-title" href="/2016/09/27/2016/09/transactions in MongoDB/">mongo中实现事务</a>
</li>
<li class="item-post item">
<span class="post-date">2016-10-31</span>
<a class="post-title" href="/2016/10/31/2016/10/error-collection/">error collection</a>
</li>
<li class="item-post item">
<span class="post-date">2016-10-27</span>
<a class="post-title" href="/2016/10/27/2016/10/hapi-first/">HAPI--build reusable api</a>
</li>
<li class="item-post item">
<span class="post-date">2016-10-25</span>
<a class="post-title" href="/2016/10/25/2016/10/promise-bluebird/">promise--save you from callback</a>
</li>
<li id="leancloud" class="item-category-name item-title item-title-2">
<!--
<a href="" class="text-year">
-->
leancloud
<span class="category-count">( 1 )</span>
<!--
</a>
-->
</li>
<li class="item-post item">
<span class="post-date">2016-09-01</span>
<a class="post-title" href="/2016/09/01/2016/09/leancloud(1)/">使用leancloud搭建自己的webapp(一)</a>
</li>
<li id="mean" class="item-category-name item-title item-title-3">
<!--
<a href="" class="text-year">
-->
mean
<span class="category-count">( 1 )</span>
<!--
</a>
-->
</li>
<li class="item-post item">
<span class="post-date">2016-03-01</span>
<a class="post-title" href="/2016/03/01/2016/03/MEAN/">MEAN堆栈入门基础(翻译)</a>
</li>
<li id="mongodb" class="item-category-name item-title item-title-4">
<!--
<a href="" class="text-year">
-->
mongodb
<span class="category-count">( 6 )</span>
<!--
</a>
-->
</li>
<li class="item-post item">
<span class="post-date">2016-01-10</span>
<a class="post-title" href="/2016/01/10/2016/01/create-windows-mongodb/">MongoDB安装成为windows服务</a>
</li>
<li class="item-post item">
<span class="post-date">2016-03-03</span>
<a class="post-title" href="/2016/03/03/2016/03/create-web-express+mongodb+jade/">使用express + jade + mongodb创建网站</a>
</li>
<li class="item-post item">
<span class="post-date">2016-02-20</span>
<a class="post-title" href="/2016/02/20/2016/02/mysql-mongodb/">MongoDB与MySQL的对比</a>
</li>
<li class="item-post item">
<span class="post-date">2016-09-27</span>
<a class="post-title" href="/2016/09/27/2016/09/transactions in MongoDB/">mongo中实现事务</a>
</li>
<li class="item-post item">
<span class="post-date">2016-10-20</span>
<a class="post-title" href="/2016/10/20/2016/10/mongo-restore-dump/">mongo的备份、导入、导出</a>
</li>
<li class="item-post item">
<span class="post-date">2016-10-10</span>
<a class="post-title" href="/2016/10/10/2016/10/mongowhere/">Mongo中的where方法</a>
</li>
<li id="mysql" class="item-category-name item-title item-title-0">
<!--
<a href="" class="text-year">
-->
mysql
<span class="category-count">( 1 )</span>
<!--
</a>
-->
</li>
<li class="item-post item">
<span class="post-date">2016-02-20</span>
<a class="post-title" href="/2016/02/20/2016/02/mysql-mongodb/">MongoDB与MySQL的对比</a>
</li>
<li id="node" class="item-category-name item-title item-title-1">
<!--
<a href="" class="text-year">
-->
node
<span class="category-count">( 4 )</span>
<!--
</a>
-->
</li>
<li class="item-post item">
<span class="post-date">2016-03-03</span>
<a class="post-title" href="/2016/03/03/2016/03/create-web-express+mongodb+jade/">使用express + jade + mongodb创建网站</a>
</li>
<li class="item-post item">
<span class="post-date">2016-09-08</span>
<a class="post-title" href="/2016/09/08/2016/09/express(1)/">express开发(一)简介与搭建</a>
</li>
<li class="item-post item">
<span class="post-date">2016-09-09</span>
<a class="post-title" href="/2016/09/09/2016/09/express(2)/">express开发(二)引入handlebars</a>
</li>
<li class="item-post item">
<span class="post-date">2016-10-23</span>
<a class="post-title" href="/2016/10/23/2016/10/request-package/">request--Simplified HTTP request client</a>
</li>
<li id="promise" class="item-category-name item-title item-title-2">
<!--
<a href="" class="text-year">
-->
promise
<span class="category-count">( 2 )</span>
<!--
</a>
-->
</li>
<li class="item-post item">
<span class="post-date">2016-10-31</span>
<a class="post-title" href="/2016/10/31/2016/10/error-collection/">error collection</a>
</li>
<li class="item-post item">
<span class="post-date">2016-10-25</span>
<a class="post-title" href="/2016/10/25/2016/10/promise-bluebird/">promise--save you from callback</a>
</li>
<li id="request" class="item-category-name item-title item-title-3">
<!--
<a href="" class="text-year">
-->
request
<span class="category-count">( 1 )</span>
<!--
</a>
-->
</li>
<li class="item-post item">
<span class="post-date">2016-10-23</span>
<a class="post-title" href="/2016/10/23/2016/10/request-package/">request--Simplified HTTP request client</a>
</li>
<li id="restful" class="item-category-name item-title item-title-4">
<!--
<a href="" class="text-year">
-->
restful
<span class="category-count">( 2 )</span>
<!--
</a>
-->
</li>
<li class="item-post item">
<span class="post-date">2016-09-01</span>
<a class="post-title" href="/2016/09/01/2016/09/leancloud(1)/">使用leancloud搭建自己的webapp(一)</a>
</li>
<li class="item-post item">
<span class="post-date">2016-09-22</span>
<a class="post-title" href="/2016/09/22/2016/09/restfulgetpostpatch/">restful服务中post/put/patch的区别</a>
</li>
<li id="search" class="item-category-name item-title item-title-0">
<!--
<a href="" class="text-year">
-->
search
<span class="category-count">( 1 )</span>
<!--
</a>
-->
</li>
<li class="item-post item">
<span class="post-date">2016-10-10</span>
<a class="post-title" href="/2016/10/10/2016/10/mongowhere/">Mongo中的where方法</a>
</li>
<li id="theme" class="item-category-name item-title item-title-1">
<!--
<a href="" class="text-year">
-->
theme
<span class="category-count">( 1 )</span>
<!--
</a>
-->
</li>
<li class="item-post item">
<span class="post-date">2016-08-31</span>
<a class="post-title" href="/2016/08/31/2016/08/fexo-theme/">使用fexo主题并添加分页</a>
</li>
<li id="vue" class="item-category-name item-title item-title-2">
<!--
<a href="" class="text-year">
-->
vue
<span class="category-count">( 2 )</span>
<!--
</a>
-->
</li>
<li class="item-post item">
<span class="post-date">2016-09-02</span>
<a class="post-title" href="/2016/09/02/2016/09/studyvue1/">学习Vue(一)</a>
</li>
<li class="item-post item">
<span class="post-date">2016-09-20</span>
<a class="post-title" href="/2016/09/20/2016/09/studyvue2/">学习Vue(一)</a>
</li>
<li id="windows" class="item-category-name item-title item-title-3">
<!--
<a href="" class="text-year">
-->
windows
<span class="category-count">( 1 )</span>
<!--
</a>
-->
</li>
<li class="item-post item">
<span class="post-date">2016-01-10</span>
<a class="post-title" href="/2016/01/10/2016/01/create-windows-mongodb/">MongoDB安装成为windows服务</a>
</li>
<li id="三栏布局" class="item-category-name item-title item-title-4">
<!--
<a href="" class="text-year">
-->
三栏布局
<span class="category-count">( 1 )</span>
<!--
</a>
-->
</li>
<li class="item-post item">
<span class="post-date">2016-03-15</span>
<a class="post-title" href="/2016/03/15/2016/03/css-three-layout-task3/">三栏式布局学习总结</a>
</li>
<li id="全栈" class="item-category-name item-title item-title-0">
<!--
<a href="" class="text-year">
-->
全栈
<span class="category-count">( 1 )</span>
<!--
</a>
-->
</li>
<li class="item-post item">
<span class="post-date">2016-03-01</span>
<a class="post-title" href="/2016/03/01/2016/03/MEAN/">MEAN堆栈入门基础(翻译)</a>
</li>
<li id="教程" class="item-category-name item-title item-title-1">
<!--
<a href="" class="text-year">
-->
教程
<span class="category-count">( 2 )</span>
<!--
</a>
-->
</li>
<li class="item-post item">
<span class="post-date">2015-12-16</span>
<a class="post-title" href="/2015/12/16/2015/Git study/">我的常用Git命令</a>
</li>
<li class="item-post item">
<span class="post-date">2015-09-12</span>
<a class="post-title" href="/2015/09/12/2015/create-my-blog-with-jekyll1/">Jekyll 搭建静态博客</a>
</li>
<li id="日记" class="item-category-name item-title item-title-2">
<!--
<a href="" class="text-year">
-->
日记
<span class="category-count">( 1 )</span>
<!--
</a>
-->
</li>
<li class="item-post item">
<span class="post-date">2016-10-15</span>
<a class="post-title" href="/2016/10/15/2016/10/something of this week10-15/">国庆后的一周</a>
</li>
<li id="翻译" class="item-category-name item-title item-title-3">
<!--
<a href="" class="text-year">
-->
翻译
<span class="category-count">( 1 )</span>
<!--
</a>
-->
</li>
<li class="item-post item">
<span class="post-date">2016-02-28</span>
<a class="post-title" href="/2016/02/28/2016/02/The Dangers of Stopping Event Propagation/">The Dangers of Stopping Event Propagation</a>
</li>
</ul>
</div>
<a id="backTop" class="back-top">
<i class="icon-angle-up"></i>
</a>
<div class="modal" id="modal">
<span id="cover" class="cover hide"></span>
<div id="modal-dialog" class="modal-dialog hide-dialog">
<div class="modal-header">
<span id="close" class="btn-close">关闭</span>
</div>
<hr>
<div class="modal-body">
<ul class="list-toolbox">
<li class="item-toolbox">
<a
class="CIRCLE"
href="/archives/"
target="_self"
>
博客
</a>
</li>
<li class="item-toolbox">
<a
class="CIRCLE"
href="/category/"
target="_self"
>
分类
</a>
</li>
<li class="item-toolbox">
<a
class="CIRCLE"
href="/tag/"
target="_self"
>
标签
</a>
</li>
<li class="item-toolbox">
<a
class="CIRCLE"
href="/link/"
target="_self"
>
友链
</a>
</li>
<li class="item-toolbox">
<a
class="CIRCLE"
href="/about/"
target="_self"
>
关于
</a>
</li>
<li class="item-toolbox">
<a
class="CIRCLE"
href="/atom.xml"
target="_blank"
>
RSS
</a>
</li>
<li class="item-toolbox">
<a
class="CIRCLE"
href="/search/"
target="_self"
>
搜索
</a>
</li>
</ul>
</div>
</div>
</div>
<script type="text/javascript">
function loadScript(url, callback) {
var script = document.createElement('script')
script.type = 'text/javascript';
if (script.readyState) { //IE
script.onreadystatechange = function() {
if (script.readyState == 'loaded' ||
script.readyState == 'complete') {
script.onreadystatechange = null;
callback();
}
};
} else { //Others
script.onload = function() {
callback();
};
}
script.src = url;
document.getElementsByTagName('head')[0].appendChild(script);
}
window.onload = function() {
loadScript('/js/bundle.js?235683', function() {
// load success
});
}
</script>
</body>
</html>
| ZZR-china/zzr-china.github.com | tags/node/index.html | HTML | mit | 26,242 |
<?php
use Kafoso\Questful\Exception\BadRequestException;
use Kafoso\Questful\Factory\Model\QueryParser\QueryParserFactory;
use Kafoso\Questful\Model\Mapping;
use Kafoso\Questful\Model\Mapping\Allowable;
require_once(__DIR__ . "/../vendor/autoload.php");
$url = "http://www.foo.bar/abc?filter%5B%5D=id%3C1";
// Reads as: http://www.foo.bar/abc?filter[]=id>1
$queryParserFactory = new QueryParserFactory;
$queryParser = $queryParserFactory->createFromUri($url);
try {
$queryParser->parse();
$mapping = new Mapping($queryParser);
$mapping
->relate('id', 'u.id')
->allow(new Allowable\Filter\AllowedIntegerFilter("id", ["="]))
->validate();
} catch (BadRequestException $e) {
header("HTTP/1.0 400 Bad Request");
throw $e;
} catch (\Exception $e) {
header("HTTP/1.0 500 Internal Server Error");
throw $e;
}
| kafoso/questful | examples/006-restrict-operators.php | PHP | mit | 859 |
#!/usr/bin/env bash
echo "hello.world 10 1500627240927" | mihkels/graphite-client-kotlin | bash-script-executor/src/test/resources/hello.sh | Shell | mit | 56 |
<?php
use \Curl\MultiCurl;
use \Helper\Test;
class MultiCurlTest extends PHPUnit_Framework_TestCase
{
public function testMultiCurlCallback()
{
$delete_before_send_called = false;
$delete_success_called = false;
$delete_error_called = false;
$delete_complete_called = false;
$download_before_send_called = false;
$download_success_called = false;
$download_error_called = false;
$download_complete_called = false;
$get_before_send_called = false;
$get_success_called = false;
$get_error_called = false;
$get_complete_called = false;
$head_before_send_called = false;
$head_success_called = false;
$head_error_called = false;
$head_complete_called = false;
$options_before_send_called = false;
$options_success_called = false;
$options_error_called = false;
$options_complete_called = false;
$patch_before_send_called = false;
$patch_success_called = false;
$patch_error_called = false;
$patch_complete_called = false;
$post_before_send_called = false;
$post_success_called = false;
$post_error_called = false;
$post_complete_called = false;
$put_before_send_called = false;
$put_success_called = false;
$put_error_called = false;
$put_complete_called = false;
$multi_curl = new MultiCurl();
$multi_curl->beforeSend(function ($instance) use (
&$delete_before_send_called, &$delete_success_called, &$delete_error_called, &$delete_complete_called,
&$download_before_send_called, &$download_success_called, &$download_error_called,
&$download_complete_called,
&$get_before_send_called, &$get_success_called, &$get_error_called, &$get_complete_called,
&$head_before_send_called, &$head_success_called, &$head_error_called, &$head_complete_called,
&$options_before_send_called, &$options_success_called, &$options_error_called, &$options_complete_called,
&$patch_before_send_called, &$patch_success_called, &$patch_error_called, &$patch_complete_called,
&$post_before_send_called, &$post_success_called, &$post_error_called, &$post_complete_called,
&$put_before_send_called, &$put_success_called, &$put_error_called, &$put_complete_called
) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
$request_method = $instance->getOpt(CURLOPT_CUSTOMREQUEST);
if ($request_method === 'DELETE') {
PHPUnit_Framework_Assert::assertFalse($delete_before_send_called);
PHPUnit_Framework_Assert::assertFalse($delete_success_called);
PHPUnit_Framework_Assert::assertFalse($delete_error_called);
PHPUnit_Framework_Assert::assertFalse($delete_complete_called);
$delete_before_send_called = true;
}
if (isset($instance->download)) {
PHPUnit_Framework_Assert::assertFalse($download_before_send_called);
PHPUnit_Framework_Assert::assertFalse($download_success_called);
PHPUnit_Framework_Assert::assertFalse($download_error_called);
PHPUnit_Framework_Assert::assertFalse($download_complete_called);
$download_before_send_called = true;
} elseif ($request_method === 'GET') {
PHPUnit_Framework_Assert::assertFalse($get_before_send_called);
PHPUnit_Framework_Assert::assertFalse($get_success_called);
PHPUnit_Framework_Assert::assertFalse($get_error_called);
PHPUnit_Framework_Assert::assertFalse($get_complete_called);
$get_before_send_called = true;
}
if ($request_method === 'HEAD') {
PHPUnit_Framework_Assert::assertFalse($head_before_send_called);
PHPUnit_Framework_Assert::assertFalse($head_success_called);
PHPUnit_Framework_Assert::assertFalse($head_error_called);
PHPUnit_Framework_Assert::assertFalse($head_complete_called);
$head_before_send_called = true;
}
if ($request_method === 'OPTIONS') {
PHPUnit_Framework_Assert::assertFalse($options_before_send_called);
PHPUnit_Framework_Assert::assertFalse($options_success_called);
PHPUnit_Framework_Assert::assertFalse($options_error_called);
PHPUnit_Framework_Assert::assertFalse($options_complete_called);
$options_before_send_called = true;
}
if ($request_method === 'PATCH') {
PHPUnit_Framework_Assert::assertFalse($patch_before_send_called);
PHPUnit_Framework_Assert::assertFalse($patch_success_called);
PHPUnit_Framework_Assert::assertFalse($patch_error_called);
PHPUnit_Framework_Assert::assertFalse($patch_complete_called);
$patch_before_send_called = true;
}
if ($request_method === 'POST') {
PHPUnit_Framework_Assert::assertFalse($post_before_send_called);
PHPUnit_Framework_Assert::assertFalse($post_success_called);
PHPUnit_Framework_Assert::assertFalse($post_error_called);
PHPUnit_Framework_Assert::assertFalse($post_complete_called);
$post_before_send_called = true;
}
if ($request_method === 'PUT') {
PHPUnit_Framework_Assert::assertFalse($put_before_send_called);
PHPUnit_Framework_Assert::assertFalse($put_success_called);
PHPUnit_Framework_Assert::assertFalse($put_error_called);
PHPUnit_Framework_Assert::assertFalse($put_complete_called);
$put_before_send_called = true;
}
});
$multi_curl->success(function ($instance) use (
&$delete_before_send_called, &$delete_success_called, &$delete_error_called, &$delete_complete_called,
&$download_before_send_called, &$download_success_called, &$download_error_called,
&$download_complete_called,
&$get_before_send_called, &$get_success_called, &$get_error_called, &$get_complete_called,
&$head_before_send_called, &$head_success_called, &$head_error_called, &$head_complete_called,
&$options_before_send_called, &$options_success_called, &$options_error_called, &$options_complete_called,
&$patch_before_send_called, &$patch_success_called, &$patch_error_called, &$patch_complete_called,
&$post_before_send_called, &$post_success_called, &$post_error_called, &$post_complete_called,
&$put_before_send_called, &$put_success_called, &$put_error_called, &$put_complete_called
) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
$request_method = $instance->getOpt(CURLOPT_CUSTOMREQUEST);
if ($request_method === 'DELETE') {
PHPUnit_Framework_Assert::assertTrue($delete_before_send_called);
PHPUnit_Framework_Assert::assertFalse($delete_success_called);
PHPUnit_Framework_Assert::assertFalse($delete_error_called);
PHPUnit_Framework_Assert::assertFalse($delete_complete_called);
$delete_success_called = true;
}
if (isset($instance->download)) {
PHPUnit_Framework_Assert::assertTrue($download_before_send_called);
PHPUnit_Framework_Assert::assertFalse($download_success_called);
PHPUnit_Framework_Assert::assertFalse($download_error_called);
PHPUnit_Framework_Assert::assertFalse($download_complete_called);
$download_success_called = true;
} elseif ($request_method === 'GET') {
PHPUnit_Framework_Assert::assertTrue($get_before_send_called);
PHPUnit_Framework_Assert::assertFalse($get_success_called);
PHPUnit_Framework_Assert::assertFalse($get_error_called);
PHPUnit_Framework_Assert::assertFalse($get_complete_called);
$get_success_called = true;
}
if ($request_method === 'HEAD') {
PHPUnit_Framework_Assert::assertTrue($head_before_send_called);
PHPUnit_Framework_Assert::assertFalse($head_success_called);
PHPUnit_Framework_Assert::assertFalse($head_error_called);
PHPUnit_Framework_Assert::assertFalse($head_complete_called);
$head_success_called = true;
}
if ($request_method === 'OPTIONS') {
PHPUnit_Framework_Assert::assertTrue($options_before_send_called);
PHPUnit_Framework_Assert::assertFalse($options_success_called);
PHPUnit_Framework_Assert::assertFalse($options_error_called);
PHPUnit_Framework_Assert::assertFalse($options_complete_called);
$options_success_called = true;
}
if ($request_method === 'PATCH') {
PHPUnit_Framework_Assert::assertTrue($patch_before_send_called);
PHPUnit_Framework_Assert::assertFalse($patch_success_called);
PHPUnit_Framework_Assert::assertFalse($patch_error_called);
PHPUnit_Framework_Assert::assertFalse($patch_complete_called);
$patch_success_called = true;
}
if ($request_method === 'POST') {
PHPUnit_Framework_Assert::assertTrue($post_before_send_called);
PHPUnit_Framework_Assert::assertFalse($post_success_called);
PHPUnit_Framework_Assert::assertFalse($post_error_called);
PHPUnit_Framework_Assert::assertFalse($post_complete_called);
$post_success_called = true;
}
if ($request_method === 'PUT') {
PHPUnit_Framework_Assert::assertTrue($put_before_send_called);
PHPUnit_Framework_Assert::assertFalse($put_success_called);
PHPUnit_Framework_Assert::assertFalse($put_error_called);
PHPUnit_Framework_Assert::assertFalse($put_complete_called);
$put_success_called = true;
}
});
$multi_curl->error(function ($instance) use (
&$delete_error_called,
&$download_error_called,
&$get_error_called,
&$head_error_called,
&$options_error_called,
&$patch_error_called,
&$post_error_called,
&$put_error_called
) {
$delete_error_called = true;
$download_error_called = true;
$get_error_called = true;
$head_error_called = true;
$options_error_called = true;
$patch_error_called = true;
$post_error_called = true;
$put_error_called = true;
});
$multi_curl->complete(function ($instance) use (
&$delete_before_send_called, &$delete_success_called, &$delete_error_called, &$delete_complete_called,
&$download_before_send_called, &$download_success_called, &$download_error_called,
&$download_complete_called,
&$get_before_send_called, &$get_success_called, &$get_error_called, &$get_complete_called,
&$head_before_send_called, &$head_success_called, &$head_error_called, &$head_complete_called,
&$options_before_send_called, &$options_success_called, &$options_error_called, &$options_complete_called,
&$patch_before_send_called, &$patch_success_called, &$patch_error_called, &$patch_complete_called,
&$post_before_send_called, &$post_success_called, &$post_error_called, &$post_complete_called,
&$put_before_send_called, &$put_success_called, &$put_error_called, &$put_complete_called
) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
$request_method = $instance->getOpt(CURLOPT_CUSTOMREQUEST);
if ($request_method === 'DELETE') {
PHPUnit_Framework_Assert::assertTrue($delete_before_send_called);
PHPUnit_Framework_Assert::assertTrue($delete_success_called);
PHPUnit_Framework_Assert::assertFalse($delete_error_called);
PHPUnit_Framework_Assert::assertFalse($delete_complete_called);
$delete_complete_called = true;
}
if (isset($instance->download)) {
PHPUnit_Framework_Assert::assertTrue($download_before_send_called);
PHPUnit_Framework_Assert::assertTrue($download_success_called);
PHPUnit_Framework_Assert::assertFalse($download_error_called);
PHPUnit_Framework_Assert::assertFalse($download_complete_called);
$download_complete_called = true;
} elseif ($request_method === 'GET') {
PHPUnit_Framework_Assert::assertTrue($get_before_send_called);
PHPUnit_Framework_Assert::assertTrue($get_success_called);
PHPUnit_Framework_Assert::assertFalse($get_error_called);
PHPUnit_Framework_Assert::assertFalse($get_complete_called);
$get_complete_called = true;
}
if ($request_method === 'HEAD') {
PHPUnit_Framework_Assert::assertTrue($head_before_send_called);
PHPUnit_Framework_Assert::assertTrue($head_success_called);
PHPUnit_Framework_Assert::assertFalse($head_error_called);
PHPUnit_Framework_Assert::assertFalse($head_complete_called);
$head_complete_called = true;
}
if ($request_method === 'OPTIONS') {
PHPUnit_Framework_Assert::assertTrue($options_before_send_called);
PHPUnit_Framework_Assert::assertTrue($options_success_called);
PHPUnit_Framework_Assert::assertFalse($options_error_called);
PHPUnit_Framework_Assert::assertFalse($options_complete_called);
$options_complete_called = true;
}
if ($request_method === 'PATCH') {
PHPUnit_Framework_Assert::assertTrue($patch_before_send_called);
PHPUnit_Framework_Assert::assertTrue($patch_success_called);
PHPUnit_Framework_Assert::assertFalse($patch_error_called);
PHPUnit_Framework_Assert::assertFalse($patch_complete_called);
$patch_complete_called = true;
}
if ($request_method === 'POST') {
PHPUnit_Framework_Assert::assertTrue($post_before_send_called);
PHPUnit_Framework_Assert::assertTrue($post_success_called);
PHPUnit_Framework_Assert::assertFalse($post_error_called);
PHPUnit_Framework_Assert::assertFalse($post_complete_called);
$post_complete_called = true;
}
if ($request_method === 'PUT') {
PHPUnit_Framework_Assert::assertTrue($put_before_send_called);
PHPUnit_Framework_Assert::assertTrue($put_success_called);
PHPUnit_Framework_Assert::assertFalse($put_error_called);
PHPUnit_Framework_Assert::assertFalse($put_complete_called);
$put_complete_called = true;
}
});
$multi_curl->addDelete(Test::TEST_URL);
$download_file_path = tempnam('/tmp', 'php-curl-class.');
$multi_curl->addDownload(Test::TEST_URL, $download_file_path)->download = true;
$multi_curl->addGet(Test::TEST_URL);
$multi_curl->addHead(Test::TEST_URL);
$multi_curl->addOptions(Test::TEST_URL);
$multi_curl->addPatch(Test::TEST_URL);
$multi_curl->addPost(Test::TEST_URL);
$multi_curl->addPut(Test::TEST_URL);
$multi_curl->start();
$this->assertTrue($delete_before_send_called);
$this->assertTrue($delete_success_called);
$this->assertFalse($delete_error_called);
$this->assertTrue($delete_complete_called);
$this->assertTrue($download_before_send_called);
$this->assertTrue($download_success_called);
$this->assertFalse($download_error_called);
$this->assertTrue($download_complete_called);
$this->assertTrue(unlink($download_file_path));
$this->assertTrue($get_before_send_called);
$this->assertTrue($get_success_called);
$this->assertFalse($get_error_called);
$this->assertTrue($get_complete_called);
$this->assertTrue($head_before_send_called);
$this->assertTrue($head_success_called);
$this->assertFalse($head_error_called);
$this->assertTrue($head_complete_called);
$this->assertTrue($options_before_send_called);
$this->assertTrue($options_success_called);
$this->assertFalse($options_error_called);
$this->assertTrue($options_complete_called);
$this->assertTrue($patch_before_send_called);
$this->assertTrue($patch_success_called);
$this->assertFalse($patch_error_called);
$this->assertTrue($patch_complete_called);
$this->assertTrue($post_before_send_called);
$this->assertTrue($post_success_called);
$this->assertFalse($post_error_called);
$this->assertTrue($post_complete_called);
$this->assertTrue($put_before_send_called);
$this->assertTrue($put_success_called);
$this->assertFalse($put_error_called);
$this->assertTrue($put_complete_called);
}
public function testMultiCurlCallbackError()
{
$delete_before_send_called = false;
$delete_success_called = false;
$delete_error_called = false;
$delete_complete_called = false;
$download_before_send_called = false;
$download_success_called = false;
$download_error_called = false;
$download_complete_called = false;
$get_before_send_called = false;
$get_success_called = false;
$get_error_called = false;
$get_complete_called = false;
$head_before_send_called = false;
$head_success_called = false;
$head_error_called = false;
$head_complete_called = false;
$options_before_send_called = false;
$options_success_called = false;
$options_error_called = false;
$options_complete_called = false;
$patch_before_send_called = false;
$patch_success_called = false;
$patch_error_called = false;
$patch_complete_called = false;
$post_before_send_called = false;
$post_success_called = false;
$post_error_called = false;
$post_complete_called = false;
$put_before_send_called = false;
$put_success_called = false;
$put_error_called = false;
$put_complete_called = false;
$multi_curl = new MultiCurl();
$multi_curl->beforeSend(function ($instance) use (
&$delete_before_send_called, &$delete_success_called, &$delete_error_called, &$delete_complete_called,
&$download_before_send_called, &$download_success_called, &$download_error_called,
&$download_complete_called,
&$get_before_send_called, &$get_success_called, &$get_error_called, &$get_complete_called,
&$head_before_send_called, &$head_success_called, &$head_error_called, &$head_complete_called,
&$options_before_send_called, &$options_success_called, &$options_error_called, &$options_complete_called,
&$patch_before_send_called, &$patch_success_called, &$patch_error_called, &$patch_complete_called,
&$post_before_send_called, &$post_success_called, &$post_error_called, &$post_complete_called,
&$put_before_send_called, &$put_success_called, &$put_error_called, &$put_complete_called
) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
$request_method = $instance->getOpt(CURLOPT_CUSTOMREQUEST);
if ($request_method === 'DELETE') {
PHPUnit_Framework_Assert::assertFalse($delete_before_send_called);
PHPUnit_Framework_Assert::assertFalse($delete_success_called);
PHPUnit_Framework_Assert::assertFalse($delete_error_called);
PHPUnit_Framework_Assert::assertFalse($delete_complete_called);
$delete_before_send_called = true;
}
if (isset($instance->download)) {
PHPUnit_Framework_Assert::assertFalse($download_before_send_called);
PHPUnit_Framework_Assert::assertFalse($download_success_called);
PHPUnit_Framework_Assert::assertFalse($download_error_called);
PHPUnit_Framework_Assert::assertFalse($download_complete_called);
$download_before_send_called = true;
} elseif ($request_method === 'GET') {
PHPUnit_Framework_Assert::assertFalse($get_before_send_called);
PHPUnit_Framework_Assert::assertFalse($get_success_called);
PHPUnit_Framework_Assert::assertFalse($get_error_called);
PHPUnit_Framework_Assert::assertFalse($get_complete_called);
$get_before_send_called = true;
}
if ($request_method === 'HEAD') {
PHPUnit_Framework_Assert::assertFalse($head_before_send_called);
PHPUnit_Framework_Assert::assertFalse($head_success_called);
PHPUnit_Framework_Assert::assertFalse($head_error_called);
PHPUnit_Framework_Assert::assertFalse($head_complete_called);
$head_before_send_called = true;
}
if ($request_method === 'OPTIONS') {
PHPUnit_Framework_Assert::assertFalse($options_before_send_called);
PHPUnit_Framework_Assert::assertFalse($options_success_called);
PHPUnit_Framework_Assert::assertFalse($options_error_called);
PHPUnit_Framework_Assert::assertFalse($options_complete_called);
$options_before_send_called = true;
}
if ($request_method === 'PATCH') {
PHPUnit_Framework_Assert::assertFalse($patch_before_send_called);
PHPUnit_Framework_Assert::assertFalse($patch_success_called);
PHPUnit_Framework_Assert::assertFalse($patch_error_called);
PHPUnit_Framework_Assert::assertFalse($patch_complete_called);
$patch_before_send_called = true;
}
if ($request_method === 'POST') {
PHPUnit_Framework_Assert::assertFalse($post_before_send_called);
PHPUnit_Framework_Assert::assertFalse($post_success_called);
PHPUnit_Framework_Assert::assertFalse($post_error_called);
PHPUnit_Framework_Assert::assertFalse($post_complete_called);
$post_before_send_called = true;
}
if ($request_method === 'PUT') {
PHPUnit_Framework_Assert::assertFalse($put_before_send_called);
PHPUnit_Framework_Assert::assertFalse($put_success_called);
PHPUnit_Framework_Assert::assertFalse($put_error_called);
PHPUnit_Framework_Assert::assertFalse($put_complete_called);
$put_before_send_called = true;
}
});
$multi_curl->success(function ($instance) use (
&$delete_success_called,
&$download_success_called,
&$get_success_called,
&$head_success_called,
&$options_success_called,
&$patch_success_called,
&$post_success_called,
&$put_success_called
) {
$delete_success_called = true;
$get_success_called = true;
$head_success_called = true;
$options_success_called = true;
$patch_success_called = true;
$post_success_called = true;
$put_success_called = true;
});
$multi_curl->error(function ($instance) use (
&$delete_before_send_called, &$delete_success_called, &$delete_error_called, &$delete_complete_called,
&$download_before_send_called, &$download_success_called, &$download_error_called,
&$download_complete_called,
&$get_before_send_called, &$get_success_called, &$get_error_called, &$get_complete_called,
&$head_before_send_called, &$head_success_called, &$head_error_called, &$head_complete_called,
&$options_before_send_called, &$options_success_called, &$options_error_called, &$options_complete_called,
&$patch_before_send_called, &$patch_success_called, &$patch_error_called, &$patch_complete_called,
&$post_before_send_called, &$post_success_called, &$post_error_called, &$post_complete_called,
&$put_before_send_called, &$put_success_called, &$put_error_called, &$put_complete_called
) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
$request_method = $instance->getOpt(CURLOPT_CUSTOMREQUEST);
if ($request_method === 'DELETE') {
PHPUnit_Framework_Assert::assertTrue($delete_before_send_called);
PHPUnit_Framework_Assert::assertFalse($delete_success_called);
PHPUnit_Framework_Assert::assertFalse($delete_error_called);
PHPUnit_Framework_Assert::assertFalse($delete_complete_called);
$delete_error_called = true;
}
if (isset($instance->download)) {
PHPUnit_Framework_Assert::assertTrue($download_before_send_called);
PHPUnit_Framework_Assert::assertFalse($download_success_called);
PHPUnit_Framework_Assert::assertFalse($download_error_called);
PHPUnit_Framework_Assert::assertFalse($download_complete_called);
$download_error_called = true;
} elseif ($request_method === 'GET') {
PHPUnit_Framework_Assert::assertTrue($get_before_send_called);
PHPUnit_Framework_Assert::assertFalse($get_success_called);
PHPUnit_Framework_Assert::assertFalse($get_error_called);
PHPUnit_Framework_Assert::assertFalse($get_complete_called);
$get_error_called = true;
}
if ($request_method === 'HEAD') {
PHPUnit_Framework_Assert::assertTrue($head_before_send_called);
PHPUnit_Framework_Assert::assertFalse($head_success_called);
PHPUnit_Framework_Assert::assertFalse($head_error_called);
PHPUnit_Framework_Assert::assertFalse($head_complete_called);
$head_error_called = true;
}
if ($request_method === 'OPTIONS') {
PHPUnit_Framework_Assert::assertTrue($options_before_send_called);
PHPUnit_Framework_Assert::assertFalse($options_success_called);
PHPUnit_Framework_Assert::assertFalse($options_error_called);
PHPUnit_Framework_Assert::assertFalse($options_complete_called);
$options_error_called = true;
}
if ($request_method === 'PATCH') {
PHPUnit_Framework_Assert::assertTrue($patch_before_send_called);
PHPUnit_Framework_Assert::assertFalse($patch_success_called);
PHPUnit_Framework_Assert::assertFalse($patch_error_called);
PHPUnit_Framework_Assert::assertFalse($patch_complete_called);
$patch_error_called = true;
}
if ($request_method === 'POST') {
PHPUnit_Framework_Assert::assertTrue($post_before_send_called);
PHPUnit_Framework_Assert::assertFalse($post_success_called);
PHPUnit_Framework_Assert::assertFalse($post_error_called);
PHPUnit_Framework_Assert::assertFalse($post_complete_called);
$post_error_called = true;
}
if ($request_method === 'PUT') {
PHPUnit_Framework_Assert::assertTrue($put_before_send_called);
PHPUnit_Framework_Assert::assertFalse($put_success_called);
PHPUnit_Framework_Assert::assertFalse($put_error_called);
PHPUnit_Framework_Assert::assertFalse($put_complete_called);
$put_error_called = true;
}
});
$multi_curl->complete(function ($instance) use (
&$delete_before_send_called, &$delete_success_called, &$delete_error_called, &$delete_complete_called,
&$download_before_send_called, &$download_success_called, &$download_error_called,
&$download_complete_called,
&$get_before_send_called, &$get_success_called, &$get_error_called, &$get_complete_called,
&$head_before_send_called, &$head_success_called, &$head_error_called, &$head_complete_called,
&$options_before_send_called, &$options_success_called, &$options_error_called, &$options_complete_called,
&$patch_before_send_called, &$patch_success_called, &$patch_error_called, &$patch_complete_called,
&$post_before_send_called, &$post_success_called, &$post_error_called, &$post_complete_called,
&$put_before_send_called, &$put_success_called, &$put_error_called, &$put_complete_called
) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
$request_method = $instance->getOpt(CURLOPT_CUSTOMREQUEST);
if ($request_method === 'DELETE') {
PHPUnit_Framework_Assert::assertTrue($delete_before_send_called);
PHPUnit_Framework_Assert::assertFalse($delete_success_called);
PHPUnit_Framework_Assert::assertTrue($delete_error_called);
PHPUnit_Framework_Assert::assertFalse($delete_complete_called);
$delete_complete_called = true;
}
if (isset($instance->download)) {
PHPUnit_Framework_Assert::assertTrue($download_before_send_called);
PHPUnit_Framework_Assert::assertFalse($download_success_called);
PHPUnit_Framework_Assert::assertTrue($download_error_called);
PHPUnit_Framework_Assert::assertFalse($download_complete_called);
$download_complete_called = true;
} elseif ($request_method === 'GET') {
PHPUnit_Framework_Assert::assertTrue($get_before_send_called);
PHPUnit_Framework_Assert::assertFalse($get_success_called);
PHPUnit_Framework_Assert::assertTrue($get_error_called);
PHPUnit_Framework_Assert::assertFalse($get_complete_called);
$get_complete_called = true;
}
if ($request_method === 'HEAD') {
PHPUnit_Framework_Assert::assertTrue($head_before_send_called);
PHPUnit_Framework_Assert::assertFalse($head_success_called);
PHPUnit_Framework_Assert::assertTrue($head_error_called);
PHPUnit_Framework_Assert::assertFalse($head_complete_called);
$head_complete_called = true;
}
if ($request_method === 'OPTIONS') {
PHPUnit_Framework_Assert::assertTrue($options_before_send_called);
PHPUnit_Framework_Assert::assertFalse($options_success_called);
PHPUnit_Framework_Assert::assertTrue($options_error_called);
PHPUnit_Framework_Assert::assertFalse($options_complete_called);
$options_complete_called = true;
}
if ($request_method === 'PATCH') {
PHPUnit_Framework_Assert::assertTrue($patch_before_send_called);
PHPUnit_Framework_Assert::assertFalse($patch_success_called);
PHPUnit_Framework_Assert::assertTrue($patch_error_called);
PHPUnit_Framework_Assert::assertFalse($patch_complete_called);
$patch_complete_called = true;
}
if ($request_method === 'POST') {
PHPUnit_Framework_Assert::assertTrue($post_before_send_called);
PHPUnit_Framework_Assert::assertFalse($post_success_called);
PHPUnit_Framework_Assert::assertTrue($post_error_called);
PHPUnit_Framework_Assert::assertFalse($post_complete_called);
$post_complete_called = true;
}
if ($request_method === 'PUT') {
PHPUnit_Framework_Assert::assertTrue($put_before_send_called);
PHPUnit_Framework_Assert::assertFalse($put_success_called);
PHPUnit_Framework_Assert::assertTrue($put_error_called);
PHPUnit_Framework_Assert::assertFalse($put_complete_called);
$put_complete_called = true;
}
PHPUnit_Framework_Assert::assertTrue($instance->error);
PHPUnit_Framework_Assert::assertTrue($instance->curlError);
PHPUnit_Framework_Assert::assertFalse($instance->httpError);
PHPUnit_Framework_Assert::assertEquals(CURLE_OPERATION_TIMEOUTED, $instance->errorCode);
PHPUnit_Framework_Assert::assertEquals(CURLE_OPERATION_TIMEOUTED, $instance->curlErrorCode);
});
$multi_curl->addDelete(Test::ERROR_URL);
$download_file_path = tempnam('/tmp', 'php-curl-class.');
$multi_curl->addDownload(Test::ERROR_URL, $download_file_path)->download = true;
$multi_curl->addGet(Test::ERROR_URL);
$multi_curl->addHead(Test::ERROR_URL);
$multi_curl->addOptions(Test::ERROR_URL);
$multi_curl->addPatch(Test::ERROR_URL);
$multi_curl->addPost(Test::ERROR_URL);
$multi_curl->addPut(Test::ERROR_URL);
$multi_curl->start();
$this->assertTrue($delete_before_send_called);
$this->assertFalse($delete_success_called);
$this->assertTrue($delete_error_called);
$this->assertTrue($delete_complete_called);
$this->assertTrue($download_before_send_called);
$this->assertFalse($download_success_called);
$this->assertTrue($download_error_called);
$this->assertTrue($download_complete_called);
$this->assertTrue(unlink($download_file_path));
$this->assertTrue($get_before_send_called);
$this->assertFalse($get_success_called);
$this->assertTrue($get_error_called);
$this->assertTrue($get_complete_called);
$this->assertTrue($head_before_send_called);
$this->assertFalse($head_success_called);
$this->assertTrue($head_error_called);
$this->assertTrue($head_complete_called);
$this->assertTrue($options_before_send_called);
$this->assertFalse($options_success_called);
$this->assertTrue($options_error_called);
$this->assertTrue($options_complete_called);
$this->assertTrue($patch_before_send_called);
$this->assertFalse($patch_success_called);
$this->assertTrue($patch_error_called);
$this->assertTrue($patch_complete_called);
$this->assertTrue($post_before_send_called);
$this->assertFalse($post_success_called);
$this->assertTrue($post_error_called);
$this->assertTrue($post_complete_called);
$this->assertTrue($put_before_send_called);
$this->assertFalse($put_success_called);
$this->assertTrue($put_error_called);
$this->assertTrue($put_complete_called);
}
public function testCurlCallback()
{
$multi_curl = new MultiCurl();
$delete_before_send_called = false;
$delete_success_called = false;
$delete_error_called = false;
$delete_complete_called = false;
$delete = $multi_curl->addDelete(Test::TEST_URL);
$delete->beforeSend(function ($instance) use (
&$delete_before_send_called, &$delete_success_called, &$delete_error_called, &$delete_complete_called
) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
PHPUnit_Framework_Assert::assertFalse($delete_before_send_called);
PHPUnit_Framework_Assert::assertFalse($delete_success_called);
PHPUnit_Framework_Assert::assertFalse($delete_error_called);
PHPUnit_Framework_Assert::assertFalse($delete_complete_called);
$delete_before_send_called = true;
});
$delete->success(function ($instance) use (
&$delete_before_send_called, &$delete_success_called, &$delete_error_called, &$delete_complete_called
) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
PHPUnit_Framework_Assert::assertTrue($delete_before_send_called);
PHPUnit_Framework_Assert::assertFalse($delete_success_called);
PHPUnit_Framework_Assert::assertFalse($delete_error_called);
PHPUnit_Framework_Assert::assertFalse($delete_complete_called);
$delete_success_called = true;
});
$delete->error(function ($instance) use (
&$delete_error_called
) {
$delete_error_called = true;
});
$delete->complete(function ($instance) use (
&$delete_before_send_called, &$delete_success_called, &$delete_error_called, &$delete_complete_called
) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
PHPUnit_Framework_Assert::assertTrue($delete_before_send_called);
PHPUnit_Framework_Assert::assertTrue($delete_success_called);
PHPUnit_Framework_Assert::assertFalse($delete_error_called);
PHPUnit_Framework_Assert::assertFalse($delete_complete_called);
$delete_complete_called = true;
});
$download_before_send_called = false;
$download_success_called = false;
$download_error_called = false;
$download_complete_called = false;
$download_file_path = tempnam('/tmp', 'php-curl-class.');
$download = $multi_curl->addDownload(Test::TEST_URL, $download_file_path);
$download->beforeSend(function ($instance) use (
&$download_before_send_called, &$download_success_called, &$download_error_called,
&$download_complete_called
) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
PHPUnit_Framework_Assert::assertFalse($download_before_send_called);
PHPUnit_Framework_Assert::assertFalse($download_success_called);
PHPUnit_Framework_Assert::assertFalse($download_error_called);
PHPUnit_Framework_Assert::assertFalse($download_complete_called);
$download_before_send_called = true;
});
$download->success(function ($instance) use (
&$download_before_send_called, &$download_success_called, &$download_error_called,
&$download_complete_called
) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
PHPUnit_Framework_Assert::assertTrue($download_before_send_called);
PHPUnit_Framework_Assert::assertFalse($download_success_called);
PHPUnit_Framework_Assert::assertFalse($download_error_called);
PHPUnit_Framework_Assert::assertFalse($download_complete_called);
$download_success_called = true;
});
$download->error(function ($instance) use (
&$download_error_called
) {
$download_error_called = true;
});
$download->complete(function ($instance) use (
&$download_before_send_called, &$download_success_called, &$download_error_called,
&$download_complete_called
) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
PHPUnit_Framework_Assert::assertTrue($download_before_send_called);
PHPUnit_Framework_Assert::assertTrue($download_success_called);
PHPUnit_Framework_Assert::assertFalse($download_error_called);
PHPUnit_Framework_Assert::assertFalse($download_complete_called);
$download_complete_called = true;
});
$get_before_send_called = false;
$get_success_called = false;
$get_error_called = false;
$get_complete_called = false;
$get = $multi_curl->addGet(Test::TEST_URL);
$get->beforeSend(function ($instance) use (
&$get_before_send_called, &$get_success_called, &$get_error_called, &$get_complete_called
) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
PHPUnit_Framework_Assert::assertFalse($get_before_send_called);
PHPUnit_Framework_Assert::assertFalse($get_success_called);
PHPUnit_Framework_Assert::assertFalse($get_error_called);
PHPUnit_Framework_Assert::assertFalse($get_complete_called);
$get_before_send_called = true;
});
$get->success(function ($instance) use (
&$get_before_send_called, &$get_success_called, &$get_error_called, &$get_complete_called
) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
PHPUnit_Framework_Assert::assertTrue($get_before_send_called);
PHPUnit_Framework_Assert::assertFalse($get_success_called);
PHPUnit_Framework_Assert::assertFalse($get_error_called);
PHPUnit_Framework_Assert::assertFalse($get_complete_called);
$get_success_called = true;
});
$get->error(function ($instance) use (
&$get_error_called
) {
$get_error_called = true;
});
$get->complete(function ($instance) use (
&$get_before_send_called, &$get_success_called, &$get_error_called, &$get_complete_called
) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
PHPUnit_Framework_Assert::assertTrue($get_before_send_called);
PHPUnit_Framework_Assert::assertTrue($get_success_called);
PHPUnit_Framework_Assert::assertFalse($get_error_called);
PHPUnit_Framework_Assert::assertFalse($get_complete_called);
$get_complete_called = true;
});
$head_before_send_called = false;
$head_success_called = false;
$head_error_called = false;
$head_complete_called = false;
$head = $multi_curl->addHead(Test::TEST_URL);
$head->beforeSend(function ($instance) use (
&$head_before_send_called, &$head_success_called, &$head_error_called, &$head_complete_called
) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
PHPUnit_Framework_Assert::assertFalse($head_before_send_called);
PHPUnit_Framework_Assert::assertFalse($head_success_called);
PHPUnit_Framework_Assert::assertFalse($head_error_called);
PHPUnit_Framework_Assert::assertFalse($head_complete_called);
$head_before_send_called = true;
});
$head->success(function ($instance) use (
&$head_before_send_called, &$head_success_called, &$head_error_called, &$head_complete_called
) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
PHPUnit_Framework_Assert::assertTrue($head_before_send_called);
PHPUnit_Framework_Assert::assertFalse($head_success_called);
PHPUnit_Framework_Assert::assertFalse($head_error_called);
PHPUnit_Framework_Assert::assertFalse($head_complete_called);
$head_success_called = true;
});
$head->error(function ($instance) use (
&$head_error_called
) {
$head_error_called = true;
});
$head->complete(function ($instance) use (
&$head_before_send_called, &$head_success_called, &$head_error_called, &$head_complete_called
) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
PHPUnit_Framework_Assert::assertTrue($head_before_send_called);
PHPUnit_Framework_Assert::assertTrue($head_success_called);
PHPUnit_Framework_Assert::assertFalse($head_error_called);
PHPUnit_Framework_Assert::assertFalse($head_complete_called);
$head_complete_called = true;
});
$options_before_send_called = false;
$options_success_called = false;
$options_error_called = false;
$options_complete_called = false;
$options = $multi_curl->addOptions(Test::TEST_URL);
$options->beforeSend(function ($instance) use (
&$options_before_send_called, &$options_success_called, &$options_error_called, &$options_complete_called
) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
PHPUnit_Framework_Assert::assertFalse($options_before_send_called);
PHPUnit_Framework_Assert::assertFalse($options_success_called);
PHPUnit_Framework_Assert::assertFalse($options_error_called);
PHPUnit_Framework_Assert::assertFalse($options_complete_called);
$options_before_send_called = true;
});
$options->success(function ($instance) use (
&$options_before_send_called, &$options_success_called, &$options_error_called, &$options_complete_called
) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
PHPUnit_Framework_Assert::assertTrue($options_before_send_called);
PHPUnit_Framework_Assert::assertFalse($options_success_called);
PHPUnit_Framework_Assert::assertFalse($options_error_called);
PHPUnit_Framework_Assert::assertFalse($options_complete_called);
$options_success_called = true;
});
$options->error(function ($instance) use (
&$options_error_called
) {
$options_error_called = true;
});
$options->complete(function ($instance) use (
&$options_before_send_called, &$options_success_called, &$options_error_called, &$options_complete_called
) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
PHPUnit_Framework_Assert::assertTrue($options_before_send_called);
PHPUnit_Framework_Assert::assertTrue($options_success_called);
PHPUnit_Framework_Assert::assertFalse($options_error_called);
PHPUnit_Framework_Assert::assertFalse($options_complete_called);
$options_complete_called = true;
});
$patch_before_send_called = false;
$patch_success_called = false;
$patch_error_called = false;
$patch_complete_called = false;
$patch = $multi_curl->addPatch(Test::TEST_URL);
$patch->beforeSend(function ($instance) use (
&$patch_before_send_called, &$patch_success_called, &$patch_error_called, &$patch_complete_called
) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
PHPUnit_Framework_Assert::assertFalse($patch_before_send_called);
PHPUnit_Framework_Assert::assertFalse($patch_success_called);
PHPUnit_Framework_Assert::assertFalse($patch_error_called);
PHPUnit_Framework_Assert::assertFalse($patch_complete_called);
$patch_before_send_called = true;
});
$patch->success(function ($instance) use (
&$patch_before_send_called, &$patch_success_called, &$patch_error_called, &$patch_complete_called
) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
PHPUnit_Framework_Assert::assertTrue($patch_before_send_called);
PHPUnit_Framework_Assert::assertFalse($patch_success_called);
PHPUnit_Framework_Assert::assertFalse($patch_error_called);
PHPUnit_Framework_Assert::assertFalse($patch_complete_called);
$patch_success_called = true;
});
$patch->error(function ($instance) use (
&$patch_error_called
) {
$patch_error_called = true;
});
$patch->complete(function ($instance) use (
&$patch_before_send_called, &$patch_success_called, &$patch_error_called, &$patch_complete_called
) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
PHPUnit_Framework_Assert::assertTrue($patch_before_send_called);
PHPUnit_Framework_Assert::assertTrue($patch_success_called);
PHPUnit_Framework_Assert::assertFalse($patch_error_called);
PHPUnit_Framework_Assert::assertFalse($patch_complete_called);
$patch_complete_called = true;
});
$post_before_send_called = false;
$post_success_called = false;
$post_error_called = false;
$post_complete_called = false;
$post = $multi_curl->addPost(Test::TEST_URL);
$post->beforeSend(function ($instance) use (
&$post_before_send_called, &$post_success_called, &$post_error_called, &$post_complete_called
) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
PHPUnit_Framework_Assert::assertFalse($post_before_send_called);
PHPUnit_Framework_Assert::assertFalse($post_success_called);
PHPUnit_Framework_Assert::assertFalse($post_error_called);
PHPUnit_Framework_Assert::assertFalse($post_complete_called);
$post_before_send_called = true;
});
$post->success(function ($instance) use (
&$post_before_send_called, &$post_success_called, &$post_error_called, &$post_complete_called
) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
PHPUnit_Framework_Assert::assertTrue($post_before_send_called);
PHPUnit_Framework_Assert::assertFalse($post_success_called);
PHPUnit_Framework_Assert::assertFalse($post_error_called);
PHPUnit_Framework_Assert::assertFalse($post_complete_called);
$post_success_called = true;
});
$post->error(function ($instance) use (
&$post_error_called
) {
$post_error_called = true;
});
$post->complete(function ($instance) use (
&$post_before_send_called, &$post_success_called, &$post_error_called, &$post_complete_called
) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
PHPUnit_Framework_Assert::assertTrue($post_before_send_called);
PHPUnit_Framework_Assert::assertTrue($post_success_called);
PHPUnit_Framework_Assert::assertFalse($post_error_called);
PHPUnit_Framework_Assert::assertFalse($post_complete_called);
$post_complete_called = true;
});
$put_before_send_called = false;
$put_success_called = false;
$put_error_called = false;
$put_complete_called = false;
$put = $multi_curl->addPut(Test::TEST_URL);
$put->beforeSend(function ($instance) use (
&$put_before_send_called, &$put_success_called, &$put_error_called, &$put_complete_called
) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
PHPUnit_Framework_Assert::assertFalse($put_before_send_called);
PHPUnit_Framework_Assert::assertFalse($put_success_called);
PHPUnit_Framework_Assert::assertFalse($put_error_called);
PHPUnit_Framework_Assert::assertFalse($put_complete_called);
$put_before_send_called = true;
});
$put->success(function ($instance) use (
&$put_before_send_called, &$put_success_called, &$put_error_called, &$put_complete_called
) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
PHPUnit_Framework_Assert::assertTrue($put_before_send_called);
PHPUnit_Framework_Assert::assertFalse($put_success_called);
PHPUnit_Framework_Assert::assertFalse($put_error_called);
PHPUnit_Framework_Assert::assertFalse($put_complete_called);
$put_success_called = true;
});
$put->error(function ($instance) use (
&$put_error_called
) {
$put_error_called = true;
});
$put->complete(function ($instance) use (
&$put_before_send_called, &$put_success_called, &$put_error_called, &$put_complete_called
) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
PHPUnit_Framework_Assert::assertTrue($put_before_send_called);
PHPUnit_Framework_Assert::assertTrue($put_success_called);
PHPUnit_Framework_Assert::assertFalse($put_error_called);
PHPUnit_Framework_Assert::assertFalse($put_complete_called);
$put_complete_called = true;
});
$multi_curl->start();
$this->assertTrue($delete_before_send_called);
$this->assertTrue($delete_success_called);
$this->assertFalse($delete_error_called);
$this->assertTrue($delete_complete_called);
$this->assertTrue($download_before_send_called);
$this->assertTrue($download_success_called);
$this->assertFalse($download_error_called);
$this->assertTrue($download_complete_called);
$this->assertTrue(unlink($download_file_path));
$this->assertTrue($get_before_send_called);
$this->assertTrue($get_success_called);
$this->assertFalse($get_error_called);
$this->assertTrue($get_complete_called);
$this->assertTrue($head_before_send_called);
$this->assertTrue($head_success_called);
$this->assertFalse($head_error_called);
$this->assertTrue($head_complete_called);
$this->assertTrue($options_before_send_called);
$this->assertTrue($options_success_called);
$this->assertFalse($options_error_called);
$this->assertTrue($options_complete_called);
$this->assertTrue($patch_before_send_called);
$this->assertTrue($patch_success_called);
$this->assertFalse($patch_error_called);
$this->assertTrue($patch_complete_called);
$this->assertTrue($post_before_send_called);
$this->assertTrue($post_success_called);
$this->assertFalse($post_error_called);
$this->assertTrue($post_complete_called);
$this->assertTrue($put_before_send_called);
$this->assertTrue($put_success_called);
$this->assertFalse($put_error_called);
$this->assertTrue($put_complete_called);
}
public function testCurlCallbackError()
{
$multi_curl = new MultiCurl();
$delete_before_send_called = false;
$delete_success_called = false;
$delete_error_called = false;
$delete_complete_called = false;
$delete = $multi_curl->addDelete(Test::ERROR_URL);
$delete->beforeSend(function ($instance) use (
&$delete_before_send_called, &$delete_success_called, &$delete_error_called, &$delete_complete_called
) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
PHPUnit_Framework_Assert::assertFalse($delete_before_send_called);
PHPUnit_Framework_Assert::assertFalse($delete_success_called);
PHPUnit_Framework_Assert::assertFalse($delete_error_called);
PHPUnit_Framework_Assert::assertFalse($delete_complete_called);
$delete_before_send_called = true;
});
$delete->success(function ($instance) use (
&$delete_success_called
) {
$delete_success_called = true;
});
$delete->error(function ($instance) use (
&$delete_before_send_called, &$delete_success_called, &$delete_error_called, &$delete_complete_called
) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
PHPUnit_Framework_Assert::assertTrue($delete_before_send_called);
PHPUnit_Framework_Assert::assertFalse($delete_success_called);
PHPUnit_Framework_Assert::assertFalse($delete_error_called);
PHPUnit_Framework_Assert::assertFalse($delete_complete_called);
$delete_error_called = true;
});
$delete->complete(function ($instance) use (
&$delete_before_send_called, &$delete_success_called, &$delete_error_called, &$delete_complete_called
) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
PHPUnit_Framework_Assert::assertTrue($delete_before_send_called);
PHPUnit_Framework_Assert::assertFalse($delete_success_called);
PHPUnit_Framework_Assert::assertTrue($delete_error_called);
PHPUnit_Framework_Assert::assertFalse($delete_complete_called);
$delete_complete_called = true;
});
$download_before_send_called = false;
$download_success_called = false;
$download_error_called = false;
$download_complete_called = false;
$download_file_path = tempnam('/tmp', 'php-curl-class.');
$download = $multi_curl->addDownload(Test::ERROR_URL, $download_file_path);
$download->beforeSend(function ($instance) use (
&$download_before_send_called, &$download_success_called, &$download_error_called,
&$download_complete_called
) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
PHPUnit_Framework_Assert::assertFalse($download_before_send_called);
PHPUnit_Framework_Assert::assertFalse($download_success_called);
PHPUnit_Framework_Assert::assertFalse($download_error_called);
PHPUnit_Framework_Assert::assertFalse($download_complete_called);
$download_before_send_called = true;
});
$download->success(function ($instance) use (
&$download_success_called
) {
$download_success_called = true;
});
$download->error(function ($instance) use (
&$download_before_send_called, &$download_success_called, &$download_error_called,
&$download_complete_called
) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
PHPUnit_Framework_Assert::assertTrue($download_before_send_called);
PHPUnit_Framework_Assert::assertFalse($download_success_called);
PHPUnit_Framework_Assert::assertFalse($download_error_called);
PHPUnit_Framework_Assert::assertFalse($download_complete_called);
$download_error_called = true;
});
$download->complete(function ($instance) use (
&$download_before_send_called, &$download_success_called, &$download_error_called,
&$download_complete_called
) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
PHPUnit_Framework_Assert::assertTrue($download_before_send_called);
PHPUnit_Framework_Assert::assertFalse($download_success_called);
PHPUnit_Framework_Assert::assertTrue($download_error_called);
PHPUnit_Framework_Assert::assertFalse($download_complete_called);
$download_complete_called = true;
});
$get_before_send_called = false;
$get_success_called = false;
$get_error_called = false;
$get_complete_called = false;
$get = $multi_curl->addGet(Test::ERROR_URL);
$get->beforeSend(function ($instance) use (
&$get_before_send_called, &$get_success_called, &$get_error_called, &$get_complete_called
) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
PHPUnit_Framework_Assert::assertFalse($get_before_send_called);
PHPUnit_Framework_Assert::assertFalse($get_success_called);
PHPUnit_Framework_Assert::assertFalse($get_error_called);
PHPUnit_Framework_Assert::assertFalse($get_complete_called);
$get_before_send_called = true;
});
$get->success(function ($instance) use (
&$get_success_called
) {
$get_success_called = true;
});
$get->error(function ($instance) use (
&$get_before_send_called, &$get_success_called, &$get_error_called, &$get_complete_called
) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
PHPUnit_Framework_Assert::assertTrue($get_before_send_called);
PHPUnit_Framework_Assert::assertFalse($get_success_called);
PHPUnit_Framework_Assert::assertFalse($get_error_called);
PHPUnit_Framework_Assert::assertFalse($get_complete_called);
$get_error_called = true;
});
$get->complete(function ($instance) use (
&$get_before_send_called, &$get_success_called, &$get_error_called, &$get_complete_called
) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
PHPUnit_Framework_Assert::assertTrue($get_before_send_called);
PHPUnit_Framework_Assert::assertFalse($get_success_called);
PHPUnit_Framework_Assert::assertTrue($get_error_called);
PHPUnit_Framework_Assert::assertFalse($get_complete_called);
$get_complete_called = true;
});
$head_before_send_called = false;
$head_success_called = false;
$head_error_called = false;
$head_complete_called = false;
$head = $multi_curl->addHead(Test::ERROR_URL);
$head->beforeSend(function ($instance) use (
&$head_before_send_called, &$head_success_called, &$head_error_called, &$head_complete_called
) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
PHPUnit_Framework_Assert::assertFalse($head_before_send_called);
PHPUnit_Framework_Assert::assertFalse($head_success_called);
PHPUnit_Framework_Assert::assertFalse($head_error_called);
PHPUnit_Framework_Assert::assertFalse($head_complete_called);
$head_before_send_called = true;
});
$head->success(function ($instance) use (
&$head_success_called
) {
$head_success_called = true;
});
$head->error(function ($instance) use (
&$head_before_send_called, &$head_success_called, &$head_error_called, &$head_complete_called
) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
PHPUnit_Framework_Assert::assertTrue($head_before_send_called);
PHPUnit_Framework_Assert::assertFalse($head_success_called);
PHPUnit_Framework_Assert::assertFalse($head_error_called);
PHPUnit_Framework_Assert::assertFalse($head_complete_called);
$head_error_called = true;
});
$head->complete(function ($instance) use (
&$head_before_send_called, &$head_success_called, &$head_error_called, &$head_complete_called
) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
PHPUnit_Framework_Assert::assertTrue($head_before_send_called);
PHPUnit_Framework_Assert::assertFalse($head_success_called);
PHPUnit_Framework_Assert::assertTrue($head_error_called);
PHPUnit_Framework_Assert::assertFalse($head_complete_called);
$head_complete_called = true;
});
$options_before_send_called = false;
$options_success_called = false;
$options_error_called = false;
$options_complete_called = false;
$options = $multi_curl->addOptions(Test::ERROR_URL);
$options->beforeSend(function ($instance) use (
&$options_before_send_called, &$options_success_called, &$options_error_called, &$options_complete_called
) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
PHPUnit_Framework_Assert::assertFalse($options_before_send_called);
PHPUnit_Framework_Assert::assertFalse($options_success_called);
PHPUnit_Framework_Assert::assertFalse($options_error_called);
PHPUnit_Framework_Assert::assertFalse($options_complete_called);
$options_before_send_called = true;
});
$options->success(function ($instance) use (
&$options_success_called
) {
$options_success_called = true;
});
$options->error(function ($instance) use (
&$options_before_send_called, &$options_success_called, &$options_error_called, &$options_complete_called
) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
PHPUnit_Framework_Assert::assertTrue($options_before_send_called);
PHPUnit_Framework_Assert::assertFalse($options_success_called);
PHPUnit_Framework_Assert::assertFalse($options_error_called);
PHPUnit_Framework_Assert::assertFalse($options_complete_called);
$options_error_called = true;
});
$options->complete(function ($instance) use (
&$options_before_send_called, &$options_success_called, &$options_error_called, &$options_complete_called
) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
PHPUnit_Framework_Assert::assertTrue($options_before_send_called);
PHPUnit_Framework_Assert::assertFalse($options_success_called);
PHPUnit_Framework_Assert::assertTrue($options_error_called);
PHPUnit_Framework_Assert::assertFalse($options_complete_called);
$options_complete_called = true;
});
$patch_before_send_called = false;
$patch_success_called = false;
$patch_error_called = false;
$patch_complete_called = false;
$patch = $multi_curl->addPatch(Test::ERROR_URL);
$patch->beforeSend(function ($instance) use (
&$patch_before_send_called, &$patch_success_called, &$patch_error_called, &$patch_complete_called
) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
PHPUnit_Framework_Assert::assertFalse($patch_before_send_called);
PHPUnit_Framework_Assert::assertFalse($patch_success_called);
PHPUnit_Framework_Assert::assertFalse($patch_error_called);
PHPUnit_Framework_Assert::assertFalse($patch_complete_called);
$patch_before_send_called = true;
});
$patch->success(function ($instance) use (
&$patch_success_called
) {
$patch_success_called = true;
});
$patch->error(function ($instance) use (
&$patch_before_send_called, &$patch_success_called, &$patch_error_called, &$patch_complete_called
) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
PHPUnit_Framework_Assert::assertTrue($patch_before_send_called);
PHPUnit_Framework_Assert::assertFalse($patch_success_called);
PHPUnit_Framework_Assert::assertFalse($patch_error_called);
PHPUnit_Framework_Assert::assertFalse($patch_complete_called);
$patch_error_called = true;
});
$patch->complete(function ($instance) use (
&$patch_before_send_called, &$patch_success_called, &$patch_error_called, &$patch_complete_called
) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
PHPUnit_Framework_Assert::assertTrue($patch_before_send_called);
PHPUnit_Framework_Assert::assertFalse($patch_success_called);
PHPUnit_Framework_Assert::assertTrue($patch_error_called);
PHPUnit_Framework_Assert::assertFalse($patch_complete_called);
$patch_complete_called = true;
});
$post_before_send_called = false;
$post_success_called = false;
$post_error_called = false;
$post_complete_called = false;
$post = $multi_curl->addPost(Test::ERROR_URL);
$post->beforeSend(function ($instance) use (
&$post_before_send_called, &$post_success_called, &$post_error_called, &$post_complete_called
) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
PHPUnit_Framework_Assert::assertFalse($post_before_send_called);
PHPUnit_Framework_Assert::assertFalse($post_success_called);
PHPUnit_Framework_Assert::assertFalse($post_error_called);
PHPUnit_Framework_Assert::assertFalse($post_complete_called);
$post_before_send_called = true;
});
$post->success(function ($instance) use (
&$post_success_called
) {
$post_sucess_called = true;
});
$post->error(function ($instance) use (
&$post_before_send_called, &$post_success_called, &$post_error_called, &$post_complete_called
) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
PHPUnit_Framework_Assert::assertTrue($post_before_send_called);
PHPUnit_Framework_Assert::assertFalse($post_success_called);
PHPUnit_Framework_Assert::assertFalse($post_error_called);
PHPUnit_Framework_Assert::assertFalse($post_complete_called);
$post_error_called = true;
});
$post->complete(function ($instance) use (
&$post_before_send_called, &$post_success_called, &$post_error_called, &$post_complete_called
) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
PHPUnit_Framework_Assert::assertTrue($post_before_send_called);
PHPUnit_Framework_Assert::assertFalse($post_success_called);
PHPUnit_Framework_Assert::assertTrue($post_error_called);
PHPUnit_Framework_Assert::assertFalse($post_complete_called);
$post_complete_called = true;
});
$put_before_send_called = false;
$put_success_called = false;
$put_error_called = false;
$put_complete_called = false;
$put = $multi_curl->addPut(Test::ERROR_URL);
$put->beforeSend(function ($instance) use (
&$put_before_send_called, &$put_success_called, &$put_error_called, &$put_complete_called
) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
PHPUnit_Framework_Assert::assertFalse($put_before_send_called);
PHPUnit_Framework_Assert::assertFalse($put_success_called);
PHPUnit_Framework_Assert::assertFalse($put_error_called);
PHPUnit_Framework_Assert::assertFalse($put_complete_called);
$put_before_send_called = true;
});
$put->success(function ($instance) use (
&$put_success_called
) {
$put_success_called = true;
});
$put->error(function ($instance) use (
&$put_before_send_called, &$put_success_called, &$put_error_called, &$put_complete_called
) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
PHPUnit_Framework_Assert::assertTrue($put_before_send_called);
PHPUnit_Framework_Assert::assertFalse($put_success_called);
PHPUnit_Framework_Assert::assertFalse($put_error_called);
PHPUnit_Framework_Assert::assertFalse($put_complete_called);
$put_error_called = true;
});
$put->complete(function ($instance) use (
&$put_before_send_called, &$put_success_called, &$put_error_called, &$put_complete_called
) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
PHPUnit_Framework_Assert::assertTrue($put_before_send_called);
PHPUnit_Framework_Assert::assertFalse($put_success_called);
PHPUnit_Framework_Assert::assertTrue($put_error_called);
PHPUnit_Framework_Assert::assertFalse($put_complete_called);
$put_complete_called = true;
});
$multi_curl->start();
$this->assertTrue($delete_before_send_called);
$this->assertFalse($delete_success_called);
$this->assertTrue($delete_error_called);
$this->assertTrue($delete_complete_called);
$this->assertTrue($download_before_send_called);
$this->assertFalse($download_success_called);
$this->assertTrue($download_error_called);
$this->assertTrue($download_complete_called);
$this->assertTrue(unlink($download_file_path));
$this->assertTrue($get_before_send_called);
$this->assertFalse($get_success_called);
$this->assertTrue($get_error_called);
$this->assertTrue($get_complete_called);
$this->assertTrue($head_before_send_called);
$this->assertFalse($head_success_called);
$this->assertTrue($head_error_called);
$this->assertTrue($head_complete_called);
$this->assertTrue($options_before_send_called);
$this->assertFalse($options_success_called);
$this->assertTrue($options_error_called);
$this->assertTrue($options_complete_called);
$this->assertTrue($patch_before_send_called);
$this->assertFalse($patch_success_called);
$this->assertTrue($patch_error_called);
$this->assertTrue($patch_complete_called);
$this->assertTrue($post_before_send_called);
$this->assertFalse($post_success_called);
$this->assertTrue($post_error_called);
$this->assertTrue($post_complete_called);
$this->assertTrue($put_before_send_called);
$this->assertFalse($put_success_called);
$this->assertTrue($put_error_called);
$this->assertTrue($put_complete_called);
}
public function testCurlCallbackOverride()
{
$multi_curl = new MultiCurl();
$multi_curl->beforeSend(function () {
PHPUnit_Framework_Assert::assertFalse(true);
});
$multi_curl->success(function () {
PHPUnit_Framework_Assert::assertFalse(true);
});
$multi_curl->error(function () {
PHPUnit_Framework_Assert::assertFalse(true);
});
$multi_curl->complete(function () {
PHPUnit_Framework_Assert::assertFalse(true);
});
$delete_before_send_called = false;
$delete_success_called = false;
$delete_error_called = false;
$delete_complete_called = false;
$delete = $multi_curl->addDelete(Test::TEST_URL);
$delete->beforeSend(function ($instance) use (&$delete_before_send_called) {
$delete_before_send_called = true;
});
$delete->success(function ($instance) use (&$delete_success_called) {
$delete_success_called = true;
});
$delete->error(function ($instance) use (&$delete_error_called) {
$delete_error_called = true;
});
$delete->complete(function ($instance) use (&$delete_complete_called) {
$delete_complete_called = true;
});
$download_before_send_called = false;
$download_success_called = false;
$download_error_called = false;
$download_complete_called = false;
$download_file_path = tempnam('/tmp', 'php-curl-class.');
$download = $multi_curl->addDownload(Test::TEST_URL, $download_file_path);
$download->beforeSend(function ($instance) use (&$download_before_send_called) {
$download_before_send_called = true;
});
$download->success(function ($instance) use (&$download_success_called) {
$download_success_called = true;
});
$download->error(function ($instance) use (&$download_error_called) {
$download_error_called = true;
});
$download->complete(function ($instance) use (&$download_complete_called) {
$download_complete_called = true;
});
$get_before_send_called = false;
$get_success_called = false;
$get_error_called = false;
$get_complete_called = false;
$get = $multi_curl->addGet(Test::TEST_URL);
$get->beforeSend(function ($instance) use (&$get_before_send_called) {
$get_before_send_called = true;
});
$get->success(function ($instance) use (&$get_success_called) {
$get_success_called = true;
});
$get->error(function ($instance) use (&$get_error_called) {
$get_error_called = true;
});
$get->complete(function ($instance) use (&$get_complete_called) {
$get_complete_called = true;
});
$head_before_send_called = false;
$head_success_called = false;
$head_error_called = false;
$head_complete_called = false;
$head = $multi_curl->addHead(Test::TEST_URL);
$head->beforeSend(function ($instance) use (&$head_before_send_called) {
$head_before_send_called = true;
});
$head->success(function ($instance) use (&$head_success_called) {
$head_success_called = true;
});
$head->error(function ($instance) use (&$head_error_called) {
$head_error_called = true;
});
$head->complete(function ($instance) use (&$head_complete_called) {
$head_complete_called = true;
});
$options_before_send_called = false;
$options_success_called = false;
$options_error_called = false;
$options_complete_called = false;
$options = $multi_curl->addOptions(Test::TEST_URL);
$options->beforeSend(function ($instance) use (&$options_before_send_called) {
$options_before_send_called = true;
});
$options->success(function ($instance) use (&$options_success_called) {
$options_success_called = true;
});
$options->error(function ($instance) use (&$options_error_called) {
$options_error_called = true;
});
$options->complete(function ($instance) use (&$options_complete_called) {
$options_complete_called = true;
});
$patch_before_send_called = false;
$patch_success_called = false;
$patch_error_called = false;
$patch_complete_called = false;
$patch = $multi_curl->addPatch(Test::TEST_URL);
$patch->beforeSend(function ($instance) use (&$patch_before_send_called) {
$patch_before_send_called = true;
});
$patch->success(function ($instance) use (&$patch_success_called) {
$patch_success_called = true;
});
$patch->error(function ($instance) use (&$patch_error_called) {
$patch_error_called = true;
});
$patch->complete(function ($instance) use (&$patch_complete_called) {
$patch_complete_called = true;
});
$post_before_send_called = false;
$post_success_called = false;
$post_error_called = false;
$post_complete_called = false;
$post = $multi_curl->addPost(Test::TEST_URL);
$post->beforeSend(function ($instance) use (&$post_before_send_called) {
$post_before_send_called = true;
});
$post->success(function ($instance) use (&$post_success_called) {
$post_success_called = true;
});
$post->error(function ($instance) use (&$post_error_called) {
$post_error_called = true;
});
$post->complete(function ($instance) use (&$post_complete_called) {
$post_complete_called = true;
});
$put_before_send_called = false;
$put_success_called = false;
$put_error_called = false;
$put_complete_called = false;
$put = $multi_curl->addPut(Test::TEST_URL);
$put->beforeSend(function ($instance) use (&$put_before_send_called) {
$put_before_send_called = true;
});
$put->success(function ($instance) use (&$put_success_called) {
$put_success_called = true;
});
$put->error(function ($instance) use (&$put_error_called) {
$put_error_called = true;
});
$put->complete(function ($instance) use (&$put_complete_called) {
$put_complete_called = true;
});
$multi_curl->start();
$this->assertTrue($delete_before_send_called);
$this->assertTrue($delete_success_called);
$this->assertFalse($delete_error_called);
$this->assertTrue($delete_complete_called);
$this->assertTrue($download_before_send_called);
$this->assertTrue($download_success_called);
$this->assertFalse($download_error_called);
$this->assertTrue($download_complete_called);
$this->assertTrue(unlink($download_file_path));
$this->assertTrue($get_before_send_called);
$this->assertTrue($get_success_called);
$this->assertFalse($get_error_called);
$this->assertTrue($get_complete_called);
$this->assertTrue($head_before_send_called);
$this->assertTrue($head_success_called);
$this->assertFalse($head_error_called);
$this->assertTrue($head_complete_called);
$this->assertTrue($options_before_send_called);
$this->assertTrue($options_success_called);
$this->assertFalse($options_error_called);
$this->assertTrue($options_complete_called);
$this->assertTrue($patch_before_send_called);
$this->assertTrue($patch_success_called);
$this->assertFalse($patch_error_called);
$this->assertTrue($patch_complete_called);
$this->assertTrue($post_before_send_called);
$this->assertTrue($post_success_called);
$this->assertFalse($post_error_called);
$this->assertTrue($post_complete_called);
$this->assertTrue($put_before_send_called);
$this->assertTrue($put_success_called);
$this->assertFalse($put_error_called);
$this->assertTrue($put_complete_called);
}
public function testCurlCallbackAddedAfter()
{
$delete_before_send_called = false;
$delete_success_called = false;
$delete_error_called = false;
$delete_complete_called = false;
$multi_curl = new MultiCurl();
$multi_curl->addDelete(Test::TEST_URL);
$multi_curl->beforeSend(function ($instance) use (&$delete_before_send_called) {
$delete_before_send_called = true;
});
$multi_curl->success(function ($instance) use (&$delete_success_called) {
$delete_success_called = true;
});
$multi_curl->error(function ($instance) use (&$delete_error_called) {
$delete_error_called = true;
});
$multi_curl->complete(function ($instance) use (&$delete_complete_called) {
$delete_complete_called = true;
});
$multi_curl->start();
$this->assertTrue($delete_before_send_called);
$this->assertTrue($delete_success_called);
$this->assertFalse($delete_error_called);
$this->assertTrue($delete_complete_called);
$download_before_send_called = false;
$download_success_called = false;
$download_error_called = false;
$download_complete_called = false;
$download_file_path = tempnam('/tmp', 'php-curl-class.');
$multi_curl = new MultiCurl();
$multi_curl->addDownload(Test::TEST_URL, $download_file_path);
$multi_curl->beforeSend(function ($instance) use (&$download_before_send_called) {
$download_before_send_called = true;
});
$multi_curl->success(function ($instance) use (&$download_success_called) {
$download_success_called = true;
});
$multi_curl->error(function ($instance) use (&$download_error_called) {
$download_error_called = true;
});
$multi_curl->complete(function ($instance) use (&$download_complete_called) {
$download_complete_called = true;
});
$multi_curl->start();
$this->assertTrue($download_before_send_called);
$this->assertTrue($download_success_called);
$this->assertFalse($download_error_called);
$this->assertTrue($download_complete_called);
$this->assertTrue(unlink($download_file_path));
$get_before_send_called = false;
$get_success_called = false;
$get_error_called = false;
$get_complete_called = false;
$multi_curl = new MultiCurl();
$multi_curl->addGet(Test::TEST_URL);
$multi_curl->beforeSend(function ($instance) use (&$get_before_send_called) {
$get_before_send_called = true;
});
$multi_curl->success(function ($instance) use (&$get_success_called) {
$get_success_called = true;
});
$multi_curl->error(function ($instance) use (&$get_error_called) {
$get_error_called = true;
});
$multi_curl->complete(function ($instance) use (&$get_complete_called) {
$get_complete_called = true;
});
$multi_curl->start();
$this->assertTrue($get_before_send_called);
$this->assertTrue($get_success_called);
$this->assertFalse($get_error_called);
$this->assertTrue($get_complete_called);
$head_before_send_called = false;
$head_success_called = false;
$head_error_called = false;
$head_complete_called = false;
$multi_curl = new MultiCurl();
$multi_curl->addHead(Test::TEST_URL);
$multi_curl->beforeSend(function ($instance) use (&$head_before_send_called) {
$head_before_send_called = true;
});
$multi_curl->success(function ($instance) use (&$head_success_called) {
$head_success_called = true;
});
$multi_curl->error(function ($instance) use (&$head_error_called) {
$head_error_called = true;
});
$multi_curl->complete(function ($instance) use (&$head_complete_called) {
$head_complete_called = true;
});
$multi_curl->start();
$this->assertTrue($head_before_send_called);
$this->assertTrue($head_success_called);
$this->assertFalse($head_error_called);
$this->assertTrue($head_complete_called);
$options_before_send_called = false;
$options_success_called = false;
$options_error_called = false;
$options_complete_called = false;
$multi_curl = new MultiCurl();
$multi_curl->addOptions(Test::TEST_URL);
$multi_curl->beforeSend(function ($instance) use (&$options_before_send_called) {
$options_before_send_called = true;
});
$multi_curl->success(function ($instance) use (&$options_success_called) {
$options_success_called = true;
});
$multi_curl->error(function ($instance) use (&$options_error_called) {
$options_error_called = true;
});
$multi_curl->complete(function ($instance) use (&$options_complete_called) {
$options_complete_called = true;
});
$multi_curl->start();
$this->assertTrue($options_before_send_called);
$this->assertTrue($options_success_called);
$this->assertFalse($options_error_called);
$this->assertTrue($options_complete_called);
$patch_before_send_called = false;
$patch_success_called = false;
$patch_error_called = false;
$patch_complete_called = false;
$multi_curl = new MultiCurl();
$multi_curl->addPatch(Test::TEST_URL);
$multi_curl->beforeSend(function ($instance) use (&$patch_before_send_called) {
$patch_before_send_called = true;
});
$multi_curl->success(function ($instance) use (&$patch_success_called) {
$patch_success_called = true;
});
$multi_curl->error(function ($instance) use (&$patch_error_called) {
$patch_error_called = true;
});
$multi_curl->complete(function ($instance) use (&$patch_complete_called) {
$patch_complete_called = true;
});
$multi_curl->start();
$this->assertTrue($patch_before_send_called);
$this->assertTrue($patch_success_called);
$this->assertFalse($patch_error_called);
$this->assertTrue($patch_complete_called);
$post_before_send_called = false;
$post_success_called = false;
$post_error_called = false;
$post_complete_called = false;
$multi_curl = new MultiCurl();
$multi_curl->addPost(Test::TEST_URL);
$multi_curl->beforeSend(function ($instance) use (&$post_before_send_called) {
$post_before_send_called = true;
});
$multi_curl->success(function ($instance) use (&$post_success_called) {
$post_success_called = true;
});
$multi_curl->error(function ($instance) use (&$post_error_called) {
$post_error_called = true;
});
$multi_curl->complete(function ($instance) use (&$post_complete_called) {
$post_complete_called = true;
});
$multi_curl->start();
$this->assertTrue($post_before_send_called);
$this->assertTrue($post_success_called);
$this->assertFalse($post_error_called);
$this->assertTrue($post_complete_called);
$put_before_send_called = false;
$put_success_called = false;
$put_error_called = false;
$put_complete_called = false;
$multi_curl = new MultiCurl();
$multi_curl->addPut(Test::TEST_URL);
$multi_curl->beforeSend(function ($instance) use (&$put_before_send_called) {
$put_before_send_called = true;
});
$multi_curl->success(function ($instance) use (&$put_success_called) {
$put_success_called = true;
});
$multi_curl->error(function ($instance) use (&$put_error_called) {
$put_error_called = true;
});
$multi_curl->complete(function ($instance) use (&$put_complete_called) {
$put_complete_called = true;
});
$multi_curl->start();
$this->assertTrue($put_before_send_called);
$this->assertTrue($put_success_called);
$this->assertFalse($put_error_called);
$this->assertTrue($put_complete_called);
}
public function testSetOptAndSetOptOverride()
{
$multi_curl_user_agent = 'multi curl user agent';
$curl_user_agent = 'curl user agent';
$data = array('key' => 'HTTP_USER_AGENT');
$multi_curl = new MultiCurl();
$multi_curl->setHeader('X-DEBUG-TEST', 'server');
$multi_curl->setOpt(CURLOPT_USERAGENT, $multi_curl_user_agent);
$get_1 = $multi_curl->addGet(Test::TEST_URL, $data);
$get_1->complete(function ($instance) use ($multi_curl_user_agent) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
PHPUnit_Framework_Assert::assertEquals($multi_curl_user_agent, $instance->getOpt(CURLOPT_USERAGENT));
PHPUnit_Framework_Assert::assertEquals($multi_curl_user_agent, $instance->response);
});
$get_2 = $multi_curl->addGet(Test::TEST_URL, $data);
$get_2->beforeSend(function ($instance) use ($curl_user_agent) {
$instance->setOpt(CURLOPT_USERAGENT, $curl_user_agent);
});
$get_2->complete(function ($instance) use ($curl_user_agent) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
PHPUnit_Framework_Assert::assertEquals($curl_user_agent, $instance->getOpt(CURLOPT_USERAGENT));
PHPUnit_Framework_Assert::assertEquals($curl_user_agent, $instance->response);
});
$multi_curl->start();
$this->assertEquals($multi_curl_user_agent, $multi_curl->getOpt(CURLOPT_USERAGENT));
$this->assertEquals($multi_curl_user_agent, $get_1->getOpt(CURLOPT_USERAGENT));
$this->assertEquals($multi_curl_user_agent, $get_1->response);
$this->assertEquals($curl_user_agent, $get_2->getOpt(CURLOPT_USERAGENT));
$this->assertEquals($curl_user_agent, $get_2->response);
}
public function testSetHeaderAndOverride()
{
$multi_curl = new MultiCurl();
$multi_curl->setHeader('header-for-all-before', 'a');
$get_1 = $multi_curl->addGet(Test::TEST_URL);
$get_1->setHeader('header-for-1st-request', '1');
$get_1->complete(function ($instance) {
PHPUnit_Framework_Assert::assertEquals('a', $instance->requestHeaders['header-for-all-before']);
PHPUnit_Framework_Assert::assertEquals('b', $instance->requestHeaders['header-for-all-after']);
PHPUnit_Framework_Assert::assertEquals('1', $instance->requestHeaders['header-for-1st-request']);
});
$get_2 = $multi_curl->addGet(Test::TEST_URL);
$get_2->setHeader('header-for-2nd-request', '2');
$get_2->complete(function ($instance) {
PHPUnit_Framework_Assert::assertEquals('a', $instance->requestHeaders['header-for-all-before']);
PHPUnit_Framework_Assert::assertEquals('b', $instance->requestHeaders['header-for-all-after']);
PHPUnit_Framework_Assert::assertEquals('2', $instance->requestHeaders['header-for-2nd-request']);
});
$multi_curl->setHeader('header-for-all-after', 'b');
$multi_curl->start();
}
public function testBasicHttpAuthSuccess()
{
$username1 = 'myusername';
$password1 = 'mypassword';
$username2 = 'myotherusername';
$password2 = 'myotherpassword';
$multi_curl = new MultiCurl();
$multi_curl->setHeader('X-DEBUG-TEST', 'http_basic_auth');
$multi_curl->setBasicAuthentication($username1, $password1);
$get_1 = $multi_curl->addGet(Test::TEST_URL);
$get_1->complete(function ($instance) use ($username1, $password1) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
PHPUnit_Framework_Assert::assertEquals($username1, $instance->response->username);
PHPUnit_Framework_Assert::assertEquals($password1, $instance->response->password);
});
$get_2 = $multi_curl->addGet(Test::TEST_URL);
$get_2->beforeSend(function ($instance) use ($username2, $password2) {
$instance->setBasicAuthentication($username2, $password2);
});
$get_2->complete(function ($instance) use ($username2, $password2) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
PHPUnit_Framework_Assert::assertEquals($username2, $instance->response->username);
PHPUnit_Framework_Assert::assertEquals($password2, $instance->response->password);
});
$multi_curl->start();
$this->assertEquals(CURLAUTH_BASIC, $multi_curl->getOpt(CURLOPT_HTTPAUTH));
$this->assertEquals(CURLAUTH_BASIC, $get_1->getOpt(CURLOPT_HTTPAUTH));
$this->assertEquals($username1, $get_1->response->username);
$this->assertEquals($password1, $get_1->response->password);
$this->assertEquals(CURLAUTH_BASIC, $get_2->getOpt(CURLOPT_HTTPAUTH));
$this->assertEquals($username2, $get_2->response->username);
$this->assertEquals($password2, $get_2->response->password);
}
public function testDigestHttpAuthSuccess()
{
// Skip Digest Access Authentication test on HHVM.
// https://github.com/facebook/hhvm/issues/5201
if (defined('HHVM_VERSION')) {
return;
}
$username = 'myusername';
$password = 'mypassword';
$invalid_password = 'anotherpassword';
// Ensure that http digest returns canceled when not using any http digest authentication.
$multi_curl = new MultiCurl();
$multi_curl->setHeader('X-DEBUG-TEST', 'http_digest_auth');
$get_1 = $multi_curl->addGet(Test::TEST_URL);
$get_1->complete(function ($instance) {
PHPUnit_Framework_Assert::assertEquals('canceled', $instance->response);
PHPUnit_Framework_Assert::assertEquals(401, $instance->httpStatusCode);
});
$multi_curl->start();
// Ensure that http digest returns invalid when using incorrect http digest authentication.
$multi_curl = new MultiCurl();
$multi_curl->setHeader('X-DEBUG-TEST', 'http_digest_auth');
$multi_curl->setDigestAuthentication($username, $invalid_password);
$this->assertEquals(CURLAUTH_DIGEST, $multi_curl->getOpt(CURLOPT_HTTPAUTH));
$get_1 = $multi_curl->addGet(Test::TEST_URL);
$get_1->complete(function ($instance) {
PHPUnit_Framework_Assert::assertEquals(CURLAUTH_DIGEST, $instance->getOpt(CURLOPT_HTTPAUTH));
PHPUnit_Framework_Assert::assertEquals('invalid', $instance->response);
PHPUnit_Framework_Assert::assertEquals(401, $instance->httpStatusCode);
});
$multi_curl->start();
// Ensure that http digest returns valid when using correct http digest authentication.
$multi_curl = new MultiCurl();
$multi_curl->setHeader('X-DEBUG-TEST', 'http_digest_auth');
$multi_curl->setDigestAuthentication($username, $password);
$this->assertEquals(CURLAUTH_DIGEST, $multi_curl->getOpt(CURLOPT_HTTPAUTH));
$get_1 = $multi_curl->addGet(Test::TEST_URL);
$get_1->complete(function ($instance) {
PHPUnit_Framework_Assert::assertEquals(CURLAUTH_DIGEST, $instance->getOpt(CURLOPT_HTTPAUTH));
PHPUnit_Framework_Assert::assertEquals('valid', $instance->response);
PHPUnit_Framework_Assert::assertEquals(200, $instance->httpStatusCode);
});
$multi_curl->start();
// Ensure that http digest can return both invalid and valid when using
// incorrect and correct authentication in the same MultiCurl.
$multi_curl = new MultiCurl();
$multi_curl->setHeader('X-DEBUG-TEST', 'http_digest_auth');
$multi_curl->setDigestAuthentication($username, $password);
$this->assertEquals(CURLAUTH_DIGEST, $multi_curl->getOpt(CURLOPT_HTTPAUTH));
$get_1 = $multi_curl->addGet(Test::TEST_URL);
$get_1->beforeSend(function ($instance) use ($username, $invalid_password) {
$instance->setDigestAuthentication($username, $invalid_password);
PHPUnit_Framework_Assert::assertEquals(CURLAUTH_DIGEST, $instance->getOpt(CURLOPT_HTTPAUTH));
});
$get_1->complete(function ($instance) {
PHPUnit_Framework_Assert::assertEquals(CURLAUTH_DIGEST, $instance->getOpt(CURLOPT_HTTPAUTH));
PHPUnit_Framework_Assert::assertEquals('invalid', $instance->response);
PHPUnit_Framework_Assert::assertEquals(401, $instance->httpStatusCode);
});
$get_2 = $multi_curl->addGet(Test::TEST_URL);
$get_2->complete(function ($instance) {
PHPUnit_Framework_Assert::assertEquals(CURLAUTH_DIGEST, $instance->getOpt(CURLOPT_HTTPAUTH));
PHPUnit_Framework_Assert::assertEquals('valid', $instance->response);
PHPUnit_Framework_Assert::assertEquals(200, $instance->httpStatusCode);
});
$multi_curl->start();
}
public function testCookies()
{
$multi_curl = new MultiCurl();
$multi_curl->setHeader('X-DEBUG-TEST', 'setcookie');
$multi_curl->setCookie('mycookie', 'yum');
$multi_curl->setCookie('cookie-for-all-before', 'a');
$get_1 = $multi_curl->addGet(Test::TEST_URL);
$get_1->setCookie('cookie-for-1st-request', '1');
$get_1->complete(function ($instance) {
PHPUnit_Framework_Assert::assertEquals('yum', $instance->responseCookies['mycookie']);
PHPUnit_Framework_Assert::assertEquals('a', $instance->responseCookies['cookie-for-all-before']);
PHPUnit_Framework_Assert::assertEquals('b', $instance->responseCookies['cookie-for-all-after']);
PHPUnit_Framework_Assert::assertEquals('1', $instance->responseCookies['cookie-for-1st-request']);
});
$get_2 = $multi_curl->addGet(Test::TEST_URL);
$get_2->setCookie('cookie-for-2nd-request', '2');
$get_2->beforeSend(function ($instance) {
$instance->setCookie('mycookie', 'yummy');
});
$get_2->complete(function ($instance) {
PHPUnit_Framework_Assert::assertEquals('yummy', $instance->responseCookies['mycookie']);
PHPUnit_Framework_Assert::assertEquals('a', $instance->responseCookies['cookie-for-all-before']);
PHPUnit_Framework_Assert::assertEquals('b', $instance->responseCookies['cookie-for-all-after']);
PHPUnit_Framework_Assert::assertEquals('2', $instance->responseCookies['cookie-for-2nd-request']);
});
$multi_curl->setCookie('cookie-for-all-after', 'b');
$multi_curl->start();
$this->assertEquals('yum', $get_1->responseCookies['mycookie']);
$this->assertEquals('yummy', $get_2->responseCookies['mycookie']);
}
public function testJSONDecoder()
{
$multi_curl = new MultiCurl();
$multi_curl->setHeader('X-DEBUG-TEST', 'json_response');
$multi_curl->setJsonDecoder(function ($response) {
return 'foo';
});
$get_1 = $multi_curl->addGet(Test::TEST_URL);
$get_1->complete(function ($instance) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
PHPUnit_Framework_Assert::assertEquals('foo', $instance->response);
});
$get_2 = $multi_curl->addGet(Test::TEST_URL);
$get_2->beforeSend(function ($instance) {
$instance->setJsonDecoder(function ($response) {
return 'bar';
});
});
$get_2->complete(function ($instance) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
PHPUnit_Framework_Assert::assertEquals('bar', $instance->response);
});
$multi_curl->start();
$this->assertEquals('foo', $get_1->response);
$this->assertEquals('bar', $get_2->response);
}
public function testXMLDecoder()
{
$multi_curl = new MultiCurl();
$multi_curl->setHeader('X-DEBUG-TEST', 'xml_with_cdata_response');
$multi_curl->setXmlDecoder(function ($response) {
return 'foo';
});
$get_1 = $multi_curl->addGet(Test::TEST_URL);
$get_1->complete(function ($instance) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
PHPUnit_Framework_Assert::assertEquals('foo', $instance->response);
});
$get_2 = $multi_curl->addGet(Test::TEST_URL);
$get_2->beforeSend(function ($instance) {
$instance->setXmlDecoder(function ($response) {
return 'bar';
});
});
$get_2->complete(function ($instance) {
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
PHPUnit_Framework_Assert::assertEquals('bar', $instance->response);
});
$multi_curl->start();
$this->assertEquals('foo', $get_1->response);
$this->assertEquals('bar', $get_2->response);
}
public function testDownloadCallback()
{
// Upload a file.
$upload_file_path = Helper\get_png();
$upload_test = new Test();
$upload_test->server('upload_response', 'POST', array(
'image' => '@' . $upload_file_path,
));
$uploaded_file_path = $upload_test->curl->response->file_path;
// Download the file.
$download_callback_called = false;
$multi_curl = new MultiCurl();
$multi_curl->setHeader('X-DEBUG-TEST', 'download_response');
$multi_curl->addDownload(Test::TEST_URL . '?' . http_build_query(array(
'file_path' => $uploaded_file_path,
)), function ($instance, $fh) use (&$download_callback_called) {
PHPUnit_Framework_Assert::assertFalse($download_callback_called);
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
PHPUnit_Framework_Assert::assertTrue(is_resource($fh));
PHPUnit_Framework_Assert::assertEquals('stream', get_resource_type($fh));
PHPUnit_Framework_Assert::assertGreaterThan(0, strlen(stream_get_contents($fh)));
PHPUnit_Framework_Assert::assertEquals(0, strlen(stream_get_contents($fh)));
PHPUnit_Framework_Assert::assertTrue(fclose($fh));
$download_callback_called = true;
});
$multi_curl->start();
$this->assertTrue($download_callback_called);
// Remove server file.
$this->assertEquals('true', $upload_test->server('upload_cleanup', 'POST', array(
'file_path' => $uploaded_file_path,
)));
unlink($upload_file_path);
$this->assertFalse(file_exists($upload_file_path));
$this->assertFalse(file_exists($uploaded_file_path));
}
public function testDownloadCallbackError()
{
$download_before_send_called = false;
$download_callback_called = false;
$multi_curl = new MultiCurl();
$multi_curl->beforeSend(function ($instance) use (&$download_before_send_called) {
PHPUnit_Framework_Assert::assertFalse($download_before_send_called);
$download_before_send_called = true;
});
$multi_curl->addDownload(Test::ERROR_URL, function ($instance, $fh) use (&$download_callback_called) {
$download_callback_called = true;
});
$multi_curl->start();
$this->assertTrue($download_before_send_called);
$this->assertFalse($download_callback_called);
}
public function testSetUrlInConstructor()
{
$data = array('key' => 'value');
$multi_curl = new MultiCurl(Test::TEST_URL);
$multi_curl->setHeader('X-DEBUG-TEST', 'delete_with_body');
$multi_curl->addDelete($data, array('wibble' => 'wubble'))->complete(function ($instance) {
PHPUnit_Framework_Assert::assertEquals(Test::TEST_URL, $instance->baseUrl);
PHPUnit_Framework_Assert::assertEquals(
'{"get":{"key":"value"},"delete":{"wibble":"wubble"}}',
$instance->rawResponse
);
});
$multi_curl->start();
$multi_curl = new MultiCurl(Test::TEST_URL);
$multi_curl->setHeader('X-DEBUG-TEST', 'get');
$multi_curl->addDelete($data)->complete(function ($instance) {
PHPUnit_Framework_Assert::assertEquals(Test::TEST_URL, $instance->baseUrl);
PHPUnit_Framework_Assert::assertEquals('key=value', $instance->response);
});
$multi_curl->start();
$multi_curl = new MultiCurl(Test::TEST_URL);
$multi_curl->setHeader('X-DEBUG-TEST', 'get');
$multi_curl->addGet($data)->complete(function ($instance) {
PHPUnit_Framework_Assert::assertEquals(Test::TEST_URL, $instance->baseUrl);
PHPUnit_Framework_Assert::assertEquals('key=value', $instance->response);
});
$multi_curl->start();
$multi_curl = new MultiCurl(Test::TEST_URL);
$multi_curl->setHeader('X-DEBUG-TEST', 'get');
$multi_curl->addHead($data)->complete(function ($instance) {
PHPUnit_Framework_Assert::assertEquals(Test::TEST_URL, $instance->baseUrl);
PHPUnit_Framework_Assert::assertEquals(
'HEAD /?key=value HTTP/1.1',
$instance->requestHeaders['Request-Line']
);
});
$multi_curl->start();
$multi_curl = new MultiCurl(Test::TEST_URL);
$multi_curl->setHeader('X-DEBUG-TEST', 'get');
$multi_curl->addOptions($data)->complete(function ($instance) {
PHPUnit_Framework_Assert::assertEquals(Test::TEST_URL, $instance->baseUrl);
PHPUnit_Framework_Assert::assertEquals('key=value', $instance->response);
});
$multi_curl->start();
$multi_curl = new MultiCurl(Test::TEST_URL);
$multi_curl->setHeader('X-DEBUG-TEST', 'request_method');
$multi_curl->addPatch($data)->complete(function ($instance) {
PHPUnit_Framework_Assert::assertEquals(Test::TEST_URL, $instance->baseUrl);
PHPUnit_Framework_Assert::assertEquals('PATCH', $instance->response);
});
$multi_curl->start();
$multi_curl = new MultiCurl(Test::TEST_URL);
$multi_curl->setHeader('X-DEBUG-TEST', 'post');
$multi_curl->addPost($data)->complete(function ($instance) {
PHPUnit_Framework_Assert::assertEquals(Test::TEST_URL, $instance->baseUrl);
PHPUnit_Framework_Assert::assertEquals('key=value', $instance->response);
});
$multi_curl->start();
$multi_curl = new MultiCurl(Test::TEST_URL);
$multi_curl->setHeader('X-DEBUG-TEST', 'put');
$multi_curl->addPut($data)->complete(function ($instance) {
PHPUnit_Framework_Assert::assertEquals(Test::TEST_URL, $instance->baseUrl);
PHPUnit_Framework_Assert::assertEquals('key=value', $instance->response);
});
$multi_curl->start();
}
public function testSetUrl()
{
$data = array('key' => 'value');
$multi_curl = new MultiCurl();
$multi_curl->setUrl(Test::TEST_URL);
$multi_curl->addDelete($data)->complete(function ($instance) {
PHPUnit_Framework_Assert::assertEquals(
'DELETE /?key=value HTTP/1.1',
$instance->requestHeaders['Request-Line']
);
PHPUnit_Framework_Assert::assertEquals(Test::TEST_URL . '?key=value', $instance->effectiveUrl);
});
$multi_curl->start();
$multi_curl = new MultiCurl();
$multi_curl->setUrl(Test::TEST_URL);
$multi_curl->addGet($data)->complete(function ($instance) {
PHPUnit_Framework_Assert::assertEquals(
'GET /?key=value HTTP/1.1',
$instance->requestHeaders['Request-Line']
);
PHPUnit_Framework_Assert::assertEquals(Test::TEST_URL . '?key=value', $instance->effectiveUrl);
});
$multi_curl->start();
$multi_curl = new MultiCurl();
$multi_curl->setUrl(Test::TEST_URL);
$multi_curl->addHead($data)->complete(function ($instance) {
PHPUnit_Framework_Assert::assertEquals(
'HEAD /?key=value HTTP/1.1',
$instance->requestHeaders['Request-Line']
);
PHPUnit_Framework_Assert::assertEquals(Test::TEST_URL . '?key=value', $instance->effectiveUrl);
});
$multi_curl->start();
$multi_curl = new MultiCurl();
$multi_curl->setUrl(Test::TEST_URL);
$multi_curl->addOptions($data)->complete(function ($instance) {
PHPUnit_Framework_Assert::assertEquals(
'OPTIONS /?key=value HTTP/1.1',
$instance->requestHeaders['Request-Line']
);
PHPUnit_Framework_Assert::assertEquals(Test::TEST_URL . '?key=value', $instance->effectiveUrl);
});
$multi_curl = new MultiCurl();
$multi_curl->setUrl(Test::TEST_URL);
$multi_curl->addPatch($data)->complete(function ($instance) {
PHPUnit_Framework_Assert::assertEquals(
'PATCH / HTTP/1.1',
$instance->requestHeaders['Request-Line']
);
PHPUnit_Framework_Assert::assertEquals(Test::TEST_URL, $instance->effectiveUrl);
});
$multi_curl = new MultiCurl();
$multi_curl->setUrl(Test::TEST_URL);
$multi_curl->addPost($data)->complete(function ($instance) {
PHPUnit_Framework_Assert::assertEquals(
'POST / HTTP/1.1',
$instance->requestHeaders['Request-Line']
);
PHPUnit_Framework_Assert::assertEquals(Test::TEST_URL, $instance->effectiveUrl);
});
$multi_curl = new MultiCurl();
$multi_curl->setUrl(Test::TEST_URL);
$multi_curl->addPut($data)->complete(function ($instance) {
PHPUnit_Framework_Assert::assertEquals(
'PUT / HTTP/1.1',
$instance->requestHeaders['Request-Line']
);
PHPUnit_Framework_Assert::assertEquals(Test::TEST_URL, $instance->effectiveUrl);
});
}
public function testAddRequestAfterStart()
{
$multi_curl = new MultiCurl();
$urls = array();
$copy_of_urls = array();
for ($i = 0; $i < 10; $i++) {
$url = Test::TEST_URL . '?' . md5(mt_rand());
$urls[] = $url;
$copy_of_urls[] = $url;
}
$urls_called = array();
$multi_curl->complete(function ($instance) use (&$multi_curl, &$urls, &$urls_called) {
$urls_called[] = $instance->url;
$next_url = array_pop($urls);
if (!($next_url === null)) {
$multi_curl->addGet($next_url);
}
});
$multi_curl->addGet(array_pop($urls));
$multi_curl->start();
$this->assertNotEmpty($copy_of_urls);
$this->assertNotEmpty($urls_called);
$this->assertEquals(count($copy_of_urls), count($urls_called));
foreach ($copy_of_urls as $url) {
$this->assertTrue(in_array($url, $urls_called, true));
}
}
public function testClose()
{
$multi_curl = new MultiCurl();
$multi_curl->addGet(Test::TEST_URL);
$multi_curl->start();
$this->assertTrue(is_resource($multi_curl->multiCurl));
$multi_curl->close();
$this->assertFalse(is_resource($multi_curl->multiCurl));
}
public function testMultiPostRedirectGet()
{
// Deny post-redirect-get
$multi_curl = new MultiCurl(Test::TEST_URL);
$multi_curl->setOpt(CURLOPT_FOLLOWLOCATION, true);
$multi_curl->setHeader('X-DEBUG-TEST', 'post_redirect_get');
$multi_curl->addPost(array(), false)->complete(function ($instance) {
PHPUnit_Framework_Assert::assertEquals('Redirected: POST', $instance->response);
});
$multi_curl->start();
// Allow post-redirect-get
$multi_curl = new MultiCurl(Test::TEST_URL);
$multi_curl->setOpt(CURLOPT_FOLLOWLOCATION, true);
$multi_curl->setHeader('X-DEBUG-TEST', 'post_redirect_get');
$multi_curl->addPost(array(), true)->complete(function ($instance) {
PHPUnit_Framework_Assert::assertEquals('Redirected: GET', $instance->response);
});
$multi_curl->start();
}
public function testAlternativeStandardErrorOutput()
{
$buffer = fopen('php://memory', 'w+');
$multi_curl = new MultiCurl();
$multi_curl->verbose(true, $buffer);
$multi_curl->addGet(Test::TEST_URL);
$multi_curl->start();
rewind($buffer);
$stderr = stream_get_contents($buffer);
fclose($buffer);
$this->assertNotEmpty($stderr);
}
public function testUnsetHeader()
{
$request_key = 'X-Request-Id';
$request_value = '1';
$data = array(
'test' => 'server',
'key' => 'HTTP_X_REQUEST_ID',
);
$multi_curl = new MultiCurl();
$multi_curl->setHeader($request_key, $request_value);
$multi_curl->addGet(Test::TEST_URL, $data)->complete(function ($instance) use ($request_value) {
PHPUnit_Framework_Assert::assertEquals($request_value, $instance->response);
});
$multi_curl->start();
$multi_curl = new MultiCurl();
$multi_curl->setHeader($request_key, $request_value);
$multi_curl->unsetHeader($request_key);
$multi_curl->addGet(Test::TEST_URL, $data)->complete(function ($instance) {
PHPUnit_Framework_Assert::assertEquals('', $instance->response);
});
$multi_curl->start();
}
}
| zefredzocohen1/maps-ci | application/third_party/php-curl/vendor/php-curl-class/php-curl-class/tests/PHPCurlClass/PHPMultiCurlClassTest.php | PHP | mit | 117,473 |
The MIT License (MIT)
=====================
Copyright © `2015` `WCOM AB`
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.
| devlead/SqlServerSlackAPI | LICENSE.md | Markdown | mit | 1,107 |
#ifndef THREE_LIGHT_HPP
#define THREE_LIGHT_HPP
#include <three/common.hpp>
#include <three/visitor.hpp>
#include <three/core/color.hpp>
#include <three/core/object3d.hpp>
namespace three {
class Light : public Object3D {
public:
typedef std::shared_ptr<Light> Ptr;
virtual THREE::Type type() const { return THREE::Light; }
/////////////////////////////////////////////////////////////////////////
Color color;
float intensity;
float distance;
Object3D::Ptr target;
bool castShadow, onlyShadow, shadowCascade;
/////////////////////////////////////////////////////////////////////////
protected:
explicit Light( int hex, float intensity = 1, float distance = 0 )
: Object3D(),
color( hex ),
intensity( intensity ),
distance( distance ),
target( nullptr ),
castShadow( false ),
onlyShadow( false ),
shadowCascade( false ) { }
virtual void visit( Visitor& v ) { v( *this ); }
virtual void visit( ConstVisitor& v ) const { v( *this ); }
};
} // namespace three
#endif // THREE_LIGHT_HPP | jdduke/three_cpp | three/lights/light.hpp | C++ | mit | 1,069 |
var gulp = require('gulp');
var less = require('gulp-less');
var rename = require('gulp-rename');
var postcss = require('gulp-postcss');
var cssnano = require('gulp-cssnano');
var header = require('gulp-header');
var autoprefixer = require('autoprefixer');
var pkg = require('./package.json');
gulp.task('watch', function() {
gulp.watch('src/**', ['build:style', 'build:example']);
});
gulp.task('build:style', function() {
var banner = [
'/*!',
' * WeUI v<%= pkg.version %> (<%= pkg.homepage %>)',
' * Copyright <%= new Date().getFullYear() %> Tencent, Inc.',
' * Licensed under the <%= pkg.license %> license',
' */',
''
].join('\n');
gulp
.src(['src/style/**/*.wxss', 'src/example/*.wxss'], { base: 'src' })
.pipe(less())
.pipe(postcss([autoprefixer(['iOS >= 8', 'Android >= 4.1'])]))
.pipe(
cssnano({
zindex: false,
autoprefixer: false,
discardComments: { removeAll: true }
})
)
.pipe(header(banner, { pkg: pkg }))
.pipe(
rename(function(path) {
path.extname = '.wxss';
})
)
.pipe(gulp.dest('dist'));
});
gulp.task('build:example', function() {
gulp
.src(
[
'src/app.js',
'src/app.json',
'src/app.wxss',
'src/example/**',
'!src/example/*.wxss'
],
{ base: 'src' }
)
.pipe(gulp.dest('dist'));
});
gulp.task('default', ['watch', 'build:style', 'build:example']);
| ymqy/LearnBook | 微信小程序/UI组件/weui-wxss/gulpfile.js | JavaScript | mit | 1,462 |
var exec = require("child_process").exec;
// Useful for returning well-formatted errors
function buildError(){
return {success: false, errors: Array.from(arguments)}
}
/**
* @desc Checks if the YouSign API is up and if our credentials are valid
*/
function checkAuth() {
return new Promise((resolve, reject)=>{
var command = ["php", "checkAuth.php"]
exec(command.join(' '), { cwd: __dirname }, (error, stdout, stderr)=>{
if(!error && !stderr){
try{
var result = JSON.parse(stdout)
} catch(e){
var err = "checkAuth - could not parse result: " + stdout
console.error(err)
}
if(err){
return reject(buildError(err))
} else if(result.success != true){
return reject(result)
} else {
return resolve(result)
}
} else {
return reject(buildError(error, stderr))
}
})
})
}
/**
* @desc Inits a signature and returns the url of the signing page
* @param {array} filesToSign - An array of absolute paths to the documents that you wish to sign.
* Example : [/Users/joe/document1.pdf, /Users/joe/document2.pdf]
* Alternatively, you can send a string if you only have one file to sign
* Example : document1.pdf
* @param {string} firstName - Firstname of the person that will sign
* @param {string} lastName - Lastname of the person that will sign
* @param {string} email - Email of the person that will sign
* @param {string} phone - Phone of the person that will sign, including prefix (+33...).
* Must be a real Phone number as the user will receive an SMS confirmation code.
* @param {array} signatures - An array of objects, each object containing the following data for a signature :
* page, document number, pixel coordinates of the rectangle where it will appear. Example for two signatures on page 2 and 4
* on the first document of the filesToSign, and on page 2 of the second document:
* [{rectangleCoords: "337,59,572,98", page:"2", document:"1"}, {rectangleCoords: "337,193,572,232", page:"4", document:"1"},
* {rectangleCoords: "100,200,300,400", page:"2", document:"2"}],
* If you only have one signature, and want to put on page 1 of first document, you can send only a string of coordinates
* instead of an array : "337,59,572,98"
* @param {string} userSuccessRedirectUrl - A url where the user will be redirected to after he signs
* @param {string} userCancelRedirectUrl - A url where the user will be redirected to after he cancels
* the signature process
* @param {string} onSignatureStatusChangedUrl - The YouSign server will send GET requests to this url
* when the signature status changes. Statuses can be : init, cancel, waiting, signed, signed_complete
* @returns {string} iframeUrl - the url of the iframe to do the signature
* @returns {object} details - details of the signature, contains de demand ID which can be used later on
*/
function initSignature(filesToSign, firstname, lastname, email, phone,
signatures, userSuccessRedirectUrl, userCancelRedirectUrl, onSignatureStatusChangedUrl) {
return new Promise((resolve, reject)=>{
//Array of signature objects instead of one string
if(typeof signatures == 'object'){
var signatureList = []
signatures.forEach((signature)=>{
signatureList.push(signature.rectangleCoords +
"-" + signature.page +
"-" + (signature.document ? signature.document : 0))
})
signatures = signatureList.join("_")
}
//Array of file paths instead of one string
if(typeof filesToSign == 'object'){
filesToSign = filesToSign.join("[]_THIS_IS_A_BIG_SEPARATOR_[]")
}
//Base64 encode arguments so that we don't send invalid chars in shell
var args = Array.from(arguments)
var encodedArguments = []
args.forEach((argument)=>{
encodedArguments.push(Buffer.from(argument).toString('base64'))
})
var command = ["php", "initSignature.php"].concat(encodedArguments)
if(command.length < 8){
return reject(buildError("Missing parameters"))
}
exec(command.join(' '), { cwd: __dirname }, (error, stdout, stderr)=>{
if(!error && !stderr){
try{
var result = JSON.parse(stdout)
} catch(e){
var err = "initSignature - could not parse result: " + stdout
console.error(err)
}
if(err){
return reject(buildError(err))
} else if(result.success != true){
return reject(result)
} else {
//Add the redirect and callback urls to the signature page url as GET parameters
var suffix = "?urlsuccess=" + encodeURIComponent(userSuccessRedirectUrl) +
"&urlcancel=" + encodeURIComponent(userCancelRedirectUrl) +
"&urlcallback=" + encodeURIComponent(onSignatureStatusChangedUrl)
result.signingUrl = result.signingUrl + suffix
return resolve(result)
}
} else {
return reject(buildError(error, stderr))
}
})
})
}
/**
* @desc Downloads all the files in the signature process corresponding to the search parameter provided
* @param {string} search - The YouSign search parameters. This can be the email of the person who signed, the filename...
* Example : [email protected] - will download all the files in a signature process with [email protected]
* @param {string} absoluteOutFolderPath - An absolute path to the output folder for the downloaded files (without trailing /)
* Example : /Users/joe/out - the folder MUST already exist and be writeable
*/
function downloadSignaturesFiles(search, absoluteOutFolderPath) {
return new Promise((resolve, reject)=>{
//Base64 encode arguments so that we don't send invalid chars in shell
var args = Array.from(arguments)
var encodedArguments = []
args.forEach((argument)=>{
encodedArguments.push(Buffer.from(argument).toString('base64'))
})
var command = ["php", "downloadSignaturesFiles.php"].concat(encodedArguments)
if(command.length < 4){
return reject(buildError("Missing parameters"))
}
exec(command.join(' '), { cwd: __dirname }, (error, stdout, stderr)=>{
if(!error && !stderr){
try{
var result = JSON.parse(stdout)
} catch(e){
var err = "downloadSignaturesFiles - could not parse result: " + stdout
console.error(err)
}
if(err){
return reject(buildError(err))
} else if(result.success != true){
return reject(result)
} else {
return resolve(result)
}
} else {
return reject(buildError(error, stderr))
}
})
})
}
/**
* @desc Lists the existing signatures and the corresponding statuses for an email
* @param {string} email - Email of the person whose signatures we want to get
*/
function listSignatures(email) {
return new Promise((resolve, reject)=>{
var command = ["php", "listSignatures.php"].concat(Array.from(arguments))
if(command.length < 3){
return reject(buildError("Missing parameters"))
}
exec(command.join(' '), { cwd: __dirname }, (error, stdout, stderr)=>{
if(!error && !stderr){
try{
var result = JSON.parse(stdout)
} catch(e){
var err = "listSignature - could not parse result: " + stdout
console.error(err)
}
if(err){
return reject(buildError(err))
} else if(result.success != true){
return reject(result)
} else {
return resolve(result)
}
} else {
return reject(buildError(error, stderr))
}
})
})
}
// Public functions export
module.exports = {
initSignature: initSignature,
checkAuth: checkAuth,
listSignatures: listSignatures,
downloadSignaturesFiles: downloadSignaturesFiles
}
// Example call :
/*listSignatures("[email protected]").then((res)=>{
console.log(res)
}).catch((err)=>{
console.error(err)
})*/ | Axelerio/YouSign-NodeJS-API-Wrapper | index.js | JavaScript | mit | 8,868 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Coq bench</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../../..">Stable</a></li>
<li><a href=".">8.5beta1 / concurrency:pluto 1.0.0</a></li>
<li class="active"><a href="">2015-01-28 21:20:18</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="../../../../../about.html">About</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href=".">« Up</a>
<h1>
concurrency:pluto
<small>
1.0.0
<span class="label label-warning">Error with dependencies</span>
</small>
</h1>
<p><em><script>document.write(moment("2015-01-28 21:20:18 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2015-01-28 21:20:18 UTC)</em><p>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>ruby lint.rb stable ../stable/packages/coq:concurrency:pluto/coq:concurrency:pluto.1.0.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
<dt>Output</dt>
<dd><pre>The package is valid.
</pre></dd>
</dl>
<h2>Dry install</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --dry-run coq:concurrency:pluto.1.0.0 coq.8.5beta1</code></dd>
<dt>Return code</dt>
<dd>768</dd>
<dt>Duration</dt>
<dd>0 s</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.5beta1).
The following dependencies couldn't be met:
- coq:concurrency:pluto -> coq:concurrency:proxy
Your request can't be satisfied:
- coq:concurrency:proxy is not available because it requires OCaml >= 4.02.0.
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq, to test if the problem was incompatibility with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --dry-run coq:concurrency:pluto.1.0.0</code></dd>
<dt>Return code</dt>
<dd>768</dd>
<dt>Duration</dt>
<dd>2 s</dd>
<dt>Output</dt>
<dd><pre>The following actions will be performed:
- remove coq.8.5beta1
=== 1 to remove ===
=-=- Removing Packages =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Removing coq.8.5beta1.
[WARNING] Directory /home/bench/.opam/system/lib/coq is not empty, not removing
The following dependencies couldn't be met:
- coq:concurrency:pluto -> coq:concurrency:proxy
Your request can't be satisfied:
- coq:concurrency:proxy is not available because it requires OCaml >= 4.02.0.
No solution found, exiting
</pre></dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
<small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small>
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html> | coq-bench/coq-bench.github.io-old | clean/Linux-x86_64-4.01.0-1.2.0/stable/8.5beta1/concurrency:pluto/1.0.0/2015-01-28_21-20-18.html | HTML | mit | 6,365 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Manifest formatter</title>
<meta name="description" content="Pretty-prints JAR manifest files (used by OSGi)">
<meta name="keywords" content="format, pretty print, manifest, manifest.mf, jar, java, osgi">
<meta name="author" content="Robin Stocker">
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/github-fork-ribbon-css/0.1.1/gh-fork-ribbon.min.css">
<script src="formatter.js"></script>
<script src="script.js"></script>
</head>
<body>
<div class="container">
<div class="spacer"></div>
<div class="main">
<h1>JAR/OSGi manifest formatter</h1>
<p>
<textarea cols="80" rows="8" class="manifest" id="input" placeholder="Paste MANIFEST.MF contents here" spellcheck="false"></textarea>
</p>
<p>
<label><input id="format-lists" type="checkbox" checked>Format list values</label>
<label><input id="sort-lists" type="checkbox" checked>Sort lists</label>
<label><input id="sort-headers" type="checkbox">Sort headers</label>
</p>
<p>
<textarea cols="80" rows="40" class="manifest" id="output" spellcheck="false"></textarea>
</p>
<div class="github-fork-ribbon-wrapper right-bottom">
<div class="github-fork-ribbon">
<a href="https://github.com/robinst/jar-manifest-formatter">Fork me on GitHub</a>
</div>
</div>
</div>
<div class="spacer"></div>
</div>
</body>
</html>
| robinst/jar-manifest-formatter | index.html | HTML | mit | 1,544 |
using Machine.Specifications;
namespace Fabrik.Common.Specs
{
[Subject(typeof(TypeExtensions), "Implements")]
public class Type_Implements
{
static bool result;
public class When_the_current_type_is_a_subclass_of_type
{
Because of = () => result = typeof(Foo).Implements<BaseFoo>();
It Should_return_true = () => result.ShouldBeTrue();
}
public class When_the_current_type_implements_interface_type
{
Because of = () => result = typeof(Foo2).Implements<IFoo>();
It Should_return_true = () => result.ShouldBeTrue();
}
public class When_the_current_type_does_not_implement_type
{
Because of = () => result = typeof(Foo3).Implements<BaseFoo>();
It Should_return_false = () => result.ShouldBeFalse();
}
private class Foo : BaseFoo
{
}
private class Foo2 : IFoo
{
}
private class Foo3
{
}
private class BaseFoo
{
}
private class IFoo
{
}
}
}
| benfoster/Fabrik.Common | src/Specs/Fabrik.Common.Specs/TypeExtensionsSpecs.cs | C# | mit | 1,148 |
/* png.h - header file for PNG reference library
*
* libpng version 1.5.5rc01 - September 15, 2011
* Copyright (c) 1998-2011 Glenn Randers-Pehrson
* (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
* (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
*
* This code is released under the libpng license (See LICENSE, below)
*
* Authors and maintainers:
* libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
* libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger
* libpng versions 0.97, January 1998, through 1.5.5rc01 - September 15, 2011: Glenn
* See also "Contributing Authors", below.
*
* Note about libpng version numbers:
*
* Due to various miscommunications, unforeseen code incompatibilities
* and occasional factors outside the authors' control, version numbering
* on the library has not always been consistent and straightforward.
* The following table summarizes matters since version 0.89c, which was
* the first widely used release:
*
* source png.h png.h shared-lib
* version string int version
* ------- ------ ----- ----------
* 0.89c "1.0 beta 3" 0.89 89 1.0.89
* 0.90 "1.0 beta 4" 0.90 90 0.90 [should have been 2.0.90]
* 0.95 "1.0 beta 5" 0.95 95 0.95 [should have been 2.0.95]
* 0.96 "1.0 beta 6" 0.96 96 0.96 [should have been 2.0.96]
* 0.97b "1.00.97 beta 7" 1.00.97 97 1.0.1 [should have been 2.0.97]
* 0.97c 0.97 97 2.0.97
* 0.98 0.98 98 2.0.98
* 0.99 0.99 98 2.0.99
* 0.99a-m 0.99 99 2.0.99
* 1.00 1.00 100 2.1.0 [100 should be 10000]
* 1.0.0 (from here on, the 100 2.1.0 [100 should be 10000]
* 1.0.1 png.h string is 10001 2.1.0
* 1.0.1a-e identical to the 10002 from here on, the shared library
* 1.0.2 source version) 10002 is 2.V where V is the source code
* 1.0.2a-b 10003 version, except as noted.
* 1.0.3 10003
* 1.0.3a-d 10004
* 1.0.4 10004
* 1.0.4a-f 10005
* 1.0.5 (+ 2 patches) 10005
* 1.0.5a-d 10006
* 1.0.5e-r 10100 (not source compatible)
* 1.0.5s-v 10006 (not binary compatible)
* 1.0.6 (+ 3 patches) 10006 (still binary incompatible)
* 1.0.6d-f 10007 (still binary incompatible)
* 1.0.6g 10007
* 1.0.6h 10007 10.6h (testing xy.z so-numbering)
* 1.0.6i 10007 10.6i
* 1.0.6j 10007 2.1.0.6j (incompatible with 1.0.0)
* 1.0.7beta11-14 DLLNUM 10007 2.1.0.7beta11-14 (binary compatible)
* 1.0.7beta15-18 1 10007 2.1.0.7beta15-18 (binary compatible)
* 1.0.7rc1-2 1 10007 2.1.0.7rc1-2 (binary compatible)
* 1.0.7 1 10007 (still compatible)
* 1.0.8beta1-4 1 10008 2.1.0.8beta1-4
* 1.0.8rc1 1 10008 2.1.0.8rc1
* 1.0.8 1 10008 2.1.0.8
* 1.0.9beta1-6 1 10009 2.1.0.9beta1-6
* 1.0.9rc1 1 10009 2.1.0.9rc1
* 1.0.9beta7-10 1 10009 2.1.0.9beta7-10
* 1.0.9rc2 1 10009 2.1.0.9rc2
* 1.0.9 1 10009 2.1.0.9
* 1.0.10beta1 1 10010 2.1.0.10beta1
* 1.0.10rc1 1 10010 2.1.0.10rc1
* 1.0.10 1 10010 2.1.0.10
* 1.0.11beta1-3 1 10011 2.1.0.11beta1-3
* 1.0.11rc1 1 10011 2.1.0.11rc1
* 1.0.11 1 10011 2.1.0.11
* 1.0.12beta1-2 2 10012 2.1.0.12beta1-2
* 1.0.12rc1 2 10012 2.1.0.12rc1
* 1.0.12 2 10012 2.1.0.12
* 1.1.0a-f - 10100 2.1.1.0a-f (branch abandoned)
* 1.2.0beta1-2 2 10200 2.1.2.0beta1-2
* 1.2.0beta3-5 3 10200 3.1.2.0beta3-5
* 1.2.0rc1 3 10200 3.1.2.0rc1
* 1.2.0 3 10200 3.1.2.0
* 1.2.1beta1-4 3 10201 3.1.2.1beta1-4
* 1.2.1rc1-2 3 10201 3.1.2.1rc1-2
* 1.2.1 3 10201 3.1.2.1
* 1.2.2beta1-6 12 10202 12.so.0.1.2.2beta1-6
* 1.0.13beta1 10 10013 10.so.0.1.0.13beta1
* 1.0.13rc1 10 10013 10.so.0.1.0.13rc1
* 1.2.2rc1 12 10202 12.so.0.1.2.2rc1
* 1.0.13 10 10013 10.so.0.1.0.13
* 1.2.2 12 10202 12.so.0.1.2.2
* 1.2.3rc1-6 12 10203 12.so.0.1.2.3rc1-6
* 1.2.3 12 10203 12.so.0.1.2.3
* 1.2.4beta1-3 13 10204 12.so.0.1.2.4beta1-3
* 1.0.14rc1 13 10014 10.so.0.1.0.14rc1
* 1.2.4rc1 13 10204 12.so.0.1.2.4rc1
* 1.0.14 10 10014 10.so.0.1.0.14
* 1.2.4 13 10204 12.so.0.1.2.4
* 1.2.5beta1-2 13 10205 12.so.0.1.2.5beta1-2
* 1.0.15rc1-3 10 10015 10.so.0.1.0.15rc1-3
* 1.2.5rc1-3 13 10205 12.so.0.1.2.5rc1-3
* 1.0.15 10 10015 10.so.0.1.0.15
* 1.2.5 13 10205 12.so.0.1.2.5
* 1.2.6beta1-4 13 10206 12.so.0.1.2.6beta1-4
* 1.0.16 10 10016 10.so.0.1.0.16
* 1.2.6 13 10206 12.so.0.1.2.6
* 1.2.7beta1-2 13 10207 12.so.0.1.2.7beta1-2
* 1.0.17rc1 10 10017 12.so.0.1.0.17rc1
* 1.2.7rc1 13 10207 12.so.0.1.2.7rc1
* 1.0.17 10 10017 12.so.0.1.0.17
* 1.2.7 13 10207 12.so.0.1.2.7
* 1.2.8beta1-5 13 10208 12.so.0.1.2.8beta1-5
* 1.0.18rc1-5 10 10018 12.so.0.1.0.18rc1-5
* 1.2.8rc1-5 13 10208 12.so.0.1.2.8rc1-5
* 1.0.18 10 10018 12.so.0.1.0.18
* 1.2.8 13 10208 12.so.0.1.2.8
* 1.2.9beta1-3 13 10209 12.so.0.1.2.9beta1-3
* 1.2.9beta4-11 13 10209 12.so.0.9[.0]
* 1.2.9rc1 13 10209 12.so.0.9[.0]
* 1.2.9 13 10209 12.so.0.9[.0]
* 1.2.10beta1-7 13 10210 12.so.0.10[.0]
* 1.2.10rc1-2 13 10210 12.so.0.10[.0]
* 1.2.10 13 10210 12.so.0.10[.0]
* 1.4.0beta1-5 14 10400 14.so.0.0[.0]
* 1.2.11beta1-4 13 10211 12.so.0.11[.0]
* 1.4.0beta7-8 14 10400 14.so.0.0[.0]
* 1.2.11 13 10211 12.so.0.11[.0]
* 1.2.12 13 10212 12.so.0.12[.0]
* 1.4.0beta9-14 14 10400 14.so.0.0[.0]
* 1.2.13 13 10213 12.so.0.13[.0]
* 1.4.0beta15-36 14 10400 14.so.0.0[.0]
* 1.4.0beta37-87 14 10400 14.so.14.0[.0]
* 1.4.0rc01 14 10400 14.so.14.0[.0]
* 1.4.0beta88-109 14 10400 14.so.14.0[.0]
* 1.4.0rc02-08 14 10400 14.so.14.0[.0]
* 1.4.0 14 10400 14.so.14.0[.0]
* 1.4.1beta01-03 14 10401 14.so.14.1[.0]
* 1.4.1rc01 14 10401 14.so.14.1[.0]
* 1.4.1beta04-12 14 10401 14.so.14.1[.0]
* 1.4.1 14 10401 14.so.14.1[.0]
* 1.4.2 14 10402 14.so.14.2[.0]
* 1.4.3 14 10403 14.so.14.3[.0]
* 1.4.4 14 10404 14.so.14.4[.0]
* 1.5.0beta01-58 15 10500 15.so.15.0[.0]
* 1.5.0rc01-07 15 10500 15.so.15.0[.0]
* 1.5.0 15 10500 15.so.15.0[.0]
* 1.5.1beta01-11 15 10501 15.so.15.1[.0]
* 1.5.1rc01-02 15 10501 15.so.15.1[.0]
* 1.5.1 15 10501 15.so.15.1[.0]
* 1.5.2beta01-03 15 10502 15.so.15.2[.0]
* 1.5.2rc01-03 15 10502 15.so.15.2[.0]
* 1.5.2 15 10502 15.so.15.2[.0]
* 1.5.3beta01-10 15 10503 15.so.15.3[.0]
* 1.5.3rc01-02 15 10503 15.so.15.3[.0]
* 1.5.3beta11 15 10503 15.so.15.3[.0]
* 1.5.3 [omitted]
* 1.5.4beta01-08 15 10504 15.so.15.4[.0]
* 1.5.4rc01 15 10504 15.so.15.4[.0]
* 1.5.4 15 10504 15.so.15.4[.0]
* 1.5.5beta01-08 15 10505 15.so.15.5[.0]
* 1.5.5rc01 15 10505 15.so.15.5[.0]
*
* Henceforth the source version will match the shared-library major
* and minor numbers; the shared-library major version number will be
* used for changes in backward compatibility, as it is intended. The
* PNG_LIBPNG_VER macro, which is not used within libpng but is available
* for applications, is an unsigned integer of the form xyyzz corresponding
* to the source version x.y.z (leading zeros in y and z). Beta versions
* were given the previous public release number plus a letter, until
* version 1.0.6j; from then on they were given the upcoming public
* release number plus "betaNN" or "rcN".
*
* Binary incompatibility exists only when applications make direct access
* to the info_ptr or png_ptr members through png.h, and the compiled
* application is loaded with a different version of the library.
*
* DLLNUM will change each time there are forward or backward changes
* in binary compatibility (e.g., when a new feature is added).
*
* See libpng-manual.txt or libpng.3 for more information. The PNG
* specification is available as a W3C Recommendation and as an ISO
* Specification, <http://www.w3.org/TR/2003/REC-PNG-20031110/
*/
/*
* COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
*
* If you modify libpng you may insert additional notices immediately following
* this sentence.
*
* This code is released under the libpng license.
*
* libpng versions 1.2.6, August 15, 2004, through 1.5.5rc01, September 15, 2011, are
* Copyright (c) 2004, 2006-2011 Glenn Randers-Pehrson, and are
* distributed according to the same disclaimer and license as libpng-1.2.5
* with the following individual added to the list of Contributing Authors:
*
* Cosmin Truta
*
* libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are
* Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
* distributed according to the same disclaimer and license as libpng-1.0.6
* with the following individuals added to the list of Contributing Authors:
*
* Simon-Pierre Cadieux
* Eric S. Raymond
* Gilles Vollant
*
* and with the following additions to the disclaimer:
*
* There is no warranty against interference with your enjoyment of the
* library or against infringement. There is no warranty that our
* efforts or the library will fulfill any of your particular purposes
* or needs. This library is provided with all faults, and the entire
* risk of satisfactory quality, performance, accuracy, and effort is with
* the user.
*
* libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
* Copyright (c) 1998, 1999, 2000 Glenn Randers-Pehrson, and are
* distributed according to the same disclaimer and license as libpng-0.96,
* with the following individuals added to the list of Contributing Authors:
*
* Tom Lane
* Glenn Randers-Pehrson
* Willem van Schaik
*
* libpng versions 0.89, June 1996, through 0.96, May 1997, are
* Copyright (c) 1996, 1997 Andreas Dilger
* Distributed according to the same disclaimer and license as libpng-0.88,
* with the following individuals added to the list of Contributing Authors:
*
* John Bowler
* Kevin Bracey
* Sam Bushell
* Magnus Holmgren
* Greg Roelofs
* Tom Tanner
*
* libpng versions 0.5, May 1995, through 0.88, January 1996, are
* Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
*
* For the purposes of this copyright and license, "Contributing Authors"
* is defined as the following set of individuals:
*
* Andreas Dilger
* Dave Martindale
* Guy Eric Schalnat
* Paul Schmidt
* Tim Wegner
*
* The PNG Reference Library is supplied "AS IS". The Contributing Authors
* and Group 42, Inc. disclaim all warranties, expressed or implied,
* including, without limitation, the warranties of merchantability and of
* fitness for any purpose. The Contributing Authors and Group 42, Inc.
* assume no liability for direct, indirect, incidental, special, exemplary,
* or consequential damages, which may result from the use of the PNG
* Reference Library, even if advised of the possibility of such damage.
*
* Permission is hereby granted to use, copy, modify, and distribute this
* source code, or portions hereof, for any purpose, without fee, subject
* to the following restrictions:
*
* 1. The origin of this source code must not be misrepresented.
*
* 2. Altered versions must be plainly marked as such and must not
* be misrepresented as being the original source.
*
* 3. This Copyright notice may not be removed or altered from
* any source or altered source distribution.
*
* The Contributing Authors and Group 42, Inc. specifically permit, without
* fee, and encourage the use of this source code as a component to
* supporting the PNG file format in commercial products. If you use this
* source code in a product, acknowledgment is not required but would be
* appreciated.
*/
/*
* A "png_get_copyright" function is available, for convenient use in "about"
* boxes and the like:
*
* printf("%s", png_get_copyright(NULL));
*
* Also, the PNG logo (in PNG format, of course) is supplied in the
* files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
*/
/*
* Libpng is OSI Certified Open Source Software. OSI Certified is a
* certification mark of the Open Source Initiative.
*/
/*
* The contributing authors would like to thank all those who helped
* with testing, bug fixes, and patience. This wouldn't have been
* possible without all of you.
*
* Thanks to Frank J. T. Wojcik for helping with the documentation.
*/
/*
* Y2K compliance in libpng:
* =========================
*
* September 15, 2011
*
* Since the PNG Development group is an ad-hoc body, we can't make
* an official declaration.
*
* This is your unofficial assurance that libpng from version 0.71 and
* upward through 1.5.5rc01 are Y2K compliant. It is my belief that
* earlier versions were also Y2K compliant.
*
* Libpng only has two year fields. One is a 2-byte unsigned integer
* that will hold years up to 65535. The other holds the date in text
* format, and will hold years up to 9999.
*
* The integer is
* "png_uint_16 year" in png_time_struct.
*
* The string is
* "png_char time_buffer" in png_struct
*
* There are seven time-related functions:
* png.c: png_convert_to_rfc_1123() in png.c
* (formerly png_convert_to_rfc_1152() in error)
* png_convert_from_struct_tm() in pngwrite.c, called in pngwrite.c
* png_convert_from_time_t() in pngwrite.c
* png_get_tIME() in pngget.c
* png_handle_tIME() in pngrutil.c, called in pngread.c
* png_set_tIME() in pngset.c
* png_write_tIME() in pngwutil.c, called in pngwrite.c
*
* All handle dates properly in a Y2K environment. The
* png_convert_from_time_t() function calls gmtime() to convert from system
* clock time, which returns (year - 1900), which we properly convert to
* the full 4-digit year. There is a possibility that applications using
* libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
* function, or that they are incorrectly passing only a 2-digit year
* instead of "year - 1900" into the png_convert_from_struct_tm() function,
* but this is not under our control. The libpng documentation has always
* stated that it works with 4-digit years, and the APIs have been
* documented as such.
*
* The tIME chunk itself is also Y2K compliant. It uses a 2-byte unsigned
* integer to hold the year, and can hold years as large as 65535.
*
* zlib, upon which libpng depends, is also Y2K compliant. It contains
* no date-related code.
*
* Glenn Randers-Pehrson
* libpng maintainer
* PNG Development Group
*/
#ifndef PNG_H
#define PNG_H
/* This is not the place to learn how to use libpng. The file libpng-manual.txt
* describes how to use libpng, and the file example.c summarizes it
* with some code on which to build. This file is useful for looking
* at the actual function definitions and structure components.
*/
/* Version information for png.h - this should match the version in png.c */
#define PNG_LIBPNG_VER_STRING "1.5.5rc01"
#define PNG_HEADER_VERSION_STRING \
" libpng version 1.5.5rc01 - September 15, 2011\n"
#define PNG_LIBPNG_VER_SONUM 15
#define PNG_LIBPNG_VER_DLLNUM 15
/* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
#define PNG_LIBPNG_VER_MAJOR 1
#define PNG_LIBPNG_VER_MINOR 5
#define PNG_LIBPNG_VER_RELEASE 5
/* This should match the numeric part of the final component of
* PNG_LIBPNG_VER_STRING, omitting any leading zero:
*/
#define PNG_LIBPNG_VER_BUILD 01
/* Release Status */
#define PNG_LIBPNG_BUILD_ALPHA 1
#define PNG_LIBPNG_BUILD_BETA 2
#define PNG_LIBPNG_BUILD_RC 3
#define PNG_LIBPNG_BUILD_STABLE 4
#define PNG_LIBPNG_BUILD_RELEASE_STATUS_MASK 7
/* Release-Specific Flags */
#define PNG_LIBPNG_BUILD_PATCH 8 /* Can be OR'ed with
PNG_LIBPNG_BUILD_STABLE only */
#define PNG_LIBPNG_BUILD_PRIVATE 16 /* Cannot be OR'ed with
PNG_LIBPNG_BUILD_SPECIAL */
#define PNG_LIBPNG_BUILD_SPECIAL 32 /* Cannot be OR'ed with
PNG_LIBPNG_BUILD_PRIVATE */
#define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_BETA
/* Careful here. At one time, Guy wanted to use 082, but that would be octal.
* We must not include leading zeros.
* Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only
* version 1.0.0 was mis-numbered 100 instead of 10000). From
* version 1.0.1 it's xxyyzz, where x=major, y=minor, z=release
*/
#define PNG_LIBPNG_VER 10505 /* 1.5.5 */
/* Library configuration: these options cannot be changed after
* the library has been built.
*/
#ifndef PNGLCONF_H
/* If pnglibconf.h is missing, you can
* copy scripts/pnglibconf.h.prebuilt to pnglibconf.h
*/
# include "pnglibconf.h"
#endif
#ifndef PNG_VERSION_INFO_ONLY
# ifndef PNG_BUILDING_SYMBOL_TABLE
/*
* Standard header files (not needed for the version info or while
* building symbol table -- see scripts/pnglibconf.dfa)
*/
# ifdef PNG_SETJMP_SUPPORTED
# include <setjmp.h>
# endif
/* Need the time information for converting tIME chunks, it
* defines struct tm:
*/
# ifdef PNG_CONVERT_tIME_SUPPORTED
/* "time.h" functions are not supported on all operating systems */
# include <time.h>
# endif
# endif
/* Machine specific configuration. */
# include "pngconf.h"
#endif
/*
* Added at libpng-1.2.8
*
* Ref MSDN: Private as priority over Special
* VS_FF_PRIVATEBUILD File *was not* built using standard release
* procedures. If this value is given, the StringFileInfo block must
* contain a PrivateBuild string.
*
* VS_FF_SPECIALBUILD File *was* built by the original company using
* standard release procedures but is a variation of the standard
* file of the same version number. If this value is given, the
* StringFileInfo block must contain a SpecialBuild string.
*/
#ifdef PNG_USER_PRIVATEBUILD /* From pnglibconf.h */
# define PNG_LIBPNG_BUILD_TYPE \
(PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_PRIVATE)
#else
# ifdef PNG_LIBPNG_SPECIALBUILD
# define PNG_LIBPNG_BUILD_TYPE \
(PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_SPECIAL)
# else
# define PNG_LIBPNG_BUILD_TYPE (PNG_LIBPNG_BUILD_BASE_TYPE)
# endif
#endif
#ifndef PNG_VERSION_INFO_ONLY
/* Inhibit C++ name-mangling for libpng functions but not for system calls. */
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/* Version information for C files, stored in png.c. This had better match
* the version above.
*/
#define png_libpng_ver png_get_header_ver(NULL)
/* This file is arranged in several sections:
*
* 1. Any configuration options that can be specified by for the application
* code when it is built. (Build time configuration is in pnglibconf.h)
* 2. Type definitions (base types are defined in pngconf.h), structure
* definitions.
* 3. Exported library functions.
*
* The library source code has additional files (principally pngpriv.h) that
* allow configuration of the library.
*/
/* Section 1: run time configuration
* See pnglibconf.h for build time configuration
*
* Run time configuration allows the application to choose between
* implementations of certain arithmetic APIs. The default is set
* at build time and recorded in pnglibconf.h, but it is safe to
* override these (and only these) settings. Note that this won't
* change what the library does, only application code, and the
* settings can (and probably should) be made on a per-file basis
* by setting the #defines before including png.h
*
* Use macros to read integers from PNG data or use the exported
* functions?
* PNG_USE_READ_MACROS: use the macros (see below) Note that
* the macros evaluate their argument multiple times.
* PNG_NO_USE_READ_MACROS: call the relevant library function.
*
* Use the alternative algorithm for compositing alpha samples that
* does not use division?
* PNG_READ_COMPOSITE_NODIV_SUPPORTED: use the 'no division'
* algorithm.
* PNG_NO_READ_COMPOSITE_NODIV: use the 'division' algorithm.
*
* How to handle benign errors if PNG_ALLOW_BENIGN_ERRORS is
* false?
* PNG_ALLOW_BENIGN_ERRORS: map calls to the benign error
* APIs to png_warning.
* Otherwise the calls are mapped to png_error.
*/
/* Section 2: type definitions, including structures and compile time
* constants.
* See pngconf.h for base types that vary by machine/system
*/
/* This triggers a compiler error in png.c, if png.c and png.h
* do not agree upon the version number.
*/
typedef char* png_libpng_version_1_5_5rc01;
/* Three color definitions. The order of the red, green, and blue, (and the
* exact size) is not important, although the size of the fields need to
* be png_byte or png_uint_16 (as defined below).
*/
typedef struct png_color_struct
{
png_byte red;
png_byte green;
png_byte blue;
} png_color;
typedef png_color FAR * png_colorp;
typedef PNG_CONST png_color FAR * png_const_colorp;
typedef png_color FAR * FAR * png_colorpp;
typedef struct png_color_16_struct
{
png_byte index; /* used for palette files */
png_uint_16 red; /* for use in red green blue files */
png_uint_16 green;
png_uint_16 blue;
png_uint_16 gray; /* for use in grayscale files */
} png_color_16;
typedef png_color_16 FAR * png_color_16p;
typedef PNG_CONST png_color_16 FAR * png_const_color_16p;
typedef png_color_16 FAR * FAR * png_color_16pp;
typedef struct png_color_8_struct
{
png_byte red; /* for use in red green blue files */
png_byte green;
png_byte blue;
png_byte gray; /* for use in grayscale files */
png_byte alpha; /* for alpha channel files */
} png_color_8;
typedef png_color_8 FAR * png_color_8p;
typedef PNG_CONST png_color_8 FAR * png_const_color_8p;
typedef png_color_8 FAR * FAR * png_color_8pp;
/*
* The following two structures are used for the in-core representation
* of sPLT chunks.
*/
typedef struct png_sPLT_entry_struct
{
png_uint_16 red;
png_uint_16 green;
png_uint_16 blue;
png_uint_16 alpha;
png_uint_16 frequency;
} png_sPLT_entry;
typedef png_sPLT_entry FAR * png_sPLT_entryp;
typedef PNG_CONST png_sPLT_entry FAR * png_const_sPLT_entryp;
typedef png_sPLT_entry FAR * FAR * png_sPLT_entrypp;
/* When the depth of the sPLT palette is 8 bits, the color and alpha samples
* occupy the LSB of their respective members, and the MSB of each member
* is zero-filled. The frequency member always occupies the full 16 bits.
*/
typedef struct png_sPLT_struct
{
png_charp name; /* palette name */
png_byte depth; /* depth of palette samples */
png_sPLT_entryp entries; /* palette entries */
png_int_32 nentries; /* number of palette entries */
} png_sPLT_t;
typedef png_sPLT_t FAR * png_sPLT_tp;
typedef PNG_CONST png_sPLT_t FAR * png_const_sPLT_tp;
typedef png_sPLT_t FAR * FAR * png_sPLT_tpp;
#ifdef PNG_TEXT_SUPPORTED
/* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file,
* and whether that contents is compressed or not. The "key" field
* points to a regular zero-terminated C string. The "text", "lang", and
* "lang_key" fields can be regular C strings, empty strings, or NULL pointers.
* However, the structure returned by png_get_text() will always contain
* regular zero-terminated C strings (possibly empty), never NULL pointers,
* so they can be safely used in printf() and other string-handling functions.
*/
typedef struct png_text_struct
{
int compression; /* compression value:
-1: tEXt, none
0: zTXt, deflate
1: iTXt, none
2: iTXt, deflate */
png_charp key; /* keyword, 1-79 character description of "text" */
png_charp text; /* comment, may be an empty string (ie "")
or a NULL pointer */
png_size_t text_length; /* length of the text string */
png_size_t itxt_length; /* length of the itxt string */
png_charp lang; /* language code, 0-79 characters
or a NULL pointer */
png_charp lang_key; /* keyword translated UTF-8 string, 0 or more
chars or a NULL pointer */
} png_text;
typedef png_text FAR * png_textp;
typedef PNG_CONST png_text FAR * png_const_textp;
typedef png_text FAR * FAR * png_textpp;
#endif
/* Supported compression types for text in PNG files (tEXt, and zTXt).
* The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */
#define PNG_TEXT_COMPRESSION_NONE_WR -3
#define PNG_TEXT_COMPRESSION_zTXt_WR -2
#define PNG_TEXT_COMPRESSION_NONE -1
#define PNG_TEXT_COMPRESSION_zTXt 0
#define PNG_ITXT_COMPRESSION_NONE 1
#define PNG_ITXT_COMPRESSION_zTXt 2
#define PNG_TEXT_COMPRESSION_LAST 3 /* Not a valid value */
/* png_time is a way to hold the time in an machine independent way.
* Two conversions are provided, both from time_t and struct tm. There
* is no portable way to convert to either of these structures, as far
* as I know. If you know of a portable way, send it to me. As a side
* note - PNG has always been Year 2000 compliant!
*/
typedef struct png_time_struct
{
png_uint_16 year; /* full year, as in, 1995 */
png_byte month; /* month of year, 1 - 12 */
png_byte day; /* day of month, 1 - 31 */
png_byte hour; /* hour of day, 0 - 23 */
png_byte minute; /* minute of hour, 0 - 59 */
png_byte second; /* second of minute, 0 - 60 (for leap seconds) */
} png_time;
typedef png_time FAR * png_timep;
typedef PNG_CONST png_time FAR * png_const_timep;
typedef png_time FAR * FAR * png_timepp;
#if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED) || \
defined(PNG_HANDLE_AS_UNKNOWN_SUPPORTED)
/* png_unknown_chunk is a structure to hold queued chunks for which there is
* no specific support. The idea is that we can use this to queue
* up private chunks for output even though the library doesn't actually
* know about their semantics.
*/
typedef struct png_unknown_chunk_t
{
png_byte name[5];
png_byte *data;
png_size_t size;
/* libpng-using applications should NOT directly modify this byte. */
png_byte location; /* mode of operation at read time */
}
png_unknown_chunk;
typedef png_unknown_chunk FAR * png_unknown_chunkp;
typedef PNG_CONST png_unknown_chunk FAR * png_const_unknown_chunkp;
typedef png_unknown_chunk FAR * FAR * png_unknown_chunkpp;
#endif
/* Values for the unknown chunk location byte */
#define PNG_HAVE_IHDR 0x01
#define PNG_HAVE_PLTE 0x02
#define PNG_AFTER_IDAT 0x08
/* The complete definition of png_info has, as of libpng-1.5.0,
* been moved into a separate header file that is not accessible to
* applications. Read libpng-manual.txt or libpng.3 for more info.
*/
typedef struct png_info_def png_info;
typedef png_info FAR * png_infop;
typedef PNG_CONST png_info FAR * png_const_infop;
typedef png_info FAR * FAR * png_infopp;
/* Maximum positive integer used in PNG is (2^31)-1 */
#define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
#define PNG_UINT_32_MAX ((png_uint_32)(-1))
#define PNG_SIZE_MAX ((png_size_t)(-1))
/* These are constants for fixed point values encoded in the
* PNG specification manner (x100000)
*/
#define PNG_FP_1 100000
#define PNG_FP_HALF 50000
#define PNG_FP_MAX ((png_fixed_point)0x7fffffffL)
#define PNG_FP_MIN (-PNG_FP_MAX)
/* These describe the color_type field in png_info. */
/* color type masks */
#define PNG_COLOR_MASK_PALETTE 1
#define PNG_COLOR_MASK_COLOR 2
#define PNG_COLOR_MASK_ALPHA 4
/* color types. Note that not all combinations are legal */
#define PNG_COLOR_TYPE_GRAY 0
#define PNG_COLOR_TYPE_PALETTE (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
#define PNG_COLOR_TYPE_RGB (PNG_COLOR_MASK_COLOR)
#define PNG_COLOR_TYPE_RGB_ALPHA (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
#define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
/* aliases */
#define PNG_COLOR_TYPE_RGBA PNG_COLOR_TYPE_RGB_ALPHA
#define PNG_COLOR_TYPE_GA PNG_COLOR_TYPE_GRAY_ALPHA
/* This is for compression type. PNG 1.0-1.2 only define the single type. */
#define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */
#define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
/* This is for filter type. PNG 1.0-1.2 only define the single type. */
#define PNG_FILTER_TYPE_BASE 0 /* Single row per-byte filtering */
#define PNG_INTRAPIXEL_DIFFERENCING 64 /* Used only in MNG datastreams */
#define PNG_FILTER_TYPE_DEFAULT PNG_FILTER_TYPE_BASE
/* These are for the interlacing type. These values should NOT be changed. */
#define PNG_INTERLACE_NONE 0 /* Non-interlaced image */
#define PNG_INTERLACE_ADAM7 1 /* Adam7 interlacing */
#define PNG_INTERLACE_LAST 2 /* Not a valid value */
/* These are for the oFFs chunk. These values should NOT be changed. */
#define PNG_OFFSET_PIXEL 0 /* Offset in pixels */
#define PNG_OFFSET_MICROMETER 1 /* Offset in micrometers (1/10^6 meter) */
#define PNG_OFFSET_LAST 2 /* Not a valid value */
/* These are for the pCAL chunk. These values should NOT be changed. */
#define PNG_EQUATION_LINEAR 0 /* Linear transformation */
#define PNG_EQUATION_BASE_E 1 /* Exponential base e transform */
#define PNG_EQUATION_ARBITRARY 2 /* Arbitrary base exponential transform */
#define PNG_EQUATION_HYPERBOLIC 3 /* Hyperbolic sine transformation */
#define PNG_EQUATION_LAST 4 /* Not a valid value */
/* These are for the sCAL chunk. These values should NOT be changed. */
#define PNG_SCALE_UNKNOWN 0 /* unknown unit (image scale) */
#define PNG_SCALE_METER 1 /* meters per pixel */
#define PNG_SCALE_RADIAN 2 /* radians per pixel */
#define PNG_SCALE_LAST 3 /* Not a valid value */
/* These are for the pHYs chunk. These values should NOT be changed. */
#define PNG_RESOLUTION_UNKNOWN 0 /* pixels/unknown unit (aspect ratio) */
#define PNG_RESOLUTION_METER 1 /* pixels/meter */
#define PNG_RESOLUTION_LAST 2 /* Not a valid value */
/* These are for the sRGB chunk. These values should NOT be changed. */
#define PNG_sRGB_INTENT_PERCEPTUAL 0
#define PNG_sRGB_INTENT_RELATIVE 1
#define PNG_sRGB_INTENT_SATURATION 2
#define PNG_sRGB_INTENT_ABSOLUTE 3
#define PNG_sRGB_INTENT_LAST 4 /* Not a valid value */
/* This is for text chunks */
#define PNG_KEYWORD_MAX_LENGTH 79
/* Maximum number of entries in PLTE/sPLT/tRNS arrays */
#define PNG_MAX_PALETTE_LENGTH 256
/* These determine if an ancillary chunk's data has been successfully read
* from the PNG header, or if the application has filled in the corresponding
* data in the info_struct to be written into the output file. The values
* of the PNG_INFO_<chunk> defines should NOT be changed.
*/
#define PNG_INFO_gAMA 0x0001
#define PNG_INFO_sBIT 0x0002
#define PNG_INFO_cHRM 0x0004
#define PNG_INFO_PLTE 0x0008
#define PNG_INFO_tRNS 0x0010
#define PNG_INFO_bKGD 0x0020
#define PNG_INFO_hIST 0x0040
#define PNG_INFO_pHYs 0x0080
#define PNG_INFO_oFFs 0x0100
#define PNG_INFO_tIME 0x0200
#define PNG_INFO_pCAL 0x0400
#define PNG_INFO_sRGB 0x0800 /* GR-P, 0.96a */
#define PNG_INFO_iCCP 0x1000 /* ESR, 1.0.6 */
#define PNG_INFO_sPLT 0x2000 /* ESR, 1.0.6 */
#define PNG_INFO_sCAL 0x4000 /* ESR, 1.0.6 */
#define PNG_INFO_IDAT 0x8000 /* ESR, 1.0.6 */
/* This is used for the transformation routines, as some of them
* change these values for the row. It also should enable using
* the routines for other purposes.
*/
typedef struct png_row_info_struct
{
png_uint_32 width; /* width of row */
png_size_t rowbytes; /* number of bytes in row */
png_byte color_type; /* color type of row */
png_byte bit_depth; /* bit depth of row */
png_byte channels; /* number of channels (1, 2, 3, or 4) */
png_byte pixel_depth; /* bits per pixel (depth * channels) */
} png_row_info;
typedef png_row_info FAR * png_row_infop;
typedef png_row_info FAR * FAR * png_row_infopp;
/* The complete definition of png_struct has, as of libpng-1.5.0,
* been moved into a separate header file that is not accessible to
* applications. Read libpng-manual.txt or libpng.3 for more info.
*/
typedef struct png_struct_def png_struct;
typedef PNG_CONST png_struct FAR * png_const_structp;
typedef png_struct FAR * png_structp;
/* These are the function types for the I/O functions and for the functions
* that allow the user to override the default I/O functions with his or her
* own. The png_error_ptr type should match that of user-supplied warning
* and error functions, while the png_rw_ptr type should match that of the
* user read/write data functions. Note that the 'write' function must not
* modify the buffer it is passed. The 'read' function, on the other hand, is
* expected to return the read data in the buffer.
*/
typedef PNG_CALLBACK(void, *png_error_ptr, (png_structp, png_const_charp));
typedef PNG_CALLBACK(void, *png_rw_ptr, (png_structp, png_bytep, png_size_t));
typedef PNG_CALLBACK(void, *png_flush_ptr, (png_structp));
typedef PNG_CALLBACK(void, *png_read_status_ptr, (png_structp, png_uint_32,
int));
typedef PNG_CALLBACK(void, *png_write_status_ptr, (png_structp, png_uint_32,
int));
#ifdef PNG_PROGRESSIVE_READ_SUPPORTED
typedef PNG_CALLBACK(void, *png_progressive_info_ptr, (png_structp, png_infop));
typedef PNG_CALLBACK(void, *png_progressive_end_ptr, (png_structp, png_infop));
/* The following callback receives png_uint_32 row_number, int pass for the
* png_bytep data of the row. When transforming an interlaced image the
* row number is the row number within the sub-image of the interlace pass, so
* the value will increase to the height of the sub-image (not the full image)
* then reset to 0 for the next pass.
*
* Use PNG_ROW_FROM_PASS_ROW(row, pass) and PNG_COL_FROM_PASS_COL(col, pass) to
* find the output pixel (x,y) given an interlaced sub-image pixel
* (row,col,pass). (See below for these macros.)
*/
typedef PNG_CALLBACK(void, *png_progressive_row_ptr, (png_structp, png_bytep,
png_uint_32, int));
#endif
#if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
typedef PNG_CALLBACK(void, *png_user_transform_ptr, (png_structp, png_row_infop,
png_bytep));
#endif
#ifdef PNG_USER_CHUNKS_SUPPORTED
typedef PNG_CALLBACK(int, *png_user_chunk_ptr, (png_structp,
png_unknown_chunkp));
#endif
#ifdef PNG_UNKNOWN_CHUNKS_SUPPORTED
typedef PNG_CALLBACK(void, *png_unknown_chunk_ptr, (png_structp));
#endif
#ifdef PNG_SETJMP_SUPPORTED
/* This must match the function definition in <setjmp.h>, and the application
* must include this before png.h to obtain the definition of jmp_buf. The
* function is required to be PNG_NORETURN, but this is not checked. If the
* function does return the application will crash via an abort() or similar
* system level call.
*
* If you get a warning here while building the library you may need to make
* changes to ensure that pnglibconf.h records the calling convention used by
* your compiler. This may be very difficult - try using a different compiler
* to build the library!
*/
PNG_FUNCTION(void, (PNGCAPI *png_longjmp_ptr), PNGARG((jmp_buf, int)), typedef);
#endif
/* Transform masks for the high-level interface */
#define PNG_TRANSFORM_IDENTITY 0x0000 /* read and write */
#define PNG_TRANSFORM_STRIP_16 0x0001 /* read only */
#define PNG_TRANSFORM_STRIP_ALPHA 0x0002 /* read only */
#define PNG_TRANSFORM_PACKING 0x0004 /* read and write */
#define PNG_TRANSFORM_PACKSWAP 0x0008 /* read and write */
#define PNG_TRANSFORM_EXPAND 0x0010 /* read only */
#define PNG_TRANSFORM_INVERT_MONO 0x0020 /* read and write */
#define PNG_TRANSFORM_SHIFT 0x0040 /* read and write */
#define PNG_TRANSFORM_BGR 0x0080 /* read and write */
#define PNG_TRANSFORM_SWAP_ALPHA 0x0100 /* read and write */
#define PNG_TRANSFORM_SWAP_ENDIAN 0x0200 /* read and write */
#define PNG_TRANSFORM_INVERT_ALPHA 0x0400 /* read and write */
#define PNG_TRANSFORM_STRIP_FILLER 0x0800 /* write only */
/* Added to libpng-1.2.34 */
#define PNG_TRANSFORM_STRIP_FILLER_BEFORE PNG_TRANSFORM_STRIP_FILLER
#define PNG_TRANSFORM_STRIP_FILLER_AFTER 0x1000 /* write only */
/* Added to libpng-1.4.0 */
#define PNG_TRANSFORM_GRAY_TO_RGB 0x2000 /* read only */
/* Added to libpng-1.5.4 */
#define PNG_TRANSFORM_EXPAND_16 0x4000 /* read only */
#define PNG_TRANSFORM_SCALE_16 0x8000 /* read only */
/* Flags for MNG supported features */
#define PNG_FLAG_MNG_EMPTY_PLTE 0x01
#define PNG_FLAG_MNG_FILTER_64 0x04
#define PNG_ALL_MNG_FEATURES 0x05
/* NOTE: prior to 1.5 these functions had no 'API' style declaration,
* this allowed the zlib default functions to be used on Windows
* platforms. In 1.5 the zlib default malloc (which just calls malloc and
* ignores the first argument) should be completely compatible with the
* following.
*/
typedef PNG_CALLBACK(png_voidp, *png_malloc_ptr, (png_structp,
png_alloc_size_t));
typedef PNG_CALLBACK(void, *png_free_ptr, (png_structp, png_voidp));
typedef png_struct FAR * FAR * png_structpp;
/* Section 3: exported functions
* Here are the function definitions most commonly used. This is not
* the place to find out how to use libpng. See libpng-manual.txt for the
* full explanation, see example.c for the summary. This just provides
* a simple one line description of the use of each function.
*
* The PNG_EXPORT() and PNG_EXPORTA() macros used below are defined in
* pngconf.h and in the *.dfn files in the scripts directory.
*
* PNG_EXPORT(ordinal, type, name, (args));
*
* ordinal: ordinal that is used while building
* *.def files. The ordinal value is only
* relevant when preprocessing png.h with
* the *.dfn files for building symbol table
* entries, and are removed by pngconf.h.
* type: return type of the function
* name: function name
* args: function arguments, with types
*
* When we wish to append attributes to a function prototype we use
* the PNG_EXPORTA() macro instead.
*
* PNG_EXPORTA(ordinal, type, name, (args), attributes);
*
* ordinal, type, name, and args: same as in PNG_EXPORT().
* attributes: function attributes
*/
/* Returns the version number of the library */
PNG_EXPORT(1, png_uint_32, png_access_version_number, (void));
/* Tell lib we have already handled the first <num_bytes> magic bytes.
* Handling more than 8 bytes from the beginning of the file is an error.
*/
PNG_EXPORT(2, void, png_set_sig_bytes, (png_structp png_ptr, int num_bytes));
/* Check sig[start] through sig[start + num_to_check - 1] to see if it's a
* PNG file. Returns zero if the supplied bytes match the 8-byte PNG
* signature, and non-zero otherwise. Having num_to_check == 0 or
* start > 7 will always fail (ie return non-zero).
*/
PNG_EXPORT(3, int, png_sig_cmp, (png_const_bytep sig, png_size_t start,
png_size_t num_to_check));
/* Simple signature checking function. This is the same as calling
* png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n).
*/
#define png_check_sig(sig, n) !png_sig_cmp((sig), 0, (n))
/* Allocate and initialize png_ptr struct for reading, and any other memory. */
PNG_EXPORTA(4, png_structp, png_create_read_struct,
(png_const_charp user_png_ver, png_voidp error_ptr,
png_error_ptr error_fn, png_error_ptr warn_fn),
PNG_ALLOCATED);
/* Allocate and initialize png_ptr struct for writing, and any other memory */
PNG_EXPORTA(5, png_structp, png_create_write_struct,
(png_const_charp user_png_ver, png_voidp error_ptr, png_error_ptr error_fn,
png_error_ptr warn_fn),
PNG_ALLOCATED);
PNG_EXPORT(6, png_size_t, png_get_compression_buffer_size,
(png_const_structp png_ptr));
PNG_EXPORT(7, void, png_set_compression_buffer_size, (png_structp png_ptr,
png_size_t size));
/* Moved from pngconf.h in 1.4.0 and modified to ensure setjmp/longjmp
* match up.
*/
#ifdef PNG_SETJMP_SUPPORTED
/* This function returns the jmp_buf built in to *png_ptr. It must be
* supplied with an appropriate 'longjmp' function to use on that jmp_buf
* unless the default error function is overridden in which case NULL is
* acceptable. The size of the jmp_buf is checked against the actual size
* allocated by the library - the call will return NULL on a mismatch
* indicating an ABI mismatch.
*/
PNG_EXPORT(8, jmp_buf*, png_set_longjmp_fn, (png_structp png_ptr,
png_longjmp_ptr longjmp_fn, size_t jmp_buf_size));
# define png_jmpbuf(png_ptr) \
(*png_set_longjmp_fn((png_ptr), longjmp, sizeof (jmp_buf)))
#else
# define png_jmpbuf(png_ptr) \
(LIBPNG_WAS_COMPILED_WITH__PNG_NO_SETJMP)
#endif
/* This function should be used by libpng applications in place of
* longjmp(png_ptr->jmpbuf, val). If longjmp_fn() has been set, it
* will use it; otherwise it will call PNG_ABORT(). This function was
* added in libpng-1.5.0.
*/
PNG_EXPORTA(9, void, png_longjmp, (png_structp png_ptr, int val),
PNG_NORETURN);
#ifdef PNG_READ_SUPPORTED
/* Reset the compression stream */
PNG_EXPORT(10, int, png_reset_zstream, (png_structp png_ptr));
#endif
/* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */
#ifdef PNG_USER_MEM_SUPPORTED
PNG_EXPORTA(11, png_structp, png_create_read_struct_2,
(png_const_charp user_png_ver, png_voidp error_ptr, png_error_ptr error_fn,
png_error_ptr warn_fn,
png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn),
PNG_ALLOCATED);
PNG_EXPORTA(12, png_structp, png_create_write_struct_2,
(png_const_charp user_png_ver, png_voidp error_ptr, png_error_ptr error_fn,
png_error_ptr warn_fn,
png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn),
PNG_ALLOCATED);
#endif
/* Write the PNG file signature. */
PNG_EXPORT(13, void, png_write_sig, (png_structp png_ptr));
/* Write a PNG chunk - size, type, (optional) data, CRC. */
PNG_EXPORT(14, void, png_write_chunk, (png_structp png_ptr, png_const_bytep
chunk_name, png_const_bytep data, png_size_t length));
/* Write the start of a PNG chunk - length and chunk name. */
PNG_EXPORT(15, void, png_write_chunk_start, (png_structp png_ptr,
png_const_bytep chunk_name, png_uint_32 length));
/* Write the data of a PNG chunk started with png_write_chunk_start(). */
PNG_EXPORT(16, void, png_write_chunk_data, (png_structp png_ptr,
png_const_bytep data, png_size_t length));
/* Finish a chunk started with png_write_chunk_start() (includes CRC). */
PNG_EXPORT(17, void, png_write_chunk_end, (png_structp png_ptr));
/* Allocate and initialize the info structure */
PNG_EXPORTA(18, png_infop, png_create_info_struct, (png_structp png_ptr),
PNG_ALLOCATED);
PNG_EXPORT(19, void, png_info_init_3, (png_infopp info_ptr,
png_size_t png_info_struct_size));
/* Writes all the PNG information before the image. */
PNG_EXPORT(20, void, png_write_info_before_PLTE,
(png_structp png_ptr, png_infop info_ptr));
PNG_EXPORT(21, void, png_write_info,
(png_structp png_ptr, png_infop info_ptr));
#ifdef PNG_SEQUENTIAL_READ_SUPPORTED
/* Read the information before the actual image data. */
PNG_EXPORT(22, void, png_read_info,
(png_structp png_ptr, png_infop info_ptr));
#endif
#ifdef PNG_TIME_RFC1123_SUPPORTED
PNG_EXPORT(23, png_const_charp, png_convert_to_rfc1123,
(png_structp png_ptr,
png_const_timep ptime));
#endif
#ifdef PNG_CONVERT_tIME_SUPPORTED
/* Convert from a struct tm to png_time */
PNG_EXPORT(24, void, png_convert_from_struct_tm, (png_timep ptime,
PNG_CONST struct tm FAR * ttime));
/* Convert from time_t to png_time. Uses gmtime() */
PNG_EXPORT(25, void, png_convert_from_time_t,
(png_timep ptime, time_t ttime));
#endif /* PNG_CONVERT_tIME_SUPPORTED */
#ifdef PNG_READ_EXPAND_SUPPORTED
/* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */
PNG_EXPORT(26, void, png_set_expand, (png_structp png_ptr));
PNG_EXPORT(27, void, png_set_expand_gray_1_2_4_to_8, (png_structp png_ptr));
PNG_EXPORT(28, void, png_set_palette_to_rgb, (png_structp png_ptr));
PNG_EXPORT(29, void, png_set_tRNS_to_alpha, (png_structp png_ptr));
#endif
#ifdef PNG_READ_EXPAND_16_SUPPORTED
/* Expand to 16-bit channels, forces conversion of palette to RGB and expansion
* of a tRNS chunk if present.
*/
PNG_EXPORT(221, void, png_set_expand_16, (png_structp png_ptr));
#endif
#if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
/* Use blue, green, red order for pixels. */
PNG_EXPORT(30, void, png_set_bgr, (png_structp png_ptr));
#endif
#ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED
/* Expand the grayscale to 24-bit RGB if necessary. */
PNG_EXPORT(31, void, png_set_gray_to_rgb, (png_structp png_ptr));
#endif
#ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED
/* Reduce RGB to grayscale. */
PNG_FP_EXPORT(32, void, png_set_rgb_to_gray, (png_structp png_ptr,
int error_action, double red, double green));
PNG_FIXED_EXPORT(33, void, png_set_rgb_to_gray_fixed, (png_structp png_ptr,
int error_action, png_fixed_point red, png_fixed_point green));
PNG_EXPORT(34, png_byte, png_get_rgb_to_gray_status, (png_const_structp
png_ptr));
#endif
#ifdef PNG_BUILD_GRAYSCALE_PALETTE_SUPPORTED
PNG_EXPORT(35, void, png_build_grayscale_palette, (int bit_depth,
png_colorp palette));
#endif
#ifdef PNG_READ_ALPHA_MODE_SUPPORTED
/* How the alpha channel is interpreted - this affects how the color channels of
* a PNG file are returned when an alpha channel, or tRNS chunk in a palette
* file, is present.
*
* This has no effect on the way pixels are written into a PNG output
* datastream. The color samples in a PNG datastream are never premultiplied
* with the alpha samples.
*
* The default is to return data according to the PNG specification: the alpha
* channel is a linear measure of the contribution of the pixel to the
* corresponding composited pixel. The gamma encoded color channels must be
* scaled according to the contribution and to do this it is necessary to undo
* the encoding, scale the color values, perform the composition and reencode
* the values. This is the 'PNG' mode.
*
* The alternative is to 'associate' the alpha with the color information by
* storing color channel values that have been scaled by the alpha. The
* advantage is that the color channels can be resampled (the image can be
* scaled) in this form. The disadvantage is that normal practice is to store
* linear, not (gamma) encoded, values and this requires 16-bit channels for
* still images rather than the 8-bit channels that are just about sufficient if
* gamma encoding is used. In addition all non-transparent pixel values,
* including completely opaque ones, must be gamma encoded to produce the final
* image. This is the 'STANDARD', 'ASSOCIATED' or 'PREMULTIPLIED' mode (the
* latter being the two common names for associated alpha color channels.)
*
* Since it is not necessary to perform arithmetic on opaque color values so
* long as they are not to be resampled and are in the final color space it is
* possible to optimize the handling of alpha by storing the opaque pixels in
* the PNG format (adjusted for the output color space) while storing partially
* opaque pixels in the standard, linear, format. The accuracy required for
* standard alpha composition is relatively low, because the pixels are
* isolated, therefore typically the accuracy loss in storing 8-bit linear
* values is acceptable. (This is not true if the alpha channel is used to
* simulate transparency over large areas - use 16 bits or the PNG mode in
* this case!) This is the 'OPTIMIZED' mode. For this mode a pixel is
* treated as opaque only if the alpha value is equal to the maximum value.
*
* The final choice is to gamma encode the alpha channel as well. This is
* broken because, in practice, no implementation that uses this choice
* correctly undoes the encoding before handling alpha composition. Use this
* choice only if other serious errors in the software or hardware you use
* mandate it; the typical serious error is for dark halos to appear around
* opaque areas of the composited PNG image because of arithmetic overflow.
*
* The API function png_set_alpha_mode specifies which of these choices to use
* with an enumerated 'mode' value and the gamma of the required output:
*/
#define PNG_ALPHA_PNG 0 /* according to the PNG standard */
#define PNG_ALPHA_STANDARD 1 /* according to Porter/Duff */
#define PNG_ALPHA_ASSOCIATED 1 /* as above; this is the normal practice */
#define PNG_ALPHA_PREMULTIPLIED 1 /* as above */
#define PNG_ALPHA_OPTIMIZED 2 /* 'PNG' for opaque pixels, else 'STANDARD' */
#define PNG_ALPHA_BROKEN 3 /* the alpha channel is gamma encoded */
PNG_FP_EXPORT(227, void, png_set_alpha_mode, (png_structp png_ptr, int mode,
double output_gamma));
PNG_FIXED_EXPORT(228, void, png_set_alpha_mode_fixed, (png_structp png_ptr,
int mode, png_fixed_point output_gamma));
#endif
#if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_ALPHA_MODE_SUPPORTED)
/* The output_gamma value is a screen gamma in libpng terminology: it expresses
* how to decode the output values, not how they are encoded. The values used
* correspond to the normal numbers used to describe the overall gamma of a
* computer display system; for example 2.2 for an sRGB conformant system. The
* values are scaled by 100000 in the _fixed version of the API (so 220000 for
* sRGB.)
*
* The inverse of the value is always used to provide a default for the PNG file
* encoding if it has no gAMA chunk and if png_set_gamma() has not been called
* to override the PNG gamma information.
*
* When the ALPHA_OPTIMIZED mode is selected the output gamma is used to encode
* opaque pixels however pixels with lower alpha values are not encoded,
* regardless of the output gamma setting.
*
* When the standard Porter Duff handling is requested with mode 1 the output
* encoding is set to be linear and the output_gamma value is only relevant
* as a default for input data that has no gamma information. The linear output
* encoding will be overridden if png_set_gamma() is called - the results may be
* highly unexpected!
*
* The following numbers are derived from the sRGB standard and the research
* behind it. sRGB is defined to be approximated by a PNG gAMA chunk value of
* 0.45455 (1/2.2) for PNG. The value implicitly includes any viewing
* correction required to take account of any differences in the color
* environment of the original scene and the intended display environment; the
* value expresses how to *decode* the image for display, not how the original
* data was *encoded*.
*
* sRGB provides a peg for the PNG standard by defining a viewing environment.
* sRGB itself, and earlier TV standards, actually use a more complex transform
* (a linear portion then a gamma 2.4 power law) than PNG can express. (PNG is
* limited to simple power laws.) By saying that an image for direct display on
* an sRGB conformant system should be stored with a gAMA chunk value of 45455
* (11.3.3.2 and 11.3.3.5 of the ISO PNG specification) the PNG specification
* makes it possible to derive values for other display systems and
* environments.
*
* The Mac value is deduced from the sRGB based on an assumption that the actual
* extra viewing correction used in early Mac display systems was implemented as
* a power 1.45 lookup table.
*
* Any system where a programmable lookup table is used or where the behavior of
* the final display device characteristics can be changed requires system
* specific code to obtain the current characteristic. However this can be
* difficult and most PNG gamma correction only requires an approximate value.
*
* By default, if png_set_alpha_mode() is not called, libpng assumes that all
* values are unencoded, linear, values and that the output device also has a
* linear characteristic. This is only very rarely correct - it is invariably
* better to call png_set_alpha_mode() with PNG_DEFAULT_sRGB than rely on the
* default if you don't know what the right answer is!
*
* The special value PNG_GAMMA_MAC_18 indicates an older Mac system (pre Mac OS
* 10.6) which used a correction table to implement a somewhat lower gamma on an
* otherwise sRGB system.
*
* Both these values are reserved (not simple gamma values) in order to allow
* more precise correction internally in the future.
*
* NOTE: the following values can be passed to either the fixed or floating
* point APIs, but the floating point API will also accept floating point
* values.
*/
#define PNG_DEFAULT_sRGB -1 /* sRGB gamma and color space */
#define PNG_GAMMA_MAC_18 -2 /* Old Mac '1.8' gamma and color space */
#define PNG_GAMMA_sRGB 220000 /* Television standards--matches sRGB gamma */
#define PNG_GAMMA_LINEAR PNG_FP_1 /* Linear */
#endif
/* The following are examples of calls to png_set_alpha_mode to achieve the
* required overall gamma correction and, where necessary, alpha
* premultiplication.
*
* png_set_alpha_mode(pp, PNG_ALPHA_PNG, PNG_DEFAULT_sRGB);
* This is the default libpng handling of the alpha channel - it is not
* pre-multiplied into the color components. In addition the call states
* that the output is for a sRGB system and causes all PNG files without gAMA
* chunks to be assumed to be encoded using sRGB.
*
* png_set_alpha_mode(pp, PNG_ALPHA_PNG, PNG_GAMMA_MAC);
* In this case the output is assumed to be something like an sRGB conformant
* display preceeded by a power-law lookup table of power 1.45. This is how
* early Mac systems behaved.
*
* png_set_alpha_mode(pp, PNG_ALPHA_STANDARD, PNG_GAMMA_LINEAR);
* This is the classic Jim Blinn approach and will work in academic
* environments where everything is done by the book. It has the shortcoming
* of assuming that input PNG data with no gamma information is linear - this
* is unlikely to be correct unless the PNG files where generated locally.
* Most of the time the output precision will be so low as to show
* significant banding in dark areas of the image.
*
* png_set_expand_16(pp);
* png_set_alpha_mode(pp, PNG_ALPHA_STANDARD, PNG_DEFAULT_sRGB);
* This is a somewhat more realistic Jim Blinn inspired approach. PNG files
* are assumed to have the sRGB encoding if not marked with a gamma value and
* the output is always 16 bits per component. This permits accurate scaling
* and processing of the data. If you know that your input PNG files were
* generated locally you might need to replace PNG_DEFAULT_sRGB with the
* correct value for your system.
*
* png_set_alpha_mode(pp, PNG_ALPHA_OPTIMIZED, PNG_DEFAULT_sRGB);
* If you just need to composite the PNG image onto an existing background
* and if you control the code that does this you can use the optimization
* setting. In this case you just copy completely opaque pixels to the
* output. For pixels that are not completely transparent (you just skip
* those) you do the composition math using png_composite or png_composite_16
* below then encode the resultant 8-bit or 16-bit values to match the output
* encoding.
*
* Other cases
* If neither the PNG nor the standard linear encoding work for you because
* of the software or hardware you use then you have a big problem. The PNG
* case will probably result in halos around the image. The linear encoding
* will probably result in a washed out, too bright, image (it's actually too
* contrasty.) Try the ALPHA_OPTIMIZED mode above - this will probably
* substantially reduce the halos. Alternatively try:
*
* png_set_alpha_mode(pp, PNG_ALPHA_BROKEN, PNG_DEFAULT_sRGB);
* This option will also reduce the halos, but there will be slight dark
* halos round the opaque parts of the image where the background is light.
* In the OPTIMIZED mode the halos will be light halos where the background
* is dark. Take your pick - the halos are unavoidable unless you can get
* your hardware/software fixed! (The OPTIMIZED approach is slightly
* faster.)
*
* When the default gamma of PNG files doesn't match the output gamma.
* If you have PNG files with no gamma information png_set_alpha_mode allows
* you to provide a default gamma, but it also sets the ouput gamma to the
* matching value. If you know your PNG files have a gamma that doesn't
* match the output you can take advantage of the fact that
* png_set_alpha_mode always sets the output gamma but only sets the PNG
* default if it is not already set:
*
* png_set_alpha_mode(pp, PNG_ALPHA_PNG, PNG_DEFAULT_sRGB);
* png_set_alpha_mode(pp, PNG_ALPHA_PNG, PNG_GAMMA_MAC);
* The first call sets both the default and the output gamma values, the
* second call overrides the output gamma without changing the default. This
* is easier than achieving the same effect with png_set_gamma. You must use
* PNG_ALPHA_PNG for the first call - internal checking in png_set_alpha will
* fire if more than one call to png_set_alpha_mode and png_set_background is
* made in the same read operation, however multiple calls with PNG_ALPHA_PNG
* are ignored.
*/
#ifdef PNG_READ_STRIP_ALPHA_SUPPORTED
PNG_EXPORT(36, void, png_set_strip_alpha, (png_structp png_ptr));
#endif
#if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
PNG_EXPORT(37, void, png_set_swap_alpha, (png_structp png_ptr));
#endif
#if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
PNG_EXPORT(38, void, png_set_invert_alpha, (png_structp png_ptr));
#endif
#if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
/* Add a filler byte to 8-bit Gray or 24-bit RGB images. */
PNG_EXPORT(39, void, png_set_filler, (png_structp png_ptr, png_uint_32 filler,
int flags));
/* The values of the PNG_FILLER_ defines should NOT be changed */
# define PNG_FILLER_BEFORE 0
# define PNG_FILLER_AFTER 1
/* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
PNG_EXPORT(40, void, png_set_add_alpha,
(png_structp png_ptr, png_uint_32 filler,
int flags));
#endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */
#if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
/* Swap bytes in 16-bit depth files. */
PNG_EXPORT(41, void, png_set_swap, (png_structp png_ptr));
#endif
#if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
/* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */
PNG_EXPORT(42, void, png_set_packing, (png_structp png_ptr));
#endif
#if defined(PNG_READ_PACKSWAP_SUPPORTED) || \
defined(PNG_WRITE_PACKSWAP_SUPPORTED)
/* Swap packing order of pixels in bytes. */
PNG_EXPORT(43, void, png_set_packswap, (png_structp png_ptr));
#endif
#if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
/* Converts files to legal bit depths. */
PNG_EXPORT(44, void, png_set_shift, (png_structp png_ptr, png_const_color_8p
true_bits));
#endif
#if defined(PNG_READ_INTERLACING_SUPPORTED) || \
defined(PNG_WRITE_INTERLACING_SUPPORTED)
/* Have the code handle the interlacing. Returns the number of passes.
* MUST be called before png_read_update_info or png_start_read_image,
* otherwise it will not have the desired effect. Note that it is still
* necessary to call png_read_row or png_read_rows png_get_image_height
* times for each pass.
*/
PNG_EXPORT(45, int, png_set_interlace_handling, (png_structp png_ptr));
#endif
#if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
/* Invert monochrome files */
PNG_EXPORT(46, void, png_set_invert_mono, (png_structp png_ptr));
#endif
#ifdef PNG_READ_BACKGROUND_SUPPORTED
/* Handle alpha and tRNS by replacing with a background color. Prior to
* libpng-1.5.4 this API must not be called before the PNG file header has been
* read. Doing so will result in unexpected behavior and possible warnings or
* errors if the PNG file contains a bKGD chunk.
*/
PNG_FP_EXPORT(47, void, png_set_background, (png_structp png_ptr,
png_const_color_16p background_color, int background_gamma_code,
int need_expand, double background_gamma));
PNG_FIXED_EXPORT(215, void, png_set_background_fixed, (png_structp png_ptr,
png_const_color_16p background_color, int background_gamma_code,
int need_expand, png_fixed_point background_gamma));
#endif
#ifdef PNG_READ_BACKGROUND_SUPPORTED
# define PNG_BACKGROUND_GAMMA_UNKNOWN 0
# define PNG_BACKGROUND_GAMMA_SCREEN 1
# define PNG_BACKGROUND_GAMMA_FILE 2
# define PNG_BACKGROUND_GAMMA_UNIQUE 3
#endif
#ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED
/* Scale a 16-bit depth file down to 8-bit, accurately. */
PNG_EXPORT(229, void, png_set_scale_16, (png_structp png_ptr));
#endif
#ifdef PNG_READ_STRIP_16_TO_8_SUPPORTED
#define PNG_READ_16_TO_8 SUPPORTED /* Name prior to 1.5.4 */
/* Strip the second byte of information from a 16-bit depth file. */
PNG_EXPORT(48, void, png_set_strip_16, (png_structp png_ptr));
#endif
#ifdef PNG_READ_QUANTIZE_SUPPORTED
/* Turn on quantizing, and reduce the palette to the number of colors
* available.
*/
PNG_EXPORT(49, void, png_set_quantize,
(png_structp png_ptr, png_colorp palette,
int num_palette, int maximum_colors, png_const_uint_16p histogram,
int full_quantize));
#endif
#ifdef PNG_READ_GAMMA_SUPPORTED
/* The threshold on gamma processing is configurable but hard-wired into the
* library. The following is the floating point variant.
*/
#define PNG_GAMMA_THRESHOLD (PNG_GAMMA_THRESHOLD_FIXED*.00001)
/* Handle gamma correction. Screen_gamma=(display_exponent).
* NOTE: this API simply sets the screen and file gamma values. It will
* therefore override the value for gamma in a PNG file if it is called after
* the file header has been read - use with care - call before reading the PNG
* file for best results!
*
* These routines accept the same gamma values as png_set_alpha_mode (described
* above). The PNG_GAMMA_ defines and PNG_DEFAULT_sRGB can be passed to either
* API (floating point or fixed.) Notice, however, that the 'file_gamma' value
* is the inverse of a 'screen gamma' value.
*/
PNG_FP_EXPORT(50, void, png_set_gamma,
(png_structp png_ptr, double screen_gamma,
double override_file_gamma));
PNG_FIXED_EXPORT(208, void, png_set_gamma_fixed, (png_structp png_ptr,
png_fixed_point screen_gamma, png_fixed_point override_file_gamma));
#endif
#ifdef PNG_WRITE_FLUSH_SUPPORTED
/* Set how many lines between output flushes - 0 for no flushing */
PNG_EXPORT(51, void, png_set_flush, (png_structp png_ptr, int nrows));
/* Flush the current PNG output buffer */
PNG_EXPORT(52, void, png_write_flush, (png_structp png_ptr));
#endif
/* Optional update palette with requested transformations */
PNG_EXPORT(53, void, png_start_read_image, (png_structp png_ptr));
/* Optional call to update the users info structure */
PNG_EXPORT(54, void, png_read_update_info,
(png_structp png_ptr, png_infop info_ptr));
#ifdef PNG_SEQUENTIAL_READ_SUPPORTED
/* Read one or more rows of image data. */
PNG_EXPORT(55, void, png_read_rows, (png_structp png_ptr, png_bytepp row,
png_bytepp display_row, png_uint_32 num_rows));
#endif
#ifdef PNG_SEQUENTIAL_READ_SUPPORTED
/* Read a row of data. */
PNG_EXPORT(56, void, png_read_row, (png_structp png_ptr, png_bytep row,
png_bytep display_row));
#endif
#ifdef PNG_SEQUENTIAL_READ_SUPPORTED
/* Read the whole image into memory at once. */
PNG_EXPORT(57, void, png_read_image, (png_structp png_ptr, png_bytepp image));
#endif
/* Write a row of image data */
PNG_EXPORT(58, void, png_write_row,
(png_structp png_ptr, png_const_bytep row));
/* Write a few rows of image data: (*row) is not written; however, the type
* is declared as writeable to maintain compatibility with previous versions
* of libpng and to allow the 'display_row' array from read_rows to be passed
* unchanged to write_rows.
*/
PNG_EXPORT(59, void, png_write_rows, (png_structp png_ptr, png_bytepp row,
png_uint_32 num_rows));
/* Write the image data */
PNG_EXPORT(60, void, png_write_image,
(png_structp png_ptr, png_bytepp image));
/* Write the end of the PNG file. */
PNG_EXPORT(61, void, png_write_end,
(png_structp png_ptr, png_infop info_ptr));
#ifdef PNG_SEQUENTIAL_READ_SUPPORTED
/* Read the end of the PNG file. */
PNG_EXPORT(62, void, png_read_end, (png_structp png_ptr, png_infop info_ptr));
#endif
/* Free any memory associated with the png_info_struct */
PNG_EXPORT(63, void, png_destroy_info_struct, (png_structp png_ptr,
png_infopp info_ptr_ptr));
/* Free any memory associated with the png_struct and the png_info_structs */
PNG_EXPORT(64, void, png_destroy_read_struct, (png_structpp png_ptr_ptr,
png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr));
/* Free any memory associated with the png_struct and the png_info_structs */
PNG_EXPORT(65, void, png_destroy_write_struct, (png_structpp png_ptr_ptr,
png_infopp info_ptr_ptr));
/* Set the libpng method of handling chunk CRC errors */
PNG_EXPORT(66, void, png_set_crc_action,
(png_structp png_ptr, int crit_action, int ancil_action));
/* Values for png_set_crc_action() say how to handle CRC errors in
* ancillary and critical chunks, and whether to use the data contained
* therein. Note that it is impossible to "discard" data in a critical
* chunk. For versions prior to 0.90, the action was always error/quit,
* whereas in version 0.90 and later, the action for CRC errors in ancillary
* chunks is warn/discard. These values should NOT be changed.
*
* value action:critical action:ancillary
*/
#define PNG_CRC_DEFAULT 0 /* error/quit warn/discard data */
#define PNG_CRC_ERROR_QUIT 1 /* error/quit error/quit */
#define PNG_CRC_WARN_DISCARD 2 /* (INVALID) warn/discard data */
#define PNG_CRC_WARN_USE 3 /* warn/use data warn/use data */
#define PNG_CRC_QUIET_USE 4 /* quiet/use data quiet/use data */
#define PNG_CRC_NO_CHANGE 5 /* use current value use current value */
/* These functions give the user control over the scan-line filtering in
* libpng and the compression methods used by zlib. These functions are
* mainly useful for testing, as the defaults should work with most users.
* Those users who are tight on memory or want faster performance at the
* expense of compression can modify them. See the compression library
* header file (zlib.h) for an explination of the compression functions.
*/
/* Set the filtering method(s) used by libpng. Currently, the only valid
* value for "method" is 0.
*/
PNG_EXPORT(67, void, png_set_filter,
(png_structp png_ptr, int method, int filters));
/* Flags for png_set_filter() to say which filters to use. The flags
* are chosen so that they don't conflict with real filter types
* below, in case they are supplied instead of the #defined constants.
* These values should NOT be changed.
*/
#define PNG_NO_FILTERS 0x00
#define PNG_FILTER_NONE 0x08
#define PNG_FILTER_SUB 0x10
#define PNG_FILTER_UP 0x20
#define PNG_FILTER_AVG 0x40
#define PNG_FILTER_PAETH 0x80
#define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
PNG_FILTER_AVG | PNG_FILTER_PAETH)
/* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now.
* These defines should NOT be changed.
*/
#define PNG_FILTER_VALUE_NONE 0
#define PNG_FILTER_VALUE_SUB 1
#define PNG_FILTER_VALUE_UP 2
#define PNG_FILTER_VALUE_AVG 3
#define PNG_FILTER_VALUE_PAETH 4
#define PNG_FILTER_VALUE_LAST 5
#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED /* EXPERIMENTAL */
/* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_
* defines, either the default (minimum-sum-of-absolute-differences), or
* the experimental method (weighted-minimum-sum-of-absolute-differences).
*
* Weights are factors >= 1.0, indicating how important it is to keep the
* filter type consistent between rows. Larger numbers mean the current
* filter is that many times as likely to be the same as the "num_weights"
* previous filters. This is cumulative for each previous row with a weight.
* There needs to be "num_weights" values in "filter_weights", or it can be
* NULL if the weights aren't being specified. Weights have no influence on
* the selection of the first row filter. Well chosen weights can (in theory)
* improve the compression for a given image.
*
* Costs are factors >= 1.0 indicating the relative decoding costs of a
* filter type. Higher costs indicate more decoding expense, and are
* therefore less likely to be selected over a filter with lower computational
* costs. There needs to be a value in "filter_costs" for each valid filter
* type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't
* setting the costs. Costs try to improve the speed of decompression without
* unduly increasing the compressed image size.
*
* A negative weight or cost indicates the default value is to be used, and
* values in the range [0.0, 1.0) indicate the value is to remain unchanged.
* The default values for both weights and costs are currently 1.0, but may
* change if good general weighting/cost heuristics can be found. If both
* the weights and costs are set to 1.0, this degenerates the WEIGHTED method
* to the UNWEIGHTED method, but with added encoding time/computation.
*/
PNG_FP_EXPORT(68, void, png_set_filter_heuristics, (png_structp png_ptr,
int heuristic_method, int num_weights, png_const_doublep filter_weights,
png_const_doublep filter_costs));
PNG_FIXED_EXPORT(209, void, png_set_filter_heuristics_fixed,
(png_structp png_ptr,
int heuristic_method, int num_weights, png_const_fixed_point_p
filter_weights, png_const_fixed_point_p filter_costs));
#endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
/* Heuristic used for row filter selection. These defines should NOT be
* changed.
*/
#define PNG_FILTER_HEURISTIC_DEFAULT 0 /* Currently "UNWEIGHTED" */
#define PNG_FILTER_HEURISTIC_UNWEIGHTED 1 /* Used by libpng < 0.95 */
#define PNG_FILTER_HEURISTIC_WEIGHTED 2 /* Experimental feature */
#define PNG_FILTER_HEURISTIC_LAST 3 /* Not a valid value */
#ifdef PNG_WRITE_SUPPORTED
/* Set the library compression level. Currently, valid values range from
* 0 - 9, corresponding directly to the zlib compression levels 0 - 9
* (0 - no compression, 9 - "maximal" compression). Note that tests have
* shown that zlib compression levels 3-6 usually perform as well as level 9
* for PNG images, and do considerably fewer caclulations. In the future,
* these values may not correspond directly to the zlib compression levels.
*/
PNG_EXPORT(69, void, png_set_compression_level,
(png_structp png_ptr, int level));
PNG_EXPORT(70, void, png_set_compression_mem_level, (png_structp png_ptr,
int mem_level));
PNG_EXPORT(71, void, png_set_compression_strategy, (png_structp png_ptr,
int strategy));
/* If PNG_WRITE_OPTIMIZE_CMF_SUPPORTED is defined, libpng will use a
* smaller value of window_bits if it can do so safely.
*/
PNG_EXPORT(72, void, png_set_compression_window_bits, (png_structp png_ptr,
int window_bits));
PNG_EXPORT(73, void, png_set_compression_method, (png_structp png_ptr,
int method));
#endif
#ifdef PNG_WRITE_CUSTOMIZE_ZTXT_COMPRESSION_SUPPORTED
/* Also set zlib parameters for compressing non-IDAT chunks */
PNG_EXPORT(222, void, png_set_text_compression_level,
(png_structp png_ptr, int level));
PNG_EXPORT(223, void, png_set_text_compression_mem_level, (png_structp png_ptr,
int mem_level));
PNG_EXPORT(224, void, png_set_text_compression_strategy, (png_structp png_ptr,
int strategy));
/* If PNG_WRITE_OPTIMIZE_CMF_SUPPORTED is defined, libpng will use a
* smaller value of window_bits if it can do so safely.
*/
PNG_EXPORT(225, void, png_set_text_compression_window_bits, (png_structp
png_ptr, int window_bits));
PNG_EXPORT(226, void, png_set_text_compression_method, (png_structp png_ptr,
int method));
#endif /* PNG_WRITE_CUSTOMIZE_ZTXT_COMPRESSION_SUPPORTED */
/* These next functions are called for input/output, memory, and error
* handling. They are in the file pngrio.c, pngwio.c, and pngerror.c,
* and call standard C I/O routines such as fread(), fwrite(), and
* fprintf(). These functions can be made to use other I/O routines
* at run time for those applications that need to handle I/O in a
* different manner by calling png_set_???_fn(). See libpng-manual.txt for
* more information.
*/
#ifdef PNG_STDIO_SUPPORTED
/* Initialize the input/output for the PNG file to the default functions. */
PNG_EXPORT(74, void, png_init_io, (png_structp png_ptr, png_FILE_p fp));
#endif
/* Replace the (error and abort), and warning functions with user
* supplied functions. If no messages are to be printed you must still
* write and use replacement functions. The replacement error_fn should
* still do a longjmp to the last setjmp location if you are using this
* method of error handling. If error_fn or warning_fn is NULL, the
* default function will be used.
*/
PNG_EXPORT(75, void, png_set_error_fn,
(png_structp png_ptr, png_voidp error_ptr,
png_error_ptr error_fn, png_error_ptr warning_fn));
/* Return the user pointer associated with the error functions */
PNG_EXPORT(76, png_voidp, png_get_error_ptr, (png_const_structp png_ptr));
/* Replace the default data output functions with a user supplied one(s).
* If buffered output is not used, then output_flush_fn can be set to NULL.
* If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time
* output_flush_fn will be ignored (and thus can be NULL).
* It is probably a mistake to use NULL for output_flush_fn if
* write_data_fn is not also NULL unless you have built libpng with
* PNG_WRITE_FLUSH_SUPPORTED undefined, because in this case libpng's
* default flush function, which uses the standard *FILE structure, will
* be used.
*/
PNG_EXPORT(77, void, png_set_write_fn, (png_structp png_ptr, png_voidp io_ptr,
png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn));
/* Replace the default data input function with a user supplied one. */
PNG_EXPORT(78, void, png_set_read_fn, (png_structp png_ptr, png_voidp io_ptr,
png_rw_ptr read_data_fn));
/* Return the user pointer associated with the I/O functions */
PNG_EXPORT(79, png_voidp, png_get_io_ptr, (png_structp png_ptr));
PNG_EXPORT(80, void, png_set_read_status_fn, (png_structp png_ptr,
png_read_status_ptr read_row_fn));
PNG_EXPORT(81, void, png_set_write_status_fn, (png_structp png_ptr,
png_write_status_ptr write_row_fn));
#ifdef PNG_USER_MEM_SUPPORTED
/* Replace the default memory allocation functions with user supplied one(s). */
PNG_EXPORT(82, void, png_set_mem_fn, (png_structp png_ptr, png_voidp mem_ptr,
png_malloc_ptr malloc_fn, png_free_ptr free_fn));
/* Return the user pointer associated with the memory functions */
PNG_EXPORT(83, png_voidp, png_get_mem_ptr, (png_const_structp png_ptr));
#endif
#ifdef PNG_READ_USER_TRANSFORM_SUPPORTED
PNG_EXPORT(84, void, png_set_read_user_transform_fn, (png_structp png_ptr,
png_user_transform_ptr read_user_transform_fn));
#endif
#ifdef PNG_WRITE_USER_TRANSFORM_SUPPORTED
PNG_EXPORT(85, void, png_set_write_user_transform_fn, (png_structp png_ptr,
png_user_transform_ptr write_user_transform_fn));
#endif
#ifdef PNG_USER_TRANSFORM_PTR_SUPPORTED
PNG_EXPORT(86, void, png_set_user_transform_info, (png_structp png_ptr,
png_voidp user_transform_ptr, int user_transform_depth,
int user_transform_channels));
/* Return the user pointer associated with the user transform functions */
PNG_EXPORT(87, png_voidp, png_get_user_transform_ptr,
(png_const_structp png_ptr));
#endif
#ifdef PNG_USER_TRANSFORM_INFO_SUPPORTED
/* Return information about the row currently being processed. Note that these
* APIs do not fail but will return unexpected results if called outside a user
* transform callback. Also note that when transforming an interlaced image the
* row number is the row number within the sub-image of the interlace pass, so
* the value will increase to the height of the sub-image (not the full image)
* then reset to 0 for the next pass.
*
* Use PNG_ROW_FROM_PASS_ROW(row, pass) and PNG_COL_FROM_PASS_COL(col, pass) to
* find the output pixel (x,y) given an interlaced sub-image pixel
* (row,col,pass). (See below for these macros.)
*/
PNG_EXPORT(217, png_uint_32, png_get_current_row_number, (png_const_structp));
PNG_EXPORT(218, png_byte, png_get_current_pass_number, (png_const_structp));
#endif
#ifdef PNG_USER_CHUNKS_SUPPORTED
PNG_EXPORT(88, void, png_set_read_user_chunk_fn, (png_structp png_ptr,
png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn));
PNG_EXPORT(89, png_voidp, png_get_user_chunk_ptr, (png_const_structp png_ptr));
#endif
#ifdef PNG_PROGRESSIVE_READ_SUPPORTED
/* Sets the function callbacks for the push reader, and a pointer to a
* user-defined structure available to the callback functions.
*/
PNG_EXPORT(90, void, png_set_progressive_read_fn, (png_structp png_ptr,
png_voidp progressive_ptr, png_progressive_info_ptr info_fn,
png_progressive_row_ptr row_fn, png_progressive_end_ptr end_fn));
/* Returns the user pointer associated with the push read functions */
PNG_EXPORT(91, png_voidp, png_get_progressive_ptr, (png_const_structp png_ptr));
/* Function to be called when data becomes available */
PNG_EXPORT(92, void, png_process_data,
(png_structp png_ptr, png_infop info_ptr,
png_bytep buffer, png_size_t buffer_size));
/* A function which may be called *only* within png_process_data to stop the
* processing of any more data. The function returns the number of bytes
* remaining, excluding any that libpng has cached internally. A subsequent
* call to png_process_data must supply these bytes again. If the argument
* 'save' is set to true the routine will first save all the pending data and
* will always return 0.
*/
PNG_EXPORT(219, png_size_t, png_process_data_pause, (png_structp, int save));
/* A function which may be called *only* outside (after) a call to
* png_process_data. It returns the number of bytes of data to skip in the
* input. Normally it will return 0, but if it returns a non-zero value the
* application must skip than number of bytes of input data and pass the
* following data to the next call to png_process_data.
*/
PNG_EXPORT(220, png_uint_32, png_process_data_skip, (png_structp));
/* Function that combines rows. 'new_row' is a flag that should come from
* the callback and be non-NULL if anything needs to be done; the library
* stores its own version of the new data internally and ignores the passed
* in value.
*/
PNG_EXPORT(93, void, png_progressive_combine_row, (png_structp png_ptr,
png_bytep old_row, png_const_bytep new_row));
#endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
PNG_EXPORTA(94, png_voidp, png_malloc,
(png_structp png_ptr, png_alloc_size_t size),
PNG_ALLOCATED);
/* Added at libpng version 1.4.0 */
PNG_EXPORTA(95, png_voidp, png_calloc,
(png_structp png_ptr, png_alloc_size_t size),
PNG_ALLOCATED);
/* Added at libpng version 1.2.4 */
PNG_EXPORTA(96, png_voidp, png_malloc_warn, (png_structp png_ptr,
png_alloc_size_t size), PNG_ALLOCATED);
/* Frees a pointer allocated by png_malloc() */
PNG_EXPORT(97, void, png_free, (png_structp png_ptr, png_voidp ptr));
/* Free data that was allocated internally */
PNG_EXPORT(98, void, png_free_data,
(png_structp png_ptr, png_infop info_ptr, png_uint_32 free_me, int num));
/* Reassign responsibility for freeing existing data, whether allocated
* by libpng or by the application */
PNG_EXPORT(99, void, png_data_freer,
(png_structp png_ptr, png_infop info_ptr, int freer, png_uint_32 mask));
/* Assignments for png_data_freer */
#define PNG_DESTROY_WILL_FREE_DATA 1
#define PNG_SET_WILL_FREE_DATA 1
#define PNG_USER_WILL_FREE_DATA 2
/* Flags for png_ptr->free_me and info_ptr->free_me */
#define PNG_FREE_HIST 0x0008
#define PNG_FREE_ICCP 0x0010
#define PNG_FREE_SPLT 0x0020
#define PNG_FREE_ROWS 0x0040
#define PNG_FREE_PCAL 0x0080
#define PNG_FREE_SCAL 0x0100
#define PNG_FREE_UNKN 0x0200
#define PNG_FREE_LIST 0x0400
#define PNG_FREE_PLTE 0x1000
#define PNG_FREE_TRNS 0x2000
#define PNG_FREE_TEXT 0x4000
#define PNG_FREE_ALL 0x7fff
#define PNG_FREE_MUL 0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */
#ifdef PNG_USER_MEM_SUPPORTED
PNG_EXPORTA(100, png_voidp, png_malloc_default, (png_structp png_ptr,
png_alloc_size_t size), PNG_ALLOCATED);
PNG_EXPORT(101, void, png_free_default, (png_structp png_ptr, png_voidp ptr));
#endif
#ifdef PNG_ERROR_TEXT_SUPPORTED
/* Fatal error in PNG image of libpng - can't continue */
PNG_EXPORTA(102, void, png_error,
(png_structp png_ptr, png_const_charp error_message),
PNG_NORETURN);
/* The same, but the chunk name is prepended to the error string. */
PNG_EXPORTA(103, void, png_chunk_error, (png_structp png_ptr,
png_const_charp error_message), PNG_NORETURN);
#else
/* Fatal error in PNG image of libpng - can't continue */
PNG_EXPORTA(104, void, png_err, (png_structp png_ptr), PNG_NORETURN);
#endif
#ifdef PNG_WARNINGS_SUPPORTED
/* Non-fatal error in libpng. Can continue, but may have a problem. */
PNG_EXPORT(105, void, png_warning, (png_structp png_ptr,
png_const_charp warning_message));
/* Non-fatal error in libpng, chunk name is prepended to message. */
PNG_EXPORT(106, void, png_chunk_warning, (png_structp png_ptr,
png_const_charp warning_message));
#endif
#ifdef PNG_BENIGN_ERRORS_SUPPORTED
/* Benign error in libpng. Can continue, but may have a problem.
* User can choose whether to handle as a fatal error or as a warning. */
# undef png_benign_error
PNG_EXPORT(107, void, png_benign_error, (png_structp png_ptr,
png_const_charp warning_message));
/* Same, chunk name is prepended to message. */
# undef png_chunk_benign_error
PNG_EXPORT(108, void, png_chunk_benign_error, (png_structp png_ptr,
png_const_charp warning_message));
PNG_EXPORT(109, void, png_set_benign_errors,
(png_structp png_ptr, int allowed));
#else
# ifdef PNG_ALLOW_BENIGN_ERRORS
# define png_benign_error png_warning
# define png_chunk_benign_error png_chunk_warning
# else
# define png_benign_error png_error
# define png_chunk_benign_error png_chunk_error
# endif
#endif
/* The png_set_<chunk> functions are for storing values in the png_info_struct.
* Similarly, the png_get_<chunk> calls are used to read values from the
* png_info_struct, either storing the parameters in the passed variables, or
* setting pointers into the png_info_struct where the data is stored. The
* png_get_<chunk> functions return a non-zero value if the data was available
* in info_ptr, or return zero and do not change any of the parameters if the
* data was not available.
*
* These functions should be used instead of directly accessing png_info
* to avoid problems with future changes in the size and internal layout of
* png_info_struct.
*/
/* Returns "flag" if chunk data is valid in info_ptr. */
PNG_EXPORT(110, png_uint_32, png_get_valid,
(png_const_structp png_ptr, png_const_infop info_ptr,
png_uint_32 flag));
/* Returns number of bytes needed to hold a transformed row. */
PNG_EXPORT(111, png_size_t, png_get_rowbytes, (png_const_structp png_ptr,
png_const_infop info_ptr));
#ifdef PNG_INFO_IMAGE_SUPPORTED
/* Returns row_pointers, which is an array of pointers to scanlines that was
* returned from png_read_png().
*/
PNG_EXPORT(112, png_bytepp, png_get_rows,
(png_const_structp png_ptr, png_const_infop info_ptr));
/* Set row_pointers, which is an array of pointers to scanlines for use
* by png_write_png().
*/
PNG_EXPORT(113, void, png_set_rows, (png_structp png_ptr,
png_infop info_ptr, png_bytepp row_pointers));
#endif
/* Returns number of color channels in image. */
PNG_EXPORT(114, png_byte, png_get_channels,
(png_const_structp png_ptr, png_const_infop info_ptr));
#ifdef PNG_EASY_ACCESS_SUPPORTED
/* Returns image width in pixels. */
PNG_EXPORT(115, png_uint_32, png_get_image_width, (png_const_structp png_ptr,
png_const_infop info_ptr));
/* Returns image height in pixels. */
PNG_EXPORT(116, png_uint_32, png_get_image_height, (png_const_structp png_ptr,
png_const_infop info_ptr));
/* Returns image bit_depth. */
PNG_EXPORT(117, png_byte, png_get_bit_depth,
(png_const_structp png_ptr, png_const_infop info_ptr));
/* Returns image color_type. */
PNG_EXPORT(118, png_byte, png_get_color_type, (png_const_structp png_ptr,
png_const_infop info_ptr));
/* Returns image filter_type. */
PNG_EXPORT(119, png_byte, png_get_filter_type, (png_const_structp png_ptr,
png_const_infop info_ptr));
/* Returns image interlace_type. */
PNG_EXPORT(120, png_byte, png_get_interlace_type, (png_const_structp png_ptr,
png_const_infop info_ptr));
/* Returns image compression_type. */
PNG_EXPORT(121, png_byte, png_get_compression_type, (png_const_structp png_ptr,
png_const_infop info_ptr));
/* Returns image resolution in pixels per meter, from pHYs chunk data. */
PNG_EXPORT(122, png_uint_32, png_get_pixels_per_meter,
(png_const_structp png_ptr, png_const_infop info_ptr));
PNG_EXPORT(123, png_uint_32, png_get_x_pixels_per_meter,
(png_const_structp png_ptr, png_const_infop info_ptr));
PNG_EXPORT(124, png_uint_32, png_get_y_pixels_per_meter,
(png_const_structp png_ptr, png_const_infop info_ptr));
/* Returns pixel aspect ratio, computed from pHYs chunk data. */
PNG_FP_EXPORT(125, float, png_get_pixel_aspect_ratio,
(png_const_structp png_ptr, png_const_infop info_ptr));
PNG_FIXED_EXPORT(210, png_fixed_point, png_get_pixel_aspect_ratio_fixed,
(png_const_structp png_ptr, png_const_infop info_ptr));
/* Returns image x, y offset in pixels or microns, from oFFs chunk data. */
PNG_EXPORT(126, png_int_32, png_get_x_offset_pixels,
(png_const_structp png_ptr, png_const_infop info_ptr));
PNG_EXPORT(127, png_int_32, png_get_y_offset_pixels,
(png_const_structp png_ptr, png_const_infop info_ptr));
PNG_EXPORT(128, png_int_32, png_get_x_offset_microns,
(png_const_structp png_ptr, png_const_infop info_ptr));
PNG_EXPORT(129, png_int_32, png_get_y_offset_microns,
(png_const_structp png_ptr, png_const_infop info_ptr));
#endif /* PNG_EASY_ACCESS_SUPPORTED */
/* Returns pointer to signature string read from PNG header */
PNG_EXPORT(130, png_const_bytep, png_get_signature,
(png_const_structp png_ptr, png_infop info_ptr));
#ifdef PNG_bKGD_SUPPORTED
PNG_EXPORT(131, png_uint_32, png_get_bKGD,
(png_const_structp png_ptr, png_infop info_ptr,
png_color_16p *background));
#endif
#ifdef PNG_bKGD_SUPPORTED
PNG_EXPORT(132, void, png_set_bKGD, (png_structp png_ptr, png_infop info_ptr,
png_const_color_16p background));
#endif
#ifdef PNG_cHRM_SUPPORTED
PNG_FP_EXPORT(133, png_uint_32, png_get_cHRM, (png_const_structp png_ptr,
png_const_infop info_ptr, double *white_x, double *white_y, double *red_x,
double *red_y, double *green_x, double *green_y, double *blue_x,
double *blue_y));
PNG_FP_EXPORT(230, png_uint_32, png_get_cHRM_XYZ, (png_structp png_ptr,
png_const_infop info_ptr, double *red_X, double *red_Y, double *red_Z,
double *green_X, double *green_Y, double *green_Z, double *blue_X,
double *blue_Y, double *blue_Z));
#ifdef PNG_FIXED_POINT_SUPPORTED /* Otherwise not implemented */
PNG_FIXED_EXPORT(134, png_uint_32, png_get_cHRM_fixed,
(png_const_structp png_ptr,
png_const_infop info_ptr, png_fixed_point *int_white_x,
png_fixed_point *int_white_y, png_fixed_point *int_red_x,
png_fixed_point *int_red_y, png_fixed_point *int_green_x,
png_fixed_point *int_green_y, png_fixed_point *int_blue_x,
png_fixed_point *int_blue_y));
#endif
PNG_FIXED_EXPORT(231, png_uint_32, png_get_cHRM_XYZ_fixed,
(png_structp png_ptr, png_const_infop info_ptr,
png_fixed_point *int_red_X, png_fixed_point *int_red_Y,
png_fixed_point *int_red_Z, png_fixed_point *int_green_X,
png_fixed_point *int_green_Y, png_fixed_point *int_green_Z,
png_fixed_point *int_blue_X, png_fixed_point *int_blue_Y,
png_fixed_point *int_blue_Z));
#endif
#ifdef PNG_cHRM_SUPPORTED
PNG_FP_EXPORT(135, void, png_set_cHRM,
(png_structp png_ptr, png_infop info_ptr,
double white_x, double white_y, double red_x, double red_y, double green_x,
double green_y, double blue_x, double blue_y));
PNG_FP_EXPORT(232, void, png_set_cHRM_XYZ, (png_structp png_ptr,
png_infop info_ptr, double red_X, double red_Y, double red_Z,
double green_X, double green_Y, double green_Z, double blue_X,
double blue_Y, double blue_Z));
PNG_FIXED_EXPORT(136, void, png_set_cHRM_fixed, (png_structp png_ptr,
png_infop info_ptr, png_fixed_point int_white_x,
png_fixed_point int_white_y, png_fixed_point int_red_x,
png_fixed_point int_red_y, png_fixed_point int_green_x,
png_fixed_point int_green_y, png_fixed_point int_blue_x,
png_fixed_point int_blue_y));
PNG_FIXED_EXPORT(233, void, png_set_cHRM_XYZ_fixed, (png_structp png_ptr,
png_infop info_ptr, png_fixed_point int_red_X, png_fixed_point int_red_Y,
png_fixed_point int_red_Z, png_fixed_point int_green_X,
png_fixed_point int_green_Y, png_fixed_point int_green_Z,
png_fixed_point int_blue_X, png_fixed_point int_blue_Y,
png_fixed_point int_blue_Z));
#endif
#ifdef PNG_gAMA_SUPPORTED
PNG_FP_EXPORT(137, png_uint_32, png_get_gAMA,
(png_const_structp png_ptr, png_const_infop info_ptr,
double *file_gamma));
PNG_FIXED_EXPORT(138, png_uint_32, png_get_gAMA_fixed,
(png_const_structp png_ptr, png_const_infop info_ptr,
png_fixed_point *int_file_gamma));
#endif
#ifdef PNG_gAMA_SUPPORTED
PNG_FP_EXPORT(139, void, png_set_gAMA, (png_structp png_ptr,
png_infop info_ptr, double file_gamma));
PNG_FIXED_EXPORT(140, void, png_set_gAMA_fixed, (png_structp png_ptr,
png_infop info_ptr, png_fixed_point int_file_gamma));
#endif
#ifdef PNG_hIST_SUPPORTED
PNG_EXPORT(141, png_uint_32, png_get_hIST,
(png_const_structp png_ptr, png_const_infop info_ptr,
png_uint_16p *hist));
#endif
#ifdef PNG_hIST_SUPPORTED
PNG_EXPORT(142, void, png_set_hIST, (png_structp png_ptr,
png_infop info_ptr, png_const_uint_16p hist));
#endif
PNG_EXPORT(143, png_uint_32, png_get_IHDR,
(png_structp png_ptr, png_infop info_ptr,
png_uint_32 *width, png_uint_32 *height, int *bit_depth, int *color_type,
int *interlace_method, int *compression_method, int *filter_method));
PNG_EXPORT(144, void, png_set_IHDR,
(png_structp png_ptr, png_infop info_ptr,
png_uint_32 width, png_uint_32 height, int bit_depth, int color_type,
int interlace_method, int compression_method, int filter_method));
#ifdef PNG_oFFs_SUPPORTED
PNG_EXPORT(145, png_uint_32, png_get_oFFs,
(png_const_structp png_ptr, png_const_infop info_ptr,
png_int_32 *offset_x, png_int_32 *offset_y, int *unit_type));
#endif
#ifdef PNG_oFFs_SUPPORTED
PNG_EXPORT(146, void, png_set_oFFs,
(png_structp png_ptr, png_infop info_ptr,
png_int_32 offset_x, png_int_32 offset_y, int unit_type));
#endif
#ifdef PNG_pCAL_SUPPORTED
PNG_EXPORT(147, png_uint_32, png_get_pCAL,
(png_const_structp png_ptr, png_const_infop info_ptr,
png_charp *purpose, png_int_32 *X0, png_int_32 *X1, int *type,
int *nparams,
png_charp *units, png_charpp *params));
#endif
#ifdef PNG_pCAL_SUPPORTED
PNG_EXPORT(148, void, png_set_pCAL, (png_structp png_ptr,
png_infop info_ptr,
png_const_charp purpose, png_int_32 X0, png_int_32 X1, int type,
int nparams, png_const_charp units, png_charpp params));
#endif
#ifdef PNG_pHYs_SUPPORTED
PNG_EXPORT(149, png_uint_32, png_get_pHYs,
(png_const_structp png_ptr, png_const_infop info_ptr,
png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
#endif
#ifdef PNG_pHYs_SUPPORTED
PNG_EXPORT(150, void, png_set_pHYs,
(png_structp png_ptr, png_infop info_ptr,
png_uint_32 res_x, png_uint_32 res_y, int unit_type));
#endif
PNG_EXPORT(151, png_uint_32, png_get_PLTE,
(png_const_structp png_ptr, png_const_infop info_ptr,
png_colorp *palette, int *num_palette));
PNG_EXPORT(152, void, png_set_PLTE,
(png_structp png_ptr, png_infop info_ptr,
png_const_colorp palette, int num_palette));
#ifdef PNG_sBIT_SUPPORTED
PNG_EXPORT(153, png_uint_32, png_get_sBIT,
(png_const_structp png_ptr, png_infop info_ptr,
png_color_8p *sig_bit));
#endif
#ifdef PNG_sBIT_SUPPORTED
PNG_EXPORT(154, void, png_set_sBIT,
(png_structp png_ptr, png_infop info_ptr, png_const_color_8p sig_bit));
#endif
#ifdef PNG_sRGB_SUPPORTED
PNG_EXPORT(155, png_uint_32, png_get_sRGB, (png_const_structp png_ptr,
png_const_infop info_ptr, int *file_srgb_intent));
#endif
#ifdef PNG_sRGB_SUPPORTED
PNG_EXPORT(156, void, png_set_sRGB,
(png_structp png_ptr, png_infop info_ptr, int srgb_intent));
PNG_EXPORT(157, void, png_set_sRGB_gAMA_and_cHRM, (png_structp png_ptr,
png_infop info_ptr, int srgb_intent));
#endif
#ifdef PNG_iCCP_SUPPORTED
PNG_EXPORT(158, png_uint_32, png_get_iCCP,
(png_const_structp png_ptr, png_const_infop info_ptr,
png_charpp name, int *compression_type, png_bytepp profile,
png_uint_32 *proflen));
#endif
#ifdef PNG_iCCP_SUPPORTED
PNG_EXPORT(159, void, png_set_iCCP,
(png_structp png_ptr, png_infop info_ptr,
png_const_charp name, int compression_type, png_const_bytep profile,
png_uint_32 proflen));
#endif
#ifdef PNG_sPLT_SUPPORTED
PNG_EXPORT(160, png_uint_32, png_get_sPLT,
(png_const_structp png_ptr, png_const_infop info_ptr,
png_sPLT_tpp entries));
#endif
#ifdef PNG_sPLT_SUPPORTED
PNG_EXPORT(161, void, png_set_sPLT,
(png_structp png_ptr, png_infop info_ptr,
png_const_sPLT_tp entries, int nentries));
#endif
#ifdef PNG_TEXT_SUPPORTED
/* png_get_text also returns the number of text chunks in *num_text */
PNG_EXPORT(162, png_uint_32, png_get_text,
(png_const_structp png_ptr, png_const_infop info_ptr,
png_textp *text_ptr, int *num_text));
#endif
/* Note while png_set_text() will accept a structure whose text,
* language, and translated keywords are NULL pointers, the structure
* returned by png_get_text will always contain regular
* zero-terminated C strings. They might be empty strings but
* they will never be NULL pointers.
*/
#ifdef PNG_TEXT_SUPPORTED
PNG_EXPORT(163, void, png_set_text,
(png_structp png_ptr, png_infop info_ptr,
png_const_textp text_ptr, int num_text));
#endif
#ifdef PNG_tIME_SUPPORTED
PNG_EXPORT(164, png_uint_32, png_get_tIME,
(png_const_structp png_ptr, png_infop info_ptr, png_timep *mod_time));
#endif
#ifdef PNG_tIME_SUPPORTED
PNG_EXPORT(165, void, png_set_tIME,
(png_structp png_ptr, png_infop info_ptr, png_const_timep mod_time));
#endif
#ifdef PNG_tRNS_SUPPORTED
PNG_EXPORT(166, png_uint_32, png_get_tRNS,
(png_const_structp png_ptr, png_infop info_ptr,
png_bytep *trans_alpha, int *num_trans, png_color_16p *trans_color));
#endif
#ifdef PNG_tRNS_SUPPORTED
PNG_EXPORT(167, void, png_set_tRNS,
(png_structp png_ptr, png_infop info_ptr,
png_const_bytep trans_alpha, int num_trans,
png_const_color_16p trans_color));
#endif
#ifdef PNG_sCAL_SUPPORTED
PNG_FP_EXPORT(168, png_uint_32, png_get_sCAL,
(png_const_structp png_ptr, png_const_infop info_ptr,
int *unit, double *width, double *height));
#ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED
/* NOTE: this API is currently implemented using floating point arithmetic,
* consequently it can only be used on systems with floating point support.
* In any case the range of values supported by png_fixed_point is small and it
* is highly recommended that png_get_sCAL_s be used instead.
*/
PNG_FIXED_EXPORT(214, png_uint_32, png_get_sCAL_fixed,
(png_structp png_ptr, png_const_infop info_ptr, int *unit,
png_fixed_point *width,
png_fixed_point *height));
#endif
PNG_EXPORT(169, png_uint_32, png_get_sCAL_s,
(png_const_structp png_ptr, png_const_infop info_ptr,
int *unit, png_charpp swidth, png_charpp sheight));
PNG_FP_EXPORT(170, void, png_set_sCAL,
(png_structp png_ptr, png_infop info_ptr,
int unit, double width, double height));
PNG_FIXED_EXPORT(213, void, png_set_sCAL_fixed, (png_structp png_ptr,
png_infop info_ptr, int unit, png_fixed_point width,
png_fixed_point height));
PNG_EXPORT(171, void, png_set_sCAL_s,
(png_structp png_ptr, png_infop info_ptr,
int unit, png_const_charp swidth, png_const_charp sheight));
#endif /* PNG_sCAL_SUPPORTED */
#ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
/* Provide a list of chunks and how they are to be handled, if the built-in
handling or default unknown chunk handling is not desired. Any chunks not
listed will be handled in the default manner. The IHDR and IEND chunks
must not be listed.
keep = 0: follow default behavior
= 1: do not keep
= 2: keep only if safe-to-copy
= 3: keep even if unsafe-to-copy
*/
PNG_EXPORT(172, void, png_set_keep_unknown_chunks,
(png_structp png_ptr, int keep,
png_const_bytep chunk_list, int num_chunks));
PNG_EXPORT(173, int, png_handle_as_unknown, (png_structp png_ptr,
png_const_bytep chunk_name));
#endif
#ifdef PNG_UNKNOWN_CHUNKS_SUPPORTED
PNG_EXPORT(174, void, png_set_unknown_chunks, (png_structp png_ptr,
png_infop info_ptr, png_const_unknown_chunkp unknowns,
int num_unknowns));
PNG_EXPORT(175, void, png_set_unknown_chunk_location,
(png_structp png_ptr, png_infop info_ptr, int chunk, int location));
PNG_EXPORT(176, int, png_get_unknown_chunks, (png_const_structp png_ptr,
png_const_infop info_ptr, png_unknown_chunkpp entries));
#endif
/* Png_free_data() will turn off the "valid" flag for anything it frees.
* If you need to turn it off for a chunk that your application has freed,
* you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK);
*/
PNG_EXPORT(177, void, png_set_invalid,
(png_structp png_ptr, png_infop info_ptr, int mask));
#ifdef PNG_INFO_IMAGE_SUPPORTED
/* The "params" pointer is currently not used and is for future expansion. */
PNG_EXPORT(178, void, png_read_png, (png_structp png_ptr, png_infop info_ptr,
int transforms, png_voidp params));
PNG_EXPORT(179, void, png_write_png, (png_structp png_ptr, png_infop info_ptr,
int transforms, png_voidp params));
#endif
PNG_EXPORT(180, png_const_charp, png_get_copyright,
(png_const_structp png_ptr));
PNG_EXPORT(181, png_const_charp, png_get_header_ver,
(png_const_structp png_ptr));
PNG_EXPORT(182, png_const_charp, png_get_header_version,
(png_const_structp png_ptr));
PNG_EXPORT(183, png_const_charp, png_get_libpng_ver,
(png_const_structp png_ptr));
#ifdef PNG_MNG_FEATURES_SUPPORTED
PNG_EXPORT(184, png_uint_32, png_permit_mng_features, (png_structp png_ptr,
png_uint_32 mng_features_permitted));
#endif
/* For use in png_set_keep_unknown, added to version 1.2.6 */
#define PNG_HANDLE_CHUNK_AS_DEFAULT 0
#define PNG_HANDLE_CHUNK_NEVER 1
#define PNG_HANDLE_CHUNK_IF_SAFE 2
#define PNG_HANDLE_CHUNK_ALWAYS 3
/* Strip the prepended error numbers ("#nnn ") from error and warning
* messages before passing them to the error or warning handler.
*/
#ifdef PNG_ERROR_NUMBERS_SUPPORTED
PNG_EXPORT(185, void, png_set_strip_error_numbers,
(png_structp png_ptr,
png_uint_32 strip_mode));
#endif
/* Added in libpng-1.2.6 */
#ifdef PNG_SET_USER_LIMITS_SUPPORTED
PNG_EXPORT(186, void, png_set_user_limits, (png_structp png_ptr,
png_uint_32 user_width_max, png_uint_32 user_height_max));
PNG_EXPORT(187, png_uint_32, png_get_user_width_max,
(png_const_structp png_ptr));
PNG_EXPORT(188, png_uint_32, png_get_user_height_max,
(png_const_structp png_ptr));
/* Added in libpng-1.4.0 */
PNG_EXPORT(189, void, png_set_chunk_cache_max, (png_structp png_ptr,
png_uint_32 user_chunk_cache_max));
PNG_EXPORT(190, png_uint_32, png_get_chunk_cache_max,
(png_const_structp png_ptr));
/* Added in libpng-1.4.1 */
PNG_EXPORT(191, void, png_set_chunk_malloc_max, (png_structp png_ptr,
png_alloc_size_t user_chunk_cache_max));
PNG_EXPORT(192, png_alloc_size_t, png_get_chunk_malloc_max,
(png_const_structp png_ptr));
#endif
#if defined(PNG_INCH_CONVERSIONS_SUPPORTED)
PNG_EXPORT(193, png_uint_32, png_get_pixels_per_inch,
(png_const_structp png_ptr, png_const_infop info_ptr));
PNG_EXPORT(194, png_uint_32, png_get_x_pixels_per_inch,
(png_const_structp png_ptr, png_const_infop info_ptr));
PNG_EXPORT(195, png_uint_32, png_get_y_pixels_per_inch,
(png_const_structp png_ptr, png_const_infop info_ptr));
PNG_FP_EXPORT(196, float, png_get_x_offset_inches,
(png_const_structp png_ptr, png_const_infop info_ptr));
#ifdef PNG_FIXED_POINT_SUPPORTED /* otherwise not implemented. */
PNG_FIXED_EXPORT(211, png_fixed_point, png_get_x_offset_inches_fixed,
(png_structp png_ptr, png_const_infop info_ptr));
#endif
PNG_FP_EXPORT(197, float, png_get_y_offset_inches, (png_const_structp png_ptr,
png_const_infop info_ptr));
#ifdef PNG_FIXED_POINT_SUPPORTED /* otherwise not implemented. */
PNG_FIXED_EXPORT(212, png_fixed_point, png_get_y_offset_inches_fixed,
(png_structp png_ptr, png_const_infop info_ptr));
#endif
# ifdef PNG_pHYs_SUPPORTED
PNG_EXPORT(198, png_uint_32, png_get_pHYs_dpi, (png_const_structp png_ptr,
png_const_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y,
int *unit_type));
# endif /* PNG_pHYs_SUPPORTED */
#endif /* PNG_INCH_CONVERSIONS_SUPPORTED */
/* Added in libpng-1.4.0 */
#ifdef PNG_IO_STATE_SUPPORTED
PNG_EXPORT(199, png_uint_32, png_get_io_state, (png_structp png_ptr));
PNG_EXPORTA(200, png_const_bytep, png_get_io_chunk_name,
(png_structp png_ptr), PNG_DEPRECATED);
PNG_EXPORT(216, png_uint_32, png_get_io_chunk_type,
(png_const_structp png_ptr));
/* The flags returned by png_get_io_state() are the following: */
# define PNG_IO_NONE 0x0000 /* no I/O at this moment */
# define PNG_IO_READING 0x0001 /* currently reading */
# define PNG_IO_WRITING 0x0002 /* currently writing */
# define PNG_IO_SIGNATURE 0x0010 /* currently at the file signature */
# define PNG_IO_CHUNK_HDR 0x0020 /* currently at the chunk header */
# define PNG_IO_CHUNK_DATA 0x0040 /* currently at the chunk data */
# define PNG_IO_CHUNK_CRC 0x0080 /* currently at the chunk crc */
# define PNG_IO_MASK_OP 0x000f /* current operation: reading/writing */
# define PNG_IO_MASK_LOC 0x00f0 /* current location: sig/hdr/data/crc */
#endif /* ?PNG_IO_STATE_SUPPORTED */
/* Interlace support. The following macros are always defined so that if
* libpng interlace handling is turned off the macros may be used to handle
* interlaced images within the application.
*/
#define PNG_INTERLACE_ADAM7_PASSES 7
/* Two macros to return the first row and first column of the original,
* full, image which appears in a given pass. 'pass' is in the range 0
* to 6 and the result is in the range 0 to 7.
*/
#define PNG_PASS_START_ROW(pass) (((1U&~(pass))<<(3-((pass)>>1)))&7)
#define PNG_PASS_START_COL(pass) (((1U& (pass))<<(3-(((pass)+1)>>1)))&7)
/* Two macros to help evaluate the number of rows or columns in each
* pass. This is expressed as a shift - effectively log2 of the number or
* rows or columns in each 8x8 tile of the original image.
*/
#define PNG_PASS_ROW_SHIFT(pass) ((pass)>2?(8-(pass))>>1:3)
#define PNG_PASS_COL_SHIFT(pass) ((pass)>1?(7-(pass))>>1:3)
/* Hence two macros to determine the number of rows or columns in a given
* pass of an image given its height or width. In fact these macros may
* return non-zero even though the sub-image is empty, because the other
* dimension may be empty for a small image.
*/
#define PNG_PASS_ROWS(height, pass) (((height)+(((1<<PNG_PASS_ROW_SHIFT(pass))\
-1)-PNG_PASS_START_ROW(pass)))>>PNG_PASS_ROW_SHIFT(pass))
#define PNG_PASS_COLS(width, pass) (((width)+(((1<<PNG_PASS_COL_SHIFT(pass))\
-1)-PNG_PASS_START_COL(pass)))>>PNG_PASS_COL_SHIFT(pass))
/* For the reader row callbacks (both progressive and sequential) it is
* necessary to find the row in the output image given a row in an interlaced
* image, so two more macros:
*/
#define PNG_ROW_FROM_PASS_ROW(yIn, pass) \
(((yIn)<<PNG_PASS_ROW_SHIFT(pass))+PNG_PASS_START_ROW(pass))
#define PNG_COL_FROM_PASS_COL(xIn, pass) \
(((xIn)<<PNG_PASS_COL_SHIFT(pass))+PNG_PASS_START_COL(pass))
/* Two macros which return a boolean (0 or 1) saying whether the given row
* or column is in a particular pass. These use a common utility macro that
* returns a mask for a given pass - the offset 'off' selects the row or
* column version. The mask has the appropriate bit set for each column in
* the tile.
*/
#define PNG_PASS_MASK(pass,off) ( \
((0x110145AFU>>(((7-(off))-(pass))<<2)) & 0xFU) | \
((0x01145AF0U>>(((7-(off))-(pass))<<2)) & 0xF0U))
#define PNG_ROW_IN_INTERLACE_PASS(y, pass) \
((PNG_PASS_MASK(pass,0) >> ((y)&7)) & 1)
#define PNG_COL_IN_INTERLACE_PASS(x, pass) \
((PNG_PASS_MASK(pass,1) >> ((x)&7)) & 1)
#ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED
/* With these routines we avoid an integer divide, which will be slower on
* most machines. However, it does take more operations than the corresponding
* divide method, so it may be slower on a few RISC systems. There are two
* shifts (by 8 or 16 bits) and an addition, versus a single integer divide.
*
* Note that the rounding factors are NOT supposed to be the same! 128 and
* 32768 are correct for the NODIV code; 127 and 32767 are correct for the
* standard method.
*
* [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ]
*/
/* fg and bg should be in `gamma 1.0' space; alpha is the opacity */
# define png_composite(composite, fg, alpha, bg) \
{ png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) \
* (png_uint_16)(alpha) \
+ (png_uint_16)(bg)*(png_uint_16)(255 \
- (png_uint_16)(alpha)) + 128); \
(composite) = (png_byte)((temp + (temp >> 8)) >> 8); }
# define png_composite_16(composite, fg, alpha, bg) \
{ png_uint_32 temp = (png_uint_32)((png_uint_32)(fg) \
* (png_uint_32)(alpha) \
+ (png_uint_32)(bg)*(65535 \
- (png_uint_32)(alpha)) + 32768); \
(composite) = (png_uint_16)((temp + (temp >> 16)) >> 16); }
#else /* Standard method using integer division */
# define png_composite(composite, fg, alpha, bg) \
(composite) = (png_byte)(((png_uint_16)(fg) * (png_uint_16)(alpha) + \
(png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) + \
127) / 255)
# define png_composite_16(composite, fg, alpha, bg) \
(composite) = (png_uint_16)(((png_uint_32)(fg) * (png_uint_32)(alpha) + \
(png_uint_32)(bg)*(png_uint_32)(65535 - (png_uint_32)(alpha)) + \
32767) / 65535)
#endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */
#ifdef PNG_READ_INT_FUNCTIONS_SUPPORTED
PNG_EXPORT(201, png_uint_32, png_get_uint_32, (png_const_bytep buf));
PNG_EXPORT(202, png_uint_16, png_get_uint_16, (png_const_bytep buf));
PNG_EXPORT(203, png_int_32, png_get_int_32, (png_const_bytep buf));
#endif
PNG_EXPORT(204, png_uint_32, png_get_uint_31, (png_structp png_ptr,
png_const_bytep buf));
/* No png_get_int_16 -- may be added if there's a real need for it. */
/* Place a 32-bit number into a buffer in PNG byte order (big-endian). */
#ifdef PNG_WRITE_INT_FUNCTIONS_SUPPORTED
PNG_EXPORT(205, void, png_save_uint_32, (png_bytep buf, png_uint_32 i));
#endif
#ifdef PNG_SAVE_INT_32_SUPPORTED
PNG_EXPORT(206, void, png_save_int_32, (png_bytep buf, png_int_32 i));
#endif
/* Place a 16-bit number into a buffer in PNG byte order.
* The parameter is declared unsigned int, not png_uint_16,
* just to avoid potential problems on pre-ANSI C compilers.
*/
#ifdef PNG_WRITE_INT_FUNCTIONS_SUPPORTED
PNG_EXPORT(207, void, png_save_uint_16, (png_bytep buf, unsigned int i));
/* No png_save_int_16 -- may be added if there's a real need for it. */
#endif
#ifdef PNG_USE_READ_MACROS
/* Inline macros to do direct reads of bytes from the input buffer.
* The png_get_int_32() routine assumes we are using two's complement
* format for negative values, which is almost certainly true.
*/
# define png_get_uint_32(buf) \
(((png_uint_32)(*(buf)) << 24) + \
((png_uint_32)(*((buf) + 1)) << 16) + \
((png_uint_32)(*((buf) + 2)) << 8) + \
((png_uint_32)(*((buf) + 3))))
/* From libpng-1.4.0 until 1.4.4, the png_get_uint_16 macro (but not the
* function) incorrectly returned a value of type png_uint_32.
*/
# define png_get_uint_16(buf) \
((png_uint_16) \
(((unsigned int)(*(buf)) << 8) + \
((unsigned int)(*((buf) + 1)))))
# define png_get_int_32(buf) \
((png_int_32)((*(buf) & 0x80) \
? -((png_int_32)((png_get_uint_32(buf) ^ 0xffffffffL) + 1)) \
: (png_int_32)png_get_uint_32(buf)))
#endif
/* Maintainer: Put new public prototypes here ^, in libpng.3, and project
* defs
*/
/* The last ordinal number (this is the *last* one already used; the next
* one to use is one more than this.) Maintainer, remember to add an entry to
* scripts/symbols.def as well.
*/
#ifdef PNG_EXPORT_LAST_ORDINAL
PNG_EXPORT_LAST_ORDINAL(233);
#endif
#ifdef __cplusplus
}
#endif
#endif /* PNG_VERSION_INFO_ONLY */
/* Do not put anything past this line */
#endif /* PNG_H */
| saniv/symta | ffi/gfx/deps/png/include/png.h | C | mit | 112,641 |
// This file is automatically generated.
package adila.db;
/*
* Hisense L695
*
* DEVICE: HS8929QC
* MODEL: HS-L695
*/
final class hs8929qc_hs2dl695 {
public static final String DATA = "Hisense|L695|";
}
| karim/adila | database/src/main/java/adila/db/hs8929qc_hs2dl695.java | Java | mit | 214 |
# -*- encoding: utf-8 -*-
"""Defines all utility methods."""
def isStudentAbleToVote(student):
if student != None and not student.vote:
return True
return False
def isStudentAbleToSelected(student):
if student != None and student.is_candidate:
return True
return False
def isTeacherAbleToVote(teacher):
if teacher != None and not teacher.vote:
return True
return False
def isTeacherAbleToSelected(teacher):
if teacher != None and teacher.is_candidate:
return True
return False | dairdr/voteapp | voteapp/apps/vote/utils.py | Python | mit | 496 |
###Release 1:
######1. What does puts do?
Puts stands for put-string. It prints the output of our code to the console and returns nil on a new line.
######2. What's an integer? What's a float?
An integer is a number without decimal points(eg. 1, 2 or 65). A float is a number with decimal points after it(eg. 2.1, .99, 65.56)
######3. What is the difference between float and integer division? How would you explain the difference to someone who doesn't know anything about programming?
Float division is the division we're used to. In float division, you can get fraction answers. For example 7/2 = 3.5 in float division.
Integer division doesn't use decimals, it seems strange at first, but it's actually much more applicable to real life. For example if I have $100 I want to buy as many $15 CDs as I can, I would ask myself: What's 100/15? Float division would tell us that 100/15 is 6.666, but I can't buy .666 of a CD. 100/15 = 6 in integer division because it deals with whole numbers only.
###Release 2:
Here's some fun Ruby:
```
puts 24 * 365 # hours in a year
puts 60 * 24 * 365 * 10 # minutes in a decade
puts 60 * 60 * 24 * 365 * 25 + 60 * 60 * 24 * 7 # my age in seconds
```
###Release 5(Excercises):
[4.2.1 Defining Variables](https://github.com/gaw1990/phase-0/blob/master/week-4/defining-variables.rb)
[4.2.2 Simple String Methods](https://github.com/gaw1990/phase-0/blob/master/week-4/simple-string.rb)
[4.2.3 Local Variables and Basic Arithmetical Operations](https://github.com/gaw1990/phase-0/blob/master/week-4/basic-math.rb)
###Release 7(Reflection):
######1. How does Ruby handle addition, subtraction, multiplication, and division of numbers?
Ruby handles mathmatical operations using symbols. I'm not really sure what this question is asking.
######2. What is the difference between integers and floats?
An integer is a whole number with no decimal points(eg. 2 or 9). A float is a number that may have decimals (eg. 2.5 or 9.0)
######3. What is the difference between integer and float division?
Float division is the division we're used to. In float division, you can get fraction answers. For example 7/2 = 3.5 in float division.
Integer division doesn't use decimals, it seems strange at first, but it's actually much more applicable to real life. For example if I have $100 I want to buy as many $15 CDs as I can, I would ask myself: What's 100/15? Float division would tell us that 100/15 is 6.666, but I can't buy .666 of a CD. 100/15 = 6 in integer division because it deals with whole numbers only.
######4. What are strings? Why and when would you use them?
Strings are a class of variable that includes a series or string of characters. You would use them if you wanted to work with anything that's not an integer, float, or boolean in ruby. For example words or numbers.
######5. What are local variables? Why and when would you use them?
Local variables are variables that you can define for a session of Ruby, but that will only exist in that session. They're extremely useful becuase you can use them to store values specific to one Ruby program or to store a temporary value.
######6. How was this challenge? Did you get a good review of some of the basics?
This challenge was fine. All around pretty easy, good to get back into Ruby slowly, but surely. I forget how much fun it is!
| gaw1990/phase-0 | 4-week/nums-letters.md | Markdown | mit | 3,360 |
module Thermometer
class << self
def configure
yield configuration
end
def configuration
@configuration ||= Configuration.new
end
end
end
require "active_record"
$LOAD_PATH.unshift(File.dirname(__FILE__))
require 'thermometer/configuration'
require "thermometer/evaluate"
require "thermometer/active_record"
require "thermometer/temperature"
$LOAD_PATH.shift
#if defined?(ActiveRecord::Base)
# class ActiveRecord::Base
# include Thermometer::Temperature
# end
#end
| blotto/thermometer | lib/thermometer.rb | Ruby | mit | 511 |
### 参考资料
* [iOS Touch ID 简易开发教程](http://segmentfault.com/a/1190000002516465)
* [iOS8 Touch ID api接口调用](http://blog.csdn.net/johnson_puning/article/details/36188255) | Bijiabo/ios-docs-cn | demo/TouchID/readme.md | Markdown | mit | 193 |
import unittest
from itertools import chain
from board import Board
class BoardTest(unittest.TestCase):
def test_board_width(self):
board = Board(6,5)
self.assertEqual(len(board.blocks), 5)
def test_board_height(self):
board = Board(6,5)
self.assertTrue(all(map(lambda x: len(x) == 6, board.blocks)))
def test_board_elements_all_none(self):
board = Board(6,5)
self.assertTrue(all(map(lambda x: x is None, chain(*board.blocks))))
if __name__ == '__main__':
unittest.main() | velinakd/candy-crush-2048 | tests/board_test.py | Python | mit | 541 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Microsoft.MixedReality.Toolkit.Core.Inspectors.Profiles;
using UnityEditor;
namespace Microsoft.MixedReality.Toolkit.Core.DataProviders.Controllers.UnityInput.Profiles.Inspectors
{
[CustomEditor(typeof(GenericUnityControllerMappingProfile))]
public class GenericUnityControllerMappingProfileInspector : BaseMixedRealityControllerMappingProfileInspector { }
} | StephenHodgson/MixedRealityToolkit-Unity | Assets/MixedRealityToolkit/_Core/DataProviders/Controllers/UnityInput/Profiles/Inspectors/GenericUnityControllerMappingProfileInspector.cs | C# | mit | 533 |
//..............................................................................
//
// This file is part of the Jancy toolkit.
//
// Jancy is distributed under the MIT license.
// For details see accompanying license.txt file,
// the public copy of which is also available at:
// http://tibbo.com/downloads/archive/jancy/license.txt
//
//..............................................................................
#include "pch.h"
#include "jnc_ct_SchedLauncherFunction.h"
#include "jnc_ct_Module.h"
namespace jnc {
namespace ct {
//..............................................................................
bool
SchedLauncherFunction::compile() {
bool result;
size_t argCount = m_type->getArgArray().getCount();
char buffer[256];
sl::Array<Value> argValueArray(rc::BufKind_Stack, buffer, sizeof(buffer));
argValueArray.setCount(argCount);
m_module->m_functionMgr.internalPrologue(this, argValueArray, argCount);
Value functionPtrValue = argValueArray[0];
Value schedulerValue = argValueArray[1];
Value scheduleValue;
result = m_module->m_operatorMgr.memberOperator(schedulerValue, "schedule", &scheduleValue);
if (!result)
return false;
if (argCount > 2) {
sl::BoxList<Value> argList;
for (size_t i = 2; i < argCount; i++)
argList.insertTail(argValueArray[i]);
result = m_module->m_operatorMgr.closureOperator(&functionPtrValue, &argList);
if (!result)
return false;
}
result = m_module->m_operatorMgr.callOperator(scheduleValue, functionPtrValue);
if (!result)
return false;
m_module->m_functionMgr.internalEpilogue();
return true;
}
//..............................................................................
} // namespace ct
} // namespace jnc
| vovkos/jancy | src/jnc_ct/jnc_ct_FunctionMgr/jnc_ct_SchedLauncherFunction.cpp | C++ | mit | 1,716 |
<?php
namespace Acme\ChildrenBundle\Repository;
use Doctrine\ORM\EntityRepository;
/**
* TextRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class ChildrenRepository extends EntityRepository
{
}
| systemdo/kindergarten | src/Acme/EmployedBundle/Repository/enRepository.php | PHP | mit | 269 |
using System;
using System.Collections.Generic;
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sisacon.Domain.Entities;
namespace Sisacon.Infra.Mapping
{
public class BaseMap<T> : EntityTypeConfiguration<T> where T : BaseEntity
{
public BaseMap()
{
HasKey(x => x.Id);
Property(x => x.RegistrationDate)
.HasColumnType("DateTime")
.IsRequired();
Property(x => x.ExclusionDate)
.HasColumnType("DateTime")
.IsOptional();
}
}
}
| OdimTech/Sisacon | Sisacon/Sisacon.Infra/Mapping/BaseMap.cs | C# | mit | 663 |
/* tslint:disable */
import { ConcreteRequest } from "relay-runtime";
import { FragmentRefs } from "relay-runtime";
export type ViewingRoomApp_ClosedTest_QueryVariables = {
slug: string;
};
export type ViewingRoomApp_ClosedTest_QueryResponse = {
readonly viewingRoom: {
readonly " $fragmentRefs": FragmentRefs<"ViewingRoomApp_viewingRoom">;
} | null;
};
export type ViewingRoomApp_ClosedTest_QueryRawResponse = {
readonly viewingRoom: ({
readonly title: string;
readonly image: ({
readonly imageURLs: ({
readonly normalized: string | null;
}) | null;
}) | null;
readonly partner: ({
readonly name: string | null;
readonly id: string | null;
readonly href: string | null;
}) | null;
readonly distanceToOpen: string | null;
readonly distanceToClose: string | null;
readonly status: string;
}) | null;
};
export type ViewingRoomApp_ClosedTest_Query = {
readonly response: ViewingRoomApp_ClosedTest_QueryResponse;
readonly variables: ViewingRoomApp_ClosedTest_QueryVariables;
readonly rawResponse: ViewingRoomApp_ClosedTest_QueryRawResponse;
};
/*
query ViewingRoomApp_ClosedTest_Query(
$slug: ID!
) {
viewingRoom(id: $slug) {
...ViewingRoomApp_viewingRoom
}
}
fragment ViewingRoomApp_viewingRoom on ViewingRoom {
...ViewingRoomMeta_viewingRoom
...ViewingRoomHeader_viewingRoom
...ViewingRoomContentNotAccessible_viewingRoom
status
}
fragment ViewingRoomContentNotAccessible_viewingRoom on ViewingRoom {
status
partner {
href
id
}
}
fragment ViewingRoomHeader_viewingRoom on ViewingRoom {
image {
imageURLs {
normalized
}
}
title
partner {
name
id
}
distanceToOpen
distanceToClose
status
}
fragment ViewingRoomMeta_viewingRoom on ViewingRoom {
title
}
*/
const node: ConcreteRequest = (function(){
var v0 = [
{
"kind": "LocalArgument",
"name": "slug",
"type": "ID!",
"defaultValue": null
}
],
v1 = [
{
"kind": "Variable",
"name": "id",
"variableName": "slug"
}
];
return {
"kind": "Request",
"fragment": {
"kind": "Fragment",
"name": "ViewingRoomApp_ClosedTest_Query",
"type": "Query",
"metadata": null,
"argumentDefinitions": (v0/*: any*/),
"selections": [
{
"kind": "LinkedField",
"alias": null,
"name": "viewingRoom",
"storageKey": null,
"args": (v1/*: any*/),
"concreteType": "ViewingRoom",
"plural": false,
"selections": [
{
"kind": "FragmentSpread",
"name": "ViewingRoomApp_viewingRoom",
"args": null
}
]
}
]
},
"operation": {
"kind": "Operation",
"name": "ViewingRoomApp_ClosedTest_Query",
"argumentDefinitions": (v0/*: any*/),
"selections": [
{
"kind": "LinkedField",
"alias": null,
"name": "viewingRoom",
"storageKey": null,
"args": (v1/*: any*/),
"concreteType": "ViewingRoom",
"plural": false,
"selections": [
{
"kind": "ScalarField",
"alias": null,
"name": "title",
"args": null,
"storageKey": null
},
{
"kind": "LinkedField",
"alias": null,
"name": "image",
"storageKey": null,
"args": null,
"concreteType": "ARImage",
"plural": false,
"selections": [
{
"kind": "LinkedField",
"alias": null,
"name": "imageURLs",
"storageKey": null,
"args": null,
"concreteType": "ImageURLs",
"plural": false,
"selections": [
{
"kind": "ScalarField",
"alias": null,
"name": "normalized",
"args": null,
"storageKey": null
}
]
}
]
},
{
"kind": "LinkedField",
"alias": null,
"name": "partner",
"storageKey": null,
"args": null,
"concreteType": "Partner",
"plural": false,
"selections": [
{
"kind": "ScalarField",
"alias": null,
"name": "name",
"args": null,
"storageKey": null
},
{
"kind": "ScalarField",
"alias": null,
"name": "id",
"args": null,
"storageKey": null
},
{
"kind": "ScalarField",
"alias": null,
"name": "href",
"args": null,
"storageKey": null
}
]
},
{
"kind": "ScalarField",
"alias": null,
"name": "distanceToOpen",
"args": null,
"storageKey": null
},
{
"kind": "ScalarField",
"alias": null,
"name": "distanceToClose",
"args": null,
"storageKey": null
},
{
"kind": "ScalarField",
"alias": null,
"name": "status",
"args": null,
"storageKey": null
}
]
}
]
},
"params": {
"operationKind": "query",
"name": "ViewingRoomApp_ClosedTest_Query",
"id": null,
"text": "query ViewingRoomApp_ClosedTest_Query(\n $slug: ID!\n) {\n viewingRoom(id: $slug) {\n ...ViewingRoomApp_viewingRoom\n }\n}\n\nfragment ViewingRoomApp_viewingRoom on ViewingRoom {\n ...ViewingRoomMeta_viewingRoom\n ...ViewingRoomHeader_viewingRoom\n ...ViewingRoomContentNotAccessible_viewingRoom\n status\n}\n\nfragment ViewingRoomContentNotAccessible_viewingRoom on ViewingRoom {\n status\n partner {\n href\n id\n }\n}\n\nfragment ViewingRoomHeader_viewingRoom on ViewingRoom {\n image {\n imageURLs {\n normalized\n }\n }\n title\n partner {\n name\n id\n }\n distanceToOpen\n distanceToClose\n status\n}\n\nfragment ViewingRoomMeta_viewingRoom on ViewingRoom {\n title\n}\n",
"metadata": {}
}
};
})();
(node as any).hash = 'fa8ab7ef7254649a80f9196118fc65e0';
export default node;
| oxaudo/force | src/v2/__generated__/ViewingRoomApp_ClosedTest_Query.graphql.ts | TypeScript | mit | 6,604 |
{% overextends "admin/base_site.html" %}
{% load i18n %}
{% block title %}Administration{% endblock %}
{% block extrahead %}
{{ block.super }}
<script type="text/javascript">
$(function() {
schnadmin.ui.message_fadeout()
})
</script>
{% endblock %}
{% block branding %}
<a href="{{ ADMIN_URL }}" id="logo" ><span></span></a>
{% endblock %}
{% block content_title %}
{{ block.super }}
<div id="site-info">
{% block site_info %}
{% endblock %}
</div>
{% endblock %}
| tonimichel/djpl-schnadmin | schnadmin/templates/admin/base_site.html | HTML | mit | 545 |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
#include "com.h"
#pragma clang diagnostic push
#pragma ide diagnostic ignored "OCUnusedGlobalDeclarationInspection"
#ifndef COMIMPL_H_INCLUDED
#define COMIMPL_H_INCLUDED
#include <cstring>
__IID_DEF(IUnknown, 0, 0, 0, C0, 00, 00, 00, 00, 00, 00, 46);
class ComObject : public virtual IUnknown
{
private:
unsigned int _refCount;
public:
virtual ULONG AddRef()
{
_refCount++;
return _refCount;
}
virtual ULONG Release()
{
_refCount--;
ULONG rv = _refCount;
if(_refCount == 0)
delete(this);
return rv;
}
ComObject()
{
_refCount = 1;
}
virtual ~ComObject()
{
}
virtual ::HRESULT STDMETHODCALLTYPE QueryInterfaceImpl(REFIID riid, void **ppvObject) = 0;
virtual ::HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid,
void **ppvObject)
{
if(0 == memcmp(riid, &IID_IUnknown, sizeof(GUID)))
*ppvObject = (IUnknown*)this;
else
{
auto rv = QueryInterfaceImpl(riid, ppvObject);
if(rv != S_OK)
return rv;
}
_refCount++;
return S_OK;
}
};
#define FORWARD_IUNKNOWN() \
virtual ULONG Release() override \
{ \
return ComObject::Release(); \
} \
virtual ULONG AddRef() override \
{ \
return ComObject::AddRef(); \
} \
virtual HRESULT QueryInterface(REFIID riid, void **ppvObject) override \
{ \
return ComObject::QueryInterface(riid, ppvObject); \
}
#define BEGIN_INTERFACE_MAP() public: virtual HRESULT STDMETHODCALLTYPE QueryInterfaceImpl(REFIID riid, void **ppvObject) override {
#define INTERFACE_MAP_ENTRY(TInterface, IID) if(0 == memcmp(riid, &IID, sizeof(GUID))) { TInterface* casted = this; *ppvObject = casted; return S_OK; }
#define END_INTERFACE_MAP() return E_NOINTERFACE; }
#define INHERIT_INTERFACE_MAP(TBase) if(TBase::QueryInterfaceImpl(riid, ppvObject) == S_OK) return S_OK;
class ComUnknownObject : public ComObject
{
public:
FORWARD_IUNKNOWN()
virtual ::HRESULT STDMETHODCALLTYPE QueryInterfaceImpl(REFIID riid, void **ppvObject) override
{
return E_NOINTERFACE;
};
virtual ~ComUnknownObject(){}
};
template<class TInterface, GUID const* TIID> class ComSingleObject : public ComObject, public virtual TInterface
{
BEGIN_INTERFACE_MAP()
INTERFACE_MAP_ENTRY(TInterface, *TIID)
END_INTERFACE_MAP()
public:
virtual ~ComSingleObject(){}
};
template<class TInterface>
class ComPtr
{
private:
TInterface* _obj;
public:
ComPtr()
{
_obj = 0;
}
ComPtr(TInterface* pObj)
{
_obj = 0;
if (pObj)
{
_obj = pObj;
_obj->AddRef();
}
}
ComPtr(const ComPtr& ptr)
{
_obj = 0;
if (ptr._obj)
{
_obj = ptr._obj;
_obj->AddRef();
}
}
ComPtr& operator=(ComPtr other)
{
if(_obj != NULL)
_obj->Release();
_obj = other._obj;
if(_obj != NULL)
_obj->AddRef();
return *this;
}
~ComPtr()
{
if (_obj)
{
_obj->Release();
_obj = 0;
}
}
TInterface* getRaw()
{
return _obj;
}
operator TInterface*() const
{
return _obj;
}
TInterface& operator*() const
{
return *_obj;
}
TInterface** operator&()
{
return &_obj;
}
TInterface* operator->() const
{
return _obj;
}
};
#endif // COMIMPL_H_INCLUDED
#pragma clang diagnostic pop
| jkoritzinsky/Perspex | native/Avalonia.Native/inc/comimpl.h | C | mit | 3,878 |
<?php
namespace PhpSchool\PhpWorkshopTest\Exception;
use PHPUnit\Framework\TestCase;
use PhpSchool\PhpWorkshop\Exception\MissingArgumentException;
class MissingArgumentExceptionTest extends TestCase
{
public function testException(): void
{
$e = new MissingArgumentException('some-route', ['arg1', 'arg2']);
$this->assertEquals(
'Command: "some-route" is missing the following arguments: "arg1", "arg2"',
$e->getMessage()
);
$this->assertSame(['arg1', 'arg2'], $e->getMissingArguments());
}
}
| php-school/php-workshop | test/Exception/MissingArgumentExceptionTest.php | PHP | mit | 565 |
import React from "react";
import {
HashSection,
Paragraph,
CodeBlock,
IJS
} from "../../../../../components/package/common";
let propsMeta = {
title: "Props",
hash: "navigating-props"
};
export let meta = {
title: "Navigating",
hash: "navigating"
};
export function NavigatingAPI() {
return (
<HashSection meta={meta} tag="h2">
<Paragraph>
The <IJS>Navigating</IJS> component is used to cancel an active
asynchronous navigation.
</Paragraph>
<Paragraph>
A component is passed to <IJS>Navigating</IJS>. When there is an active
asynchronous navigation, the component will be given a <IJS>cancel</IJS>{" "}
function. When there is not an active asynchronous navigation,{" "}
<IJS>cancel</IJS> will be <IJS>undefined</IJS>.
</Paragraph>
<CodeBlock lang="html">
{`<Navigating component={Cancel} />
<script>
import Navigating from "@curi/svelte/components/Navigating.svelte";
import Cancel from "./Cancel";
</script>`}
</CodeBlock>
<HashSection meta={propsMeta} tag="h3">
<HashSection
meta={{ title: "component", hash: "navigating-component" }}
tag="h4"
>
<Paragraph>
A component that receives a <IJS>cancel</IJS> function when there is
an active asynchronous navigation.
</Paragraph>
<CodeBlock lang="html">
{`{#if typeof cancel === "function"}
<button on:click="cancelHandler(event, cancel)">
Cancel Navigation
</button>
{/if}
<script>
export default {
methods: {
cancelHandler(event, cancel) {
event.preventDefault();
cancel();
}
}
};
</script>`}
</CodeBlock>
</HashSection>
</HashSection>
</HashSection>
);
}
| pshrmn/curi | website/src/pages/Packages/v2/svelte/api/navigating.js | JavaScript | mit | 1,820 |
(function(){
'use strict';
var app = window.LS || (window.LS = {});
var u = app.utils;
// Document module
app.document = {vm: {}};
app.document.vm.init = function() {
var vm = this;
vm.id = m.prop(m.route.param("id"));
vm.action = m.route.param("action");
vm.readOnly = true;
vm.contentType = m.prop("");
vm.updatedTags = m.prop("");
vm.content = "";
vm.binary = false;
vm.image = false;
vm.tags = [];
try {
vm.ext = vm.id().match(/\.([a-z0-9]+)$/i)[1];
} catch(e) {
vm.ext = "";
}
// Retrieve single document & update relevant variables
vm.getDoc = function(cb){
vm.doc = Doc.get(vm.id());
vm.doc.then(function(doc){
vm.content = doc.data;
vm.tags = doc.tags;
vm.updatedTags(vm.tags.filter(function(t){return !/^\$/.test(t)}).join(", "));
if (vm.tags.filter(function(t){return t === "$format:binary"}).length > 0) {
vm.binary = true;
if (vm.tags.filter(function(t){return t === "$type:image"}).length > 0) {
vm.image = true;
}
}
}, vm.flashError);
};
// Reset some properties based on action
switch (vm.action) {
case 'create':
vm.readOnly = false;
vm.content = "";
break;
case 'edit':
vm.getDoc();
vm.readOnly = false;
break;
case 'view':
vm.getDoc();
break;
}
// View document in editor
vm.viewDocument = function(){
if (vm.ext === "md" && vm.id().match(new RegExp("^admin\/md\/"))) {
// If editing a documentation page, go back to the guide.
m.route("/guide/"+vm.id().replace(/\.md$/, "").replace(new RegExp("^admin\/md\/"), ""));
} else {
m.route("/document/view/"+vm.id());
}
};
// Set current document editable
vm.edit = function(){
vm.editor.setReadOnly(false);
vm.action = "edit";
vm.flash("");
};
// Save document
vm.save = function(){
var doc = {};
doc.id = vm.id();
doc.data = vm.editor.getValue();
doc.tags = vm.tags;
var put = function(){
Doc.put(doc, vm.contentType()).then(function(){
LS.flash({type: "success", content: "Document saved successfully."});
vm.viewDocument();
}, vm.flashError);
};
if (vm.action === "create") {
doc.id = vm.id();
vm.id(doc.id);
Doc.get(doc.id)
.then(function(){
vm.showFlash({type: "danger", content: "Document '"+doc.id+"' already exists."});
}, function(){
put();
});
} else {
put();
}
};
// Delete Document
vm.delete = function(){
Doc.delete(vm.id()).then(function(){
LS.flash({type: "success", content: "Document '"+vm.id()+"' deleted successfully."});
// Tags may be changed, update infos
Info.get().then(function(info){
app.system = info;
m.route("/info");
});
}, vm.flashError);
};
// Cancel editing
vm.cancel = function(){
if (vm.action === "create"){
m.route("/info");
} else {
vm.viewDocument();
}
};
// Patch document (update tags)
vm.patch = function(){
var sysTags = vm.tags.filter(function(t){return /^\$/.test(t)});
var newTags = sysTags.concat(vm.updatedTags().split(/,\s*/));
Doc.patch(vm.id(), newTags).then(function(){
LS.flash({type: "success", content: "Tags for document '"+vm.id()+"' updated successfully."});
Info.get().then(function(info){
app.system = info;
vm.viewDocument();
});
}, vm.flashError);
};
// File uploader callbacks.
var onSuccess = function(data){
vm.id(data.id);
LS.flash({type: "success", content: "Document '"+vm.id()+"' uploader successfully."});
Info.get().then(function(info){
app.system = info;
vm.viewDocument();
});
};
var onFailure = function(data) { vm.flashError(data); };
var modalId = u.guid();
vm.uploader = u.uploader({docid: vm.id() || "", onSuccess: onSuccess, onFailure: onFailure, id: modalId});
// Populate tools based on current action
vm.tools = function(){
if (app.system.read_only) {
return [];
}
// Configure edit tags popover
var cfg = {};
cfg.title = "Edit Tags";
cfg.contentId = "#edit-tags-popover";
var tools = [];
var show = function(){ u.showModal()}
switch (vm.action){
case "view":
tools.push({title: "Upload", icon: "upload", action: vm.uploader.show()});
if (!vm.binary) {
tools.push({title: "Edit Content", icon: "edit", action: vm.edit});
}
tools.push({title: "Edit Tags", icon: "tags", action: u.showModal("#edit-tags-modal")});
tools.push({title: "Delete", icon: "trash", action: u.showModal("#delete-document-modal")});
break;
default:
tools.push({title: "Upload", icon: "upload", action: vm.uploader.show()});
tools.push({title: "Save", icon: "save", action: vm.save});
tools.push({title: "Cancel", icon: "times-circle", action: vm.cancel});
}
return tools;
};
};
// Module main view
app.document.main = function(){
var vm = app.document.vm;
var titleLeft = vm.id();
var titleRight = m("span.pull-right", vm.tags.map(function(t){return u.taglink({name: t, key: u.guid()});}));
// Delete confirmation dialog
var deleteDialogCfg = {
title: "Delete Document",
id: "delete-document-modal",
action: vm.delete,
actionText: "Delete",
content: m("p", "Do you want to delete document '"+vm.id()+"'?")
};
// Configuration for the Edit Tags dialog
var editTagsDialogCfg = {
title: "Add/Edit User Tags",
id: "edit-tags-modal",
action: vm.patch,
actionText: "Update",
content: m("div", [
m("input", {
type: "text",
class:"form-control",
onchange: m.withAttr("value", vm.updatedTags),
value: vm.updatedTags(),
placeholder: "Enter comma-separated tags..."
}),
m("div.tip", [
m("p", "Tip") ,
m("p", "Each user tag can contain letters, numbers, and any of the following special characters:"),
m("p", "?, ~, :, ., @, #, ^, !, +, _, or -")
])
])
};
if (vm.action === "create"){
titleLeft = m("span", [m("input", {
placeholder: "Document ID",
onchange: m.withAttr("value", function(value){
vm.id(value);
vm.editor.updateMode(value);
}),
size: 35,
value: vm.id()
})]);
titleRight = m("span.pull-right", [m("input", {
placeholder: "Content Type",
onchange: m.withAttr("value", function(value){
vm.contentType(value);
}),
size: 25,
value: vm.contentType()
})]);
}
var panelContent;
if (vm.image){
panelContent = m("div.text-center", [m("img", {src: app.host+"/docs/"+vm.id(), title: vm.id()})]);
} else {
panelContent = m.component(app.editor, vm);
}
var title = m("span",[titleLeft, titleRight]);
return m("div", [
vm.uploader,
u.modal(deleteDialogCfg),
u.modal(editTagsDialogCfg),
m(".row", [u.toolbar({links: vm.tools()})]),
m(".row", [u.panel({title: title, content:panelContent})])
]);
};
u.layout(app.document);
}());
| h3rald/litestore | src/admin/js/components/document.js | JavaScript | mit | 7,652 |
//
// AppDelegate.h
// GGCategories
//
// Created by 张贵广 on 2017/8/12.
// Copyright © 2017年 GG. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
| Zhangguiguang/GGCategories | GGCategories/AppDelegate.h | C | mit | 277 |
/* Copyright (C) 2019, 2020 Monomax Software Pty Ltd
*
* This file is part of Dnote.
*
* Dnote is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Dnote is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Dnote. If not, see <https://www.gnu.org/licenses/>.
*/
import React from 'react';
import { Link } from 'react-router-dom';
import classnames from 'classnames';
import { getNotePath } from 'web/libs/paths';
import { tokenize, TokenKind } from 'web/libs/fts/lexer';
import { NoteData } from 'jslib/operations/types';
import { excerpt } from 'web/libs/string';
import { Filters } from 'jslib/helpers/filters';
import { timeAgo } from '../../../helpers/time';
import Time from '../../Common/Time';
import styles from './NoteItem.scss';
function formatFTSSnippet(content: string): React.ReactNode[] {
const tokens = tokenize(content);
const output: React.ReactNode[] = [];
let buf = [];
for (let i = 0; i < tokens.length; i++) {
const t = tokens[i];
if (t.kind === TokenKind.hlBegin || t.kind === TokenKind.eol) {
output.push(buf.join(''));
buf = [];
} else if (t.kind === TokenKind.hlEnd) {
const comp = (
<span className={styles.match} key={i}>
{buf.join('')}
</span>
);
output.push(comp);
buf = [];
} else {
buf.push(t.value);
}
}
return output;
}
function renderContent(content: string): React.ReactNode[] {
if (content.indexOf('<dnotehl>') > -1) {
return formatFTSSnippet(content);
}
return excerpt(content, 160);
}
interface Props {
note: NoteData;
filters: Filters;
}
const NoteItem: React.FunctionComponent<Props> = ({ note, filters }) => {
const updatedAt = new Date(note.updatedAt).getTime();
return (
<li className={classnames('T-note-item', styles.wrapper, {})}>
<Link
className={styles.link}
to={getNotePath(note.uuid, filters)}
draggable={false}
>
<div className={styles.body}>
<div className={styles.header}>
<h3 className={styles['book-label']}>{note.book.label}</h3>
<Time
id={`${note.uuid}-ts`}
text={timeAgo(updatedAt)}
mobileText={timeAgo(updatedAt)}
ms={updatedAt}
wrapperClassName={styles.ts}
/>
</div>
<div className={styles.content}>{renderContent(note.content)}</div>
</div>
</Link>
</li>
);
};
export default NoteItem;
| dnote-io/cli | web/src/components/Home/NoteGroup/NoteItem.tsx | TypeScript | mit | 2,964 |
require 'test_helper'
class SucceedingTests < Test::Unit::TestCase
def test_succeeding1
assert_equal(true, true)
end
def test_succeeding2
assert_equal(true, true)
end
end
| guard/guard-test | test/succeeding_tests.rb | Ruby | mit | 188 |
/**
* 应用程序基类。
*
* @type {class}
*/
define(['jquery', 'core', 'base-ns', 'ui'], function ($, hsr, ns, ui) {
'use strict';
var _super = hsr.EventObject,
_superMethods = _super.prototype;
/**
* 构造方法。
*
* @param {HTMLElement | jQuery} element 主元素。
* @param {object} options 配置项。
*
* @constructor
*/
function ApplicationClass(options) {
// 私有属性。
var self = this;
// 特权属性。
this._options = options;
// 继承父类。
_super.call(self);
}
// 继承父类。
hsr.inherit(ApplicationClass, _super);
/***********公共(及特权)方法***********/
$.extend(ApplicationClass.prototype, {
/**
* 获取配置。
*
* @return {object} 配置信息。
*/
getOptions: function() {
return this._options;
},
/**
* 初始化。
*
* @protected
*/
_init: function () {
},
/**
* 销毁控件本身。
*
* @protected
*/
_destroy: function () {
var self = this;
_superMethods._destroy.call(self);
},
////////////////////// 浏览器窗口管理 ////////////////////
openLink: function (options) {
if(!options) return;
var url = options.url, name = options.name, opts = [];
if(hsr.StringUtils.isBlank(url)) return;
window.open(url, name, opts.join(','));
},
////////////////////// 消息管理 ////////////////////
/**
* 显示提示消息。
*
* @param {string} msg 提示的消息。
* @param {function} okCallbackFunc
*/
alert : function(msg, options){
hsr.ui.MessageBox.alert(msg, options);
},
/**
* 显示询问消息。
*
* @param {string} msg 提示的消息。
* @param {function} okCallbackFunc
*/
confirm : function (msg, okCallbackFunc, options) {
hsr.ui.MessageBox.confirm(msg, okCallbackFunc, options);
},
/**
* 显示提示消息。
*
* @param {string} msg 提示的消息。
*/
info : function (msg, options) {
hsr.ui.MessageBox.info(msg, options);
},
/**
* 显示警告消息。
*
* @param {string} msg 提示的消息。
*/
warn : function (msg, options) {
hsr.ui.MessageBox.warn(msg, options);
},
/**
* 显示错误消息。
*
* @param {string} msg 提示的消息。
*/
error : function (msg, options) {
hsr.ui.MessageBox.error(msg, options);
},
////////////////////// 对话框管理 ////////////////////
openDialog: function (options) {
var dialog = new ui.Dialog(options);
dialog.show();
},
openDetailDialog: function (options) {
var opts = $.extend(true, {}, {
id: 'dialog-edit',
title: '编辑',
buttons: [{
text: '取消'
}, {
text: '确定',
autofocus: true
}]
}, options);
this.openDialog(opts);
},
openEditDialog: function (options) {
var opts = $.extend(true, {}, {
id: 'dialog-edit',
title: '编辑',
buttons: [{
text: '取消'
}, {
text: '保存',
handler: function () {
var iframe = this.iframeNode;
if (iframe) {
var pageHandler = iframe.contentWindow['pageHandler'];
if (pageHandler && pageHandler.accept) {
pageHandler.accept();
}
return false;
}
},
autofocus: true
}]
}, options);
this.openDialog(opts);
}
////////////////////// 子页面管理 ////////////////////
});
return (ns.Application = ApplicationClass);
}); | ilfeng/hsr | src/js/framework/base/application.js | JavaScript | mit | 4,532 |
<table width="90%" border="0"><tr><td><script>function openfile(url) {fullwin = window.open(url, "fulltext", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes");}</script><div class="layoutclass_pic"><div class="layoutclass_first_pic"><table class="ztable"><tr><th class="ztd1"><b>成語 </b></th><td class="ztd2">行尸走骨</td></tr>
<tr><th class="ztd1"><b>注音 </b></th><td class="ztd2">ㄒ|ㄥ<sup class="subfont">ˊ</sup> ㄕ ㄗㄡ<sup class="subfont">ˇ</sup> ㄍㄨ<sup class="subfont">ˇ</sup></td></tr>
<tr><th class="ztd1"><b>漢語拼音 </b></th><td class="ztd2"><font class="english_word">xíng shī zǒu gǔ</font></td></tr>
<tr><th class="ztd1"><b>釋義 </b></th><td class="ztd2"> 義參「<a href="/cgi-bin/cydic/gsweb.cgi?o=dcydic&schfmt=text&gourl=%3De0%26sec%3Dsec1%26op%3Dsid%3D%22CW0000003457%22.%26v%3D-1" class="clink" target=_blank>行屍走肉</a>」。見「<a href="/cgi-bin/cydic/gsweb.cgi?o=dcydic&schfmt=text&gourl=%3De0%26sec%3Dsec1%26op%3Dsid%3D%22CW0000003457%22.%26v%3D-1" class="clink" target=_blank>行屍走肉</a>」條。</font></td></tr>
<tr><th class="ztd1"><b><style>.tableoutfmt2 .std1{width:3%;}</style></b></th><td class="ztd2"><table class="fmt16_table"><tr><td width=150 style="text-align:left;" class="fmt16_td1" ><b>參考詞語︰</b></td><td width=150 style="text-align:left;" class="fmt16_td2" ><a href="/cgi-bin/cydic/gsweb.cgi?o=dcydic&schfmt=text&gourl=%3De0%26sec%3Dsec1%26op%3Dsid%3D%22CW0000003457%22.%26v%3D-1" class="clink" target=_blank>行屍走肉</a></td></tr><tr><td width=150 style="text-align:left;" class="fmt16_td1" ><b>注音︰</b></td><td width=150 style="text-align:left;" class="fmt16_td2" >ㄒ|ㄥ<sup class="subfont">ˊ</sup> ㄕ ㄗㄡ<sup class="subfont">ˇ</sup> ㄖㄡ<sup class="subfont">ˋ</sup></td></tr><tr><td width=150 style="text-align:left;" class="fmt16_td1" ><b>漢語拼音︰</b></td><td width=150 style="text-align:left;" class="fmt16_td2" ><font class="english_word">xíng shī zǒu ròu</font></td></tr></table><br><br></td></tr>
</td></tr></table></div> <!-- layoutclass_first_pic --><div class="layoutclass_second_pic"></div> <!-- layoutclass_second_pic --></div> <!-- layoutclass_pic --></td></tr></table>
| BuzzAcademy/idioms-moe-unformatted-data | all-data/4000-4999/4676-34.html | HTML | mit | 2,285 |
package org.multibit.commons.crypto;
/**
* Copyright 2014 multibit.org
*
* Licensed under the MIT license (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://opensource.org/licenses/mit-license.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import com.google.common.base.Charsets;
import org.bitcoinj.core.Utils;
import org.bitcoinj.utils.BriefLogFormatter;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spongycastle.crypto.params.KeyParameter;
import java.security.SecureRandom;
import static org.junit.Assert.assertEquals;
public class AESUtilsTest {
private static final Logger log = LoggerFactory.getLogger(AESUtilsTest.class);
private static final String EXAMPLE_TEXT = "The quick brown fox jumps over the lazy dog. 01234567890. !@#$%^&*(). ,.;:[]-_=+";
// Nonsense bytes for encryption test.
private static final byte[] TEST_BYTES = {0, -101, 2, 103, -4, 105, 6, 107, 8, -109, 10, 111, -12, 113, 14, -115, 16, 117, -18, 119, 20, 121, 22, 123, -24, 125, 26, 127, -28, 29, -30, 31};
private byte[] initialisationVector;
private KeyParameter keyParameter;
private SecureRandom secureRandom;
@Before
public void setUp() throws Exception {
secureRandom = new SecureRandom();
// Create a random initialisationVector
initialisationVector = new byte[AESUtils.BLOCK_LENGTH];
secureRandom.nextBytes(initialisationVector);
// Create a random key
secureRandom.nextBytes(initialisationVector);
byte[] keyBytes = new byte[AESUtils.KEY_LENGTH];
keyParameter = new KeyParameter(keyBytes);
BriefLogFormatter.init();
}
@Test
public void testEncrypt_ExpectSuccess1() throws Exception {
// Plain text
byte[] plainBytes = EXAMPLE_TEXT.getBytes(Charsets.UTF_8);
log.debug("Initial message: '{}'", Utils.HEX.encode(plainBytes));
// Encrypt
byte[] encryptedBytes = AESUtils.encrypt(plainBytes, keyParameter, initialisationVector);
log.debug("Encrypted message: '{}'", Utils.HEX.encode(encryptedBytes));
// Decrypt
byte[] rebornBytes = AESUtils.decrypt(encryptedBytes, keyParameter, initialisationVector);
log.debug("Reborn message: '{}'", Utils.HEX.encode(rebornBytes));
assertEquals(Utils.HEX.encode(plainBytes), Utils.HEX.encode(rebornBytes));
}
@Test
public void testEncrypt_ExpectSuccess2() throws Exception {
for (int i = 0; i < 32; i++) {
// Plain text - random data with a random length
int length = secureRandom.nextInt(256);
byte[] plainBytes = new byte[length];
secureRandom.nextBytes(plainBytes);
log.debug("Initial message: '{}'", Utils.HEX.encode(plainBytes));
// Encrypt
byte[] encryptedBytes = AESUtils.encrypt(plainBytes, keyParameter, initialisationVector);
log.debug("Encrypted message: '{}'", Utils.HEX.encode(encryptedBytes));
// Decrypt
byte[] rebornBytes = AESUtils.decrypt(encryptedBytes, keyParameter, initialisationVector);
log.debug("Reborn message: '{}'", Utils.HEX.encode(rebornBytes));
assertEquals(Utils.HEX.encode(plainBytes), Utils.HEX.encode(rebornBytes));
}
}
@Test
public void testEncrypt_ExpectSuccess3() throws Exception {
// Plain text
byte[] plainBytes = TEST_BYTES;
log.debug("Initial message: '{}'", Utils.HEX.encode(plainBytes));
// Encrypt
byte[] encryptedBytes = AESUtils.encrypt(plainBytes, keyParameter, initialisationVector);
log.debug("Encrypted message: '{}'", Utils.HEX.encode(encryptedBytes));
// Decrypt
byte[] rebornBytes = AESUtils.decrypt(encryptedBytes, keyParameter, initialisationVector);
log.debug("Reborn message: '{}'", Utils.HEX.encode(rebornBytes));
assertEquals(Utils.HEX.encode(plainBytes), Utils.HEX.encode(rebornBytes));
}
}
| bitcoin-solutions/multibit-commons | src/test/java/org/multibit/commons/crypto/AESUtilsTest.java | Java | mit | 4,188 |
#ifndef DATA_STRUCTURE_AND_ALGO_GRAPH_ADJACENCY_MATRIX_H_
#define DATA_STRUCTURE_AND_ALGO_GRAPH_ADJACENCY_MATRIX_H_
#include "dsaa/macro.h"
#include "dsaa/queue.h"
#include "dsaa/avl_tree.h"
#include "dsaa/linked_list.h"
EXTERN_C_BEGIN
// graph adjacency matrix vertex
struct gam_vertex
{
void *key; // graph key
void *value; // graph vertex value
void *idx; // vertex index
};
struct gam_edge
{
struct gam_vertex *v1; // graph vertex 1
struct gam_vertex *v2; // graph vertex 2
void *weight; // edge weight
};
// graph adjacency matrix
struct gam
{
uint32_t capacity; // capacity of verteices
muggle_memory_pool_t vertex_pool; // vertex pool
muggle_memory_pool_t edge_pool; // edge pool
struct queue idx_queue; // index queue
uint32_t *idx_array; // index array
struct avl_tree key_vertex_map; // key to vertex map
struct gam_edge **edges; // graph adjacency matrix edges
};
// initialize graph adjacency matrix
// @param p_gam pointer to graph adjacency matrix
// @param cmp pointer to compare function of graph key
// @param capacity max number of graph adjacency matrix vertex
DSAA_EXPORT
bool gam_init(struct gam *p_gam, func_data_cmp cmp, uint32_t capacity);
// destroy graph adjacency matrix
// @param p_gam pointer to graph adjacency matrix
// @param key_func_free function for free key data, if it's NULL, do nothing for key data
// @param key_pool the memory pool passed to key_func_free
// @param value_func_free function for free value data, if it's NULL, do nothing for value data
// @param value_pool the memory pool passed to value_func_free
// @param weight_func_free function for free weight data, if it's NULL, do nothing for weight data
// @param weight_pool the memory pool passed to weight_func_free
DSAA_EXPORT
void gam_destroy(
struct gam *p_gam,
func_data_free key_func_free, void *key_pool,
func_data_free value_func_free, void *value_pool,
func_data_free weight_func_free, void *weight_pool);
// graph adjacency matrix add vertex
// @param p_gam pointer to graph adjacency matrix
// @param key added key
// @param value added value
DSAA_EXPORT
struct gam_vertex* gam_add_vertex(
struct gam *p_gam, void *key, void *value);
// graph adjacency matrix add edge
// @param p_gam pointer to graph adjacency matrix
// @param v1_key pointer to vertex 1 key
// @param v2_key pointer to vertex 2 key
// @param weight pointer to edge weight
DSAA_EXPORT
struct gam_edge* gam_add_edge(struct gam *p_gam, void *v1_key, void *v2_key, void *weight);
// graph adjacency matrix find vertex
// @param p_gam pointer to graph adjacency matrix
// @param key pointer to vertex key
DSAA_EXPORT
struct gam_vertex* gam_find_vertex(struct gam *p_gam, void *key);
// find edge from v1 to v2
// @param p_gam pointer to graph adjacency matrix
// @param v1_key pointer to vertex 1 key
// @param v2_key pointer to vertex 2 key
DSAA_EXPORT
struct gam_edge* gam_find_edge(struct gam *p_gam, void *v1_key, void *v2_key);
// find all edge start from vertex
// @param p_gam pointer to graph adjacency matrix
// @param key pointer to vertex key
DSAA_EXPORT
bool gam_find_out_edge(struct gam *p_gam, void *key, struct linked_list *list);
// find all edge end to vertex
// @param p_gam pointer to graph adjacency matrix
// @param key pointer to vertex key
DSAA_EXPORT
bool gam_find_in_edge(struct gam *p_gam, void *key, struct linked_list *list);
// remove vertex
// @param p_gam pointer to graph adjacency matrix
// @param key pointer to vertex key
// @param key_func_free function for free key data, if it's NULL, do nothing for key data
// @param key_pool the memory pool passed to key_func_free
// @param value_func_free function for free value data, if it's NULL, do nothing for value data
// @param value_pool the memory pool passed to value_func_free
// @param weight_func_free function for free weight data, if it's NULL, do nothing for weight data
// @param weight_pool the memory pool passed to weight_func_free
DSAA_EXPORT
void gam_remove_vertex(struct gam *p_gam, void *key,
func_data_free key_func_free, void *key_pool,
func_data_free value_func_free, void *value_pool,
func_data_free weight_func_free, void *weight_pool);
// remove edge that from v1 to v2
// @param p_gam pointer to graph adjacency matrix
// @param v1_key pointer to vertex 1 key
// @param v2_key pointer to vertex 2 key
// @param weight_func_free function for free weight data, if it's NULL, do nothing for weight data
// @param weight_pool the memory pool passed to weight_func_free
DSAA_EXPORT
void gam_remove_edge(struct gam *p_gam,
void *v1_key, void *v2_key,
func_data_free weight_func_free, void *weight_pool);
EXTERN_C_END
#endif
| MuggleWei/data_structure_and_algorithm | src/dsaa/graph_adj_matrix.h | C | mit | 4,935 |
package email
import (
"io/ioutil"
"os"
"testing"
"github.com/stretchr/testify/require"
)
/*
func newMessage(path string) Email {
message, err := NewFromFile(path)
if err != nil {
panic(err)
}
return message
}
*/
//
func TestNewFromFile(t *testing.T) {
message, err := NewFromFile("samples/multipart-text-html.eml")
require.NoError(t, err)
defer message.Close()
}
func TestNewFromByte(t *testing.T) {
fd, err := os.Open("samples/testgetbody.txt")
if err != nil {
panic(err)
}
defer fd.Close()
mBytes, err := ioutil.ReadAll(fd)
if err != nil {
panic(err)
}
message, err := NewFromByte(mBytes)
require.NoError(t, err)
defer message.Close()
}
/*
func TestRaw(t *testing.T) {
message := newMessage("samples/raw.txt")
defer message.Close()
raw, err := message.Raw()
require.NoError(t, err)
require.Equal(t, "rawmessage\r\n", string(raw))
}
//
func TestGetRawHeaders(t *testing.T) {
message := newMessage("samples/rawheaders.txt")
defer message.Close()
raw, err := message.GetRawHeaders()
require.NoError(t, err)
require.Equal(t, "header\r\nheader", string(raw))
}
func TestGetHeaders(t *testing.T) {
message := newMessage("samples/test-headers.txt")
defer message.Close()
hdr, err := message.GetHeaders("x-test-multi")
require.NoError(t, err)
assert.Equal(t, []string{"a", "a"}, hdr)
h, err := message.GetHeader("x-test-multi")
require.NoError(t, err)
assert.Equal(t, h, "a")
}
// TestGetContentType
func TestGetContentType(t *testing.T) {
message := newMessage("samples/multipart-text-html.txt")
defer message.Close()
contentType, _, err := message.GetContentType()
assert.NoError(t, err)
assert.Equal(t, "multipart/alternative", contentType)
}
func TestGetParts(t *testing.T) {
message := newMessage("samples/html_enc.eml")
defer message.Close()
_, err := message.GetParts()
require.NoError(t, err)
}
// TestGetBody test GetBody
func TestGetRawBody(t *testing.T) {
message := newMessage("samples/testgetbody.txt")
defer message.Close()
body, err := message.GetRawBody()
require.NoError(t, err)
assert.Equal(t, "The Best Play!", string(body))
}
// TestGetDomain return domains found in message
func TestGetDomains(t *testing.T) {
var err error
expectedDomains := map[string]int{
"protecmail.com": 5,
"tedmailing1.fr": 1,
"bacori1.fr": 8,
"majuscul1.fr": 1,
}
message := newMessage("samples/html.txt")
defer message.Close()
domains, err := message.GetDomains()
require.NoError(t, err)
for d, o := range expectedDomains {
_, found := domains[d]
require.True(t, found)
assert.Equal(t, o, domains[d])
}
for d, o := range domains {
_, found := expectedDomains[d]
require.True(t, found)
assert.Equal(t, o, expectedDomains[d])
}
}
*/
| toorop/email | email_test.go | GO | mit | 2,733 |
## Docker Base: Devbase-kafka
This repository contains **Dockerbase** of [Devbase-kafka](http://kafka.apache.org/) for [Docker](https://www.docker.com/)'s [Dockerbase build](https://registry.hub.docker.com/u/dockerbase/devbase-kafka/) published on the public [Docker Hub Registry](https://registry.hub.docker.com/).
### Depends on:
* [dockerbase/devbase-scala](https://registry.hub.docker.com/u/dockerbase/devbase-scala)
### Installation
1. Install [Docker](https://docs.docker.com/installation/).
2. Download [Dockerbase build](https://registry.hub.docker.com/u/dockerbase/devbase-kafka/) from public [Docker Hub Registry](https://registry.hub.docker.com/): `docker pull dockerbase/devbase-kafka`
### Usage
docker run -it --rm --name dockerbase-devbase-kafka dockerbase/devbase-kafka
### Components & Versions
Description: Ubuntu 14.04.1 LTS
git version 1.9.1
OpenSSH_6.6.1p1 Ubuntu-2ubuntu2, OpenSSL 1.0.1f 6 Jan 2014
GNU Make 3.81
Copyright (C) 2006 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.
There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE.
This program built for x86_64-pc-linux-gnu
javac 1.8.0_20
java version "1.8.0_20"
Java(TM) SE Runtime Environment (build 1.8.0_20-b26)
Java HotSpot(TM) 64-Bit Server VM (build 25.20-b23, mixed mode)
kafka:0.8.2.0
| dockerbase/devbase-kafka | README.md | Markdown | mit | 1,427 |
/**
* Wrapper class based on the following block of SVG:
*
* <text
* xmlns="http://www.w3.org/2000/svg"
* id="toolMenuItemRectangle"
* y="18" x="5"
* onmousedown="app.controller.onToolMenuItemSelect('Rectangle')"
* onmouseover="app.controller.onToolMenuItemMouseOver('toolMenuItemRectangle')"
* onmouseout="app.controller.onToolMenuItemMouseOut('toolMenuItemRectangle')">
* Rectangle</text>
*
*/
class ToolMenuItem extends Text {
/**
* Class constructor.
*
* @param descriptor string
* @param x integer
* @param y integer
*/
constructor(descriptor, xCoordinate, yCoordinate) {
super({
xmlns: Util.xmlNamespaces().xmlns,
id: 'toolMenuItem' + descriptor,
x: xCoordinate,
y: yCoordinate,
text: descriptor,
cursor: 'pointer',
onClick: null,
onMouseDown: "app.controller.onToolMenuItemSelect('" + descriptor + "');",
onMouseOver: "app.controller.onToolMenuItemMouseOver('" + 'toolMenuItem' + descriptor +"');",
onMouseOut: "app.controller.onToolMenuItemMouseOut('" + 'toolMenuItem' + descriptor + "');"
});
}
}
| bradyhouse/house | fiddles/svg/fiddle-0023-MenuBar/src/view/menubar/toolgroup/toolmenu/ToolMenuItem.js | JavaScript | mit | 1,241 |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bridge\Twig\Extension;
use Symfony\Bridge\Twig\TokenParser\DumpTokenParser;
use Symfony\Component\VarDumper\Cloner\ClonerInterface;
use Symfony\Component\VarDumper\Dumper\HtmlDumper;
use Twig\Environment;
use Twig\Extension\AbstractExtension;
use Twig\Template;
use Twig\TwigFunction;
/**
* Provides integration of the dump() function with Twig.
*
* @author Nicolas Grekas <[email protected]>
*/
final class DumpExtension extends AbstractExtension
{
private ClonerInterface $cloner;
private ?HtmlDumper $dumper;
public function __construct(ClonerInterface $cloner, HtmlDumper $dumper = null)
{
$this->cloner = $cloner;
$this->dumper = $dumper;
}
/**
* {@inheritdoc}
*/
public function getFunctions(): array
{
return [
new TwigFunction('dump', $this->dump(...), ['is_safe' => ['html'], 'needs_context' => true, 'needs_environment' => true]),
];
}
/**
* {@inheritdoc}
*/
public function getTokenParsers(): array
{
return [new DumpTokenParser()];
}
public function dump(Environment $env, array $context): ?string
{
if (!$env->isDebug()) {
return null;
}
if (2 === \func_num_args()) {
$vars = [];
foreach ($context as $key => $value) {
if (!$value instanceof Template) {
$vars[$key] = $value;
}
}
$vars = [$vars];
} else {
$vars = \func_get_args();
unset($vars[0], $vars[1]);
}
$dump = fopen('php://memory', 'r+');
$this->dumper = $this->dumper ?? new HtmlDumper();
$this->dumper->setCharset($env->getCharset());
foreach ($vars as $value) {
$this->dumper->dump($this->cloner->cloneVar($value), $dump);
}
return stream_get_contents($dump, -1, 0);
}
}
| symfony/symfony | src/Symfony/Bridge/Twig/Extension/DumpExtension.php | PHP | mit | 2,185 |
# models.autodesk.io sample
[](https://travis-ci.org/cyrillef/models.autodesk.io)
[](https://nodejs.org/)
[](https://www.npmjs.com/)
[](http://developer-autodesk.github.io/)

[](http://opensource.org/licenses/MIT)
<b>Note:</b> For hosting this sample, you do not need any credentials. But anyone using the sample will need
valid credentials for the translation / extraction process. Visit [the Forge WEB site](https://developer.autodesk.com) for
instructions to get on-board.
## Live demo at
https://models.autodesk.io/
[](https://models.autodesk.io/)
## Motivation
Our View and Data API Beta adds powerful 2D and 3D viewing functionality to your web apps.
Our REST and JavaScript API makes it easier to create applications that can view, zoom and interact with 2D and
3D models from over 60+ model formats with just a web browser, no plugin required!
But what if you wanted to view them and/or use the client API without having to implement the upload/translation protocol.
This sample will go through all the required steps.
## Description
This sample exercises and demonstrates the Autodesk View and Data API authorization, and the translation process
mentioned in the Quick Start guide. It provides you a quick way to get file ready for viewing on your own account.
It closely follows the steps described in the documentation:
* http://developer.api.autodesk.com/documentation/v1/vs_quick_start.html
In order to make use of this sample, you need to register your consumer key:
* https://developer.autodesk.com > My Apps
This provides the credentials to supply to the https requests on the Autodesk server.
## Dependencies
This sample is dependent of Node.js and few Node.js extensions which would update/install automatically via 'npm':
1. Node.js
Node.js - built on Chrome's JavaScript runtime for easily building fast, scalable network applications.
You need at least version v0.10.0. You can get Node.js from [here](http://nodejs.org/)<br /><br />
Node.js modules:
```
"serve-favicon": ">= 0.0.2",
"express": ">= 4.12.3",
"request": ">= 2.55.0",
"connect-multiparty": ">= 1.2.5",
"body-parser": ">= 1.11.0",
"fs": ">= 0.0.2",
"unirest": ">= 0.4.0",
"util": ">= 0.10.3",
"path": ">= 0.11.14",
"async": ">= 1.2.0"
```
2. filedrop.js - A Self-contained cross-browser HTML5, legacy, AJAX, drag & drop JavaScript file upload, available [here](http://filedropjs.org/).
3. flipclock.js - A flip clock javascript library, available [here](http://flipclockjs.com/).
4. zeroclipboard.js - A library which provides an easy way to copy text to the clipboard using an invisible Adobe Flash movie and a JavaScript interface,
available [here](http://zeroclipboard.org/).
## Setup/Usage Instructions
The sample was created using Node.js and javascript.
### Deploy on Heroku
[](https://heroku.com/deploy)
### Setup
1. Download and install [Node.js](http://nodejs.org/) (that will install npm as well)
2. Download this repo anywhere you want (the server will need to write files, so make sure you install in
a location where you have write permission, at least the 'uploads' folder)
3. Execute 'npm install', this command will download and install the required node modules automatically for you.
These modules are only required for the translation process.<br />
```
npm install
```
4. You are done for the setup, launch the node server using the command '[sudo] node start.js'.
sudo is required only on OSX and Linux.<br />
* Windows<br />
```
[set PORT=<port>]
node start.js
```
* OSX/Linux<br />
```
sudo [PORT=<port>] node start.js
```
<br />
<b>Note:</b> the port argument can be omitted and default to port 3000. If port 80 is already in use by another
application (like Skype, or IIS, or Apache, ...), you can use any other free port such as 8000, 3000, etc...
But in the next section you would need to specify the port to use, i.e. http://localhost[:port]/
### Use of the sample
Translating files
1. Start your favorite browser supporting HTML5 and WEBGL and browse to [http://localhost:3000/](http://localhost:3000/).<br />
<b>Note:</b> In case you use a different port above do not forget to include it in the URL. I.e.
[http://localhost:8000/](http://localhost:8000/).
2. Drag'n Drop your files into the 'Drop area' or browse for individual files, That's it.<br />
Or choose one of the proposed sample from the Dropbox and click on teh the 'Translate this one for me'.
3. After the translation completed successfully, you can copy the encoded urn string that you can use to view the
results, in a html page which supports the Autodesk viewer.
4. You are done with translation.
--------
## License
This sample is licensed under the terms of the [MIT License](http://opensource.org/licenses/MIT). Please see the [LICENSE](LICENSE) file for full details.
## Written by
Cyrille Fauvel (Autodesk Developer Network)<br />
http://www.autodesk.com/adn<br />
http://around-the-corner.typepad.com/<br />
| cyrillef/workflow-node.js-host-view.and.data.api | README.md | Markdown | mit | 5,579 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.