answer
stringlengths 15
1.25M
|
|---|
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>">
<link rel="profile" href="http://gmpg.org/xfn/11">
<?php wp_head(); ?>
</head>
<body>
<!-- Main navigation -->
<?php
do_action( 'omega_before_header' );
?>
<!-- Featured post -->
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1 col-sm-12 col-xs-12">
<div id="header-template">
</div>
</div>
</div>
</div>
<script type='template' id='headerTemplate'>
<a href="<%- url %>">
<div class="header-feature">
<div class="header-mask">
<img class="header-mask-image" src="<%= thumbnail_images == 'undefined' ? 'http://placehold.it/350x150' : thumbnail_images.large.url %>" alt="<%- title %>">
</div>
<div class="header-feature-text">
<h5>
<%= custom_fields.participant %>
</h5>
<h1>
<%= title %>
</h1>
</div>
</div>
</a>
</script>
|
<?php
namespace AppBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\<API key>;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use AppBundle\Entity\User;
class registerType extends AbstractType
{
public function buildForm(<API key> $builder, array $options)
{
$builder
->add('eMail', EmailType::class)
->add('password', RepeatedType::class, [
'type' => PasswordType::class
]);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => User::class
]);
}
public function getBlockPrefix()
{
return '<API key>';
}
}
|
package net.dudehook.cliche2.util;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @author ASG
*/
public final class ArrayHashMultiMap<K, V> implements MultiMap<K, V>
{
private Map<K, List<V>> listMap;
public ArrayHashMultiMap()
{
listMap = new HashMap<K, List<V>>();
}
public ArrayHashMultiMap(MultiMap<K, V> map)
{
this();
putAll(map);
}
public void put(K key, V value)
{
List<V> values = listMap.get(key);
if (values == null)
{
values = new ArrayList<V>();
listMap.put(key, values);
}
values.add(value);
}
public Collection<V> get(K key)
{
List<V> result = listMap.get(key);
if (result == null)
{
result = new ArrayList<V>();
}
return result;
}
public Set<K> keySet()
{
return listMap.keySet();
}
public void remove(K key, V value)
{
List<V> values = listMap.get(key);
if (values != null)
{
values.remove(value);
if (values.isEmpty())
{
listMap.remove(key);
}
}
}
public void removeAll(K key)
{
listMap.remove(key);
}
public int size()
{
int sum = 0;
for (K key : listMap.keySet())
{
sum += listMap.get(key).size();
}
return sum;
}
public void putAll(MultiMap<K, V> map)
{
for (K key : map.keySet())
{
for (V val : map.get(key))
{
put(key, val);
}
}
}
@Override
public String toString()
{
return listMap.toString();
}
}
|
const fs = require('fs')
const { normalize, resolve, join, sep } = require('path')
function getAppDir () {
let dir = process.cwd()
while (dir.length && dir[dir.length - 1] !== sep) {
if (fs.existsSync(join(dir, 'quasar.conf.js'))) {
return dir
}
dir = normalize(join(dir, '..'))
}
const { fatal } = require('./helpers/logger')
fatal(`Error. This command must be executed inside a Quasar v1+ project folder.`)
}
const appDir = getAppDir()
const cliDir = resolve(__dirname, '..')
const srcDir = resolve(appDir, 'src')
const pwaDir = resolve(appDir, 'src-pwa')
const ssrDir = resolve(appDir, 'src-ssr')
const cordovaDir = resolve(appDir, 'src-cordova')
const capacitorDir = resolve(appDir, 'src-capacitor')
const electronDir = resolve(appDir, 'src-electron')
const bexDir = resolve(appDir, 'src-bex')
module.exports = {
cliDir,
appDir,
srcDir,
pwaDir,
ssrDir,
cordovaDir,
capacitorDir,
electronDir,
bexDir,
resolve: {
cli: dir => join(cliDir, dir),
app: dir => join(appDir, dir),
src: dir => join(srcDir, dir),
pwa: dir => join(pwaDir, dir),
ssr: dir => join(ssrDir, dir),
cordova: dir => join(cordovaDir, dir),
capacitor: dir => join(capacitorDir, dir),
electron: dir => join(electronDir, dir),
bex: dir => join(bexDir, dir)
}
}
|
<?php
require_once('config.php');
$session->requireLoggedIn();
require('design_head.php');
$text = '';
if (!empty($_POST['text'])) {
$text = $_POST['text'];
guessLanguage($text);
}
?>
<h2>Guess language</h2>
Enter some text and see if the program can guess the language that the text were written in.
<form method="post" action="">
<textarea name="text" cols="70" rows="20"></textarea><br/>
<input type="submit" class="button" value="Submit"/>
</form>
<?php
require('design_foot.php');
?>
|
module.exports = {
testClient: 'http://localhost:8089/dist/',
mochaTimeout: 10000,
testLayerIds: [0],
seleniumTimeouts: {
script: 5000,
implicit: 1000,
pageLoad: 5000
}
}
|
'use strict';
import Maths from './maths.js'
import FSM from './fsm.js'
import { Animation, Interpolation } from './animation.js'
export { Maths, FSM, Interpolation, Animation }
|
namespace Free.FileFormats.VRML.Interfaces
{
public interface <API key>
{
}
}
|
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// all copies or substantial portions of the Software.
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// 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.
#ifndef _GFXGLCUBEMAP_H_
#define _GFXGLCUBEMAP_H_
#ifndef _GFXCUBEMAP_H_
#include "gfx/gfxCubemap.h"
#endif
#ifndef __RESOURCE_H__
#include "core/resource.h"
#endif
class GFXGLCubemap : public GFXCubemap
{
public:
GFXGLCubemap();
virtual ~GFXGLCubemap();
virtual void initStatic( GFXTexHandle *faces );
virtual void initStatic( DDSFile *dds );
virtual void initDynamic( U32 texSize, GFXFormat faceFormat = GFXFormatR8G8B8A8, U32 mipLevels = 0);
virtual U32 getSize() const { return mWidth; }
virtual GFXFormat getFormat() const { return mFaceFormat; }
// Convenience methods for GFXGLTextureTarget
U32 getWidth() { return mWidth; }
U32 getHeight() { return mHeight; }
U32 getHandle() { return mCubemap; }
// GFXResource interface
virtual void zombify();
virtual void resurrect();
Called by texCB; this is to ensure that all textures have been resurrected before we attempt to res the cubemap.
void tmResurrect();
static GLenum <API key>(U32 face) { return faceList[face]; } ///< Performs lookup to get a GLenum for the given face number
protected:
friend class GFXDevice;
friend class GFXGLDevice;
The callback used to get texture events.
@see GFXTextureManager::addEventDelegate
void _onTextureEvent( GFXTexCallbackCode code );
GLuint mCubemap; ///< Internal GL handle
U32 mDynamicTexSize; ///< Size of faces for a dynamic texture (used in resurrect)
// Self explanatory
U32 mWidth;
U32 mHeight;
GFXFormat mFaceFormat;
GFXTexHandle mTextures[6]; ///< Keep refs to our textures for resurrection of static cubemaps
The backing DDSFile uses to restore the faces
when the surface is lost.
Resource<DDSFile> mDDSFile;
// should only be called by GFXDevice
virtual void setToTexUnit( U32 tuNum ); ///< Binds the cubemap to the given texture unit
virtual void bind(U32 textureUnit) const; ///< Notifies our owning device that we want to be set to the given texture unit (used for GL internal state tracking)
void fillCubeTextures(GFXTexHandle* faces); ///< Copies the textures in faces into the cubemap
static GLenum faceList[6]; ///< Lookup table
};
#endif
|
// Runs the wiki on port 80
var server = require('./server');
server.run(80);
|
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
#pragma once
#include "windows.h"
#include "targetver.h"
#include <string>
// Headers for CppUnitTest
//#include "CppUnitTest.h"
// TODO: reference additional headers your program requires here
|
from datetime import datetime
from zipfile import ZipFile
from io import BytesIO
from lxml import etree
from docxgen import *
from docxgen import nsmap
from . import check_tag
def test_init():
doc = Document()
check_tag(doc.doc, ['document', 'body'])
check_tag(doc.body, ['body'])
def test_save():
doc = Document()
tmp = BytesIO()
doc.save(tmp)
with ZipFile(tmp) as zippy:
assert(zippy.testzip() is None)
assert(set(zippy.namelist()) == set([
'[Content_Types].xml', '_rels/.rels', 'docProps/app.xml',
'word/fontTable.xml', 'word/numbering.xml', 'word/settings.xml',
'word/styles.xml', 'word/stylesWithEffects.xml',
'word/webSettings.xml', 'word/theme/theme1.xml',
'word/_rels/document.xml.rels', 'word/document.xml',
'docProps/core.xml'
]))
zxf = zippy.open('word/document.xml')
root = etree.parse(zxf)
check_tag(root, 'document body'.split())
def test_load():
# assume save works
d = Document()
tmp = BytesIO()
d.save(tmp)
doc = Document.load(tmp)
check_tag(doc.doc, 'document body'.split())
check_tag(doc.body, 'body'.split())
def test_dumps():
doc = Document()
assert doc.dumps()
def test_core_props():
doc = Document()
attrs = dict(lastModifiedBy='Joe Smith',
keywords=['egg', 'spam'],
title='Testing Doc',
subject='A boilerplate document',
creator='Jill Smith',
description='Core properties test.',
created=datetime.now()
)
doc.update(attrs)
core = doc.get_core_props()
for key in ('title', 'subject', 'creator', 'description'):
attr = core.find('.//dc:%s' % key, namespaces=nsmap)
assert attr is not None
assert attr.text == attrs[key]
attr = core.find('.//cp:keywords', namespaces=nsmap)
assert attr is not None
assert attr.text == ','.join(attrs['keywords'])
attr = core.find('.//dcterms:created', namespaces=nsmap)
assert attr is not None
assert datetime.strptime(attr.text, '%Y-%m-%dT%H:%M:%SZ') == datetime(*attrs['created'].timetuple()[:6])
|
/**
* This code was auto-generated by a Codezu.
*
* Changes to this file may cause incorrect behavior and will be lost if
* the code is regenerated.
*/
package com.mozu.api.clients.commerce.customer.accounts;
import java.util.List;
import java.util.ArrayList;
import com.mozu.api.MozuClient;
import com.mozu.api.MozuClientFactory;
import com.mozu.api.MozuUrl;
import com.mozu.api.Headers;
import org.joda.time.DateTime;
import com.mozu.api.AsyncCallback;
import java.util.concurrent.CountDownLatch;
import com.mozu.api.security.AuthTicket;
import org.apache.commons.lang.StringUtils;
/** <summary>
* Tenant administrators can add and view internal notes for a customer account. For example, a client can track a shopper's interests or complaints. Only clients can add and view notes. Shoppers cannot view these notes from the My Account page.
* </summary>
*/
public class CustomerNoteClient {
/**
* Retrieves the contents of a particular note attached to a specified customer account.
* <p><pre><code>
* MozuClient<com.mozu.api.contracts.customer.CustomerNote> mozuClient=<API key>( accountId, noteId);
* client.setBaseAddress(url);
* client.executeRequest();
* CustomerNote customerNote = client.Result();
* </code></pre></p>
* @param accountId Unique identifier of the customer account.
* @param noteId Unique identifier of a particular note to retrieve.
* @return Mozu.Api.MozuClient <com.mozu.api.contracts.customer.CustomerNote>
* @see com.mozu.api.contracts.customer.CustomerNote
*/
public static MozuClient<com.mozu.api.contracts.customer.CustomerNote> <API key>(Integer accountId, Integer noteId) throws Exception
{
return <API key>( accountId, noteId, null);
}
/**
* Retrieves the contents of a particular note attached to a specified customer account.
* <p><pre><code>
* MozuClient<com.mozu.api.contracts.customer.CustomerNote> mozuClient=<API key>( accountId, noteId, responseFields);
* client.setBaseAddress(url);
* client.executeRequest();
* CustomerNote customerNote = client.Result();
* </code></pre></p>
* @param accountId Unique identifier of the customer account.
* @param noteId Unique identifier of a particular note to retrieve.
* @param responseFields Use this field to include those fields which are not included by default.
* @return Mozu.Api.MozuClient <com.mozu.api.contracts.customer.CustomerNote>
* @see com.mozu.api.contracts.customer.CustomerNote
*/
public static MozuClient<com.mozu.api.contracts.customer.CustomerNote> <API key>(Integer accountId, Integer noteId, String responseFields) throws Exception
{
MozuUrl url = com.mozu.api.urls.commerce.customer.accounts.CustomerNoteUrl.getAccountNoteUrl(accountId, noteId, responseFields);
String verb = "GET";
Class<?> clz = com.mozu.api.contracts.customer.CustomerNote.class;
MozuClient<com.mozu.api.contracts.customer.CustomerNote> mozuClient = (MozuClient<com.mozu.api.contracts.customer.CustomerNote>) MozuClientFactory.getInstance(clz);
mozuClient.setVerb(verb);
mozuClient.setResourceUrl(url);
return mozuClient;
}
/**
* Retrieves a list of notes added to a customer account according to any specified filter criteria and sort options.
* <p><pre><code>
* MozuClient<com.mozu.api.contracts.customer.<API key>> mozuClient=<API key>( accountId);
* client.setBaseAddress(url);
* client.executeRequest();
* <API key> <API key> = client.Result();
* </code></pre></p>
* @param accountId Unique identifier of the customer account.
* @return Mozu.Api.MozuClient <com.mozu.api.contracts.customer.<API key>>
* @see com.mozu.api.contracts.customer.<API key>
*/
public static MozuClient<com.mozu.api.contracts.customer.<API key>> <API key>(Integer accountId) throws Exception
{
return <API key>( accountId, null, null, null, null, null);
}
/**
* Retrieves a list of notes added to a customer account according to any specified filter criteria and sort options.
* <p><pre><code>
* MozuClient<com.mozu.api.contracts.customer.<API key>> mozuClient=<API key>( accountId, startIndex, pageSize, sortBy, filter, responseFields);
* client.setBaseAddress(url);
* client.executeRequest();
* <API key> <API key> = client.Result();
* </code></pre></p>
* @param accountId Unique identifier of the customer account.
* @param filter A set of expressions that consist of a field, operator, and value and represent search parameter syntax when filtering results of a query. Valid operators include equals (eq), does not equal (ne), greater than (gt), less than (lt), greater than or equal to (ge), less than or equal to (le), starts with (sw), or contains (cont). For example - "filter=IsDisplayed+eq+true"
* @param pageSize The number of results to display on each page when creating paged results from a query. The maximum value is 200.
* @param responseFields Use this field to include those fields which are not included by default.
* @param sortBy The property by which to sort results and whether the results appear in ascending (a-z) order, represented by ASC or in descending (z-a) order, represented by DESC. The sortBy parameter follows an available property. For example: "sortBy=productCode+asc"
* @param startIndex When creating paged results from a query, this value indicates the zero-based offset in the complete result set where the returned entities begin. For example, with a PageSize of 25, to get the 51st through the 75th items, use startIndex=3.
* @return Mozu.Api.MozuClient <com.mozu.api.contracts.customer.<API key>>
* @see com.mozu.api.contracts.customer.<API key>
*/
public static MozuClient<com.mozu.api.contracts.customer.<API key>> <API key>(Integer accountId, Integer startIndex, Integer pageSize, String sortBy, String filter, String responseFields) throws Exception
{
MozuUrl url = com.mozu.api.urls.commerce.customer.accounts.CustomerNoteUrl.getAccountNotesUrl(accountId, filter, pageSize, responseFields, sortBy, startIndex);
String verb = "GET";
Class<?> clz = com.mozu.api.contracts.customer.<API key>.class;
MozuClient<com.mozu.api.contracts.customer.<API key>> mozuClient = (MozuClient<com.mozu.api.contracts.customer.<API key>>) MozuClientFactory.getInstance(clz);
mozuClient.setVerb(verb);
mozuClient.setResourceUrl(url);
return mozuClient;
}
/**
* Adds a new note to the specified customer account.
* <p><pre><code>
* MozuClient<com.mozu.api.contracts.customer.CustomerNote> mozuClient=<API key>( note, accountId);
* client.setBaseAddress(url);
* client.executeRequest();
* CustomerNote customerNote = client.Result();
* </code></pre></p>
* @param accountId Unique identifier of the customer account.
* @param note Properties of a note configured for a customer account.
* @return Mozu.Api.MozuClient <com.mozu.api.contracts.customer.CustomerNote>
* @see com.mozu.api.contracts.customer.CustomerNote
* @see com.mozu.api.contracts.customer.CustomerNote
*/
public static MozuClient<com.mozu.api.contracts.customer.CustomerNote> <API key>(com.mozu.api.contracts.customer.CustomerNote note, Integer accountId) throws Exception
{
return <API key>( note, accountId, null);
}
/**
* Adds a new note to the specified customer account.
* <p><pre><code>
* MozuClient<com.mozu.api.contracts.customer.CustomerNote> mozuClient=<API key>( note, accountId, responseFields);
* client.setBaseAddress(url);
* client.executeRequest();
* CustomerNote customerNote = client.Result();
* </code></pre></p>
* @param accountId Unique identifier of the customer account.
* @param responseFields Use this field to include those fields which are not included by default.
* @param note Properties of a note configured for a customer account.
* @return Mozu.Api.MozuClient <com.mozu.api.contracts.customer.CustomerNote>
* @see com.mozu.api.contracts.customer.CustomerNote
* @see com.mozu.api.contracts.customer.CustomerNote
*/
public static MozuClient<com.mozu.api.contracts.customer.CustomerNote> <API key>(com.mozu.api.contracts.customer.CustomerNote note, Integer accountId, String responseFields) throws Exception
{
MozuUrl url = com.mozu.api.urls.commerce.customer.accounts.CustomerNoteUrl.addAccountNoteUrl(accountId, responseFields);
String verb = "POST";
Class<?> clz = com.mozu.api.contracts.customer.CustomerNote.class;
MozuClient<com.mozu.api.contracts.customer.CustomerNote> mozuClient = (MozuClient<com.mozu.api.contracts.customer.CustomerNote>) MozuClientFactory.getInstance(clz);
mozuClient.setVerb(verb);
mozuClient.setResourceUrl(url);
mozuClient.setBody(note);
return mozuClient;
}
/**
* Modifies an existing note for a customer account.
* <p><pre><code>
* MozuClient<com.mozu.api.contracts.customer.CustomerNote> mozuClient=<API key>( note, accountId, noteId);
* client.setBaseAddress(url);
* client.executeRequest();
* CustomerNote customerNote = client.Result();
* </code></pre></p>
* @param accountId Unique identifier of the customer account.
* @param noteId Unique identifier of a particular note to retrieve.
* @param note Properties of a note configured for a customer account.
* @return Mozu.Api.MozuClient <com.mozu.api.contracts.customer.CustomerNote>
* @see com.mozu.api.contracts.customer.CustomerNote
* @see com.mozu.api.contracts.customer.CustomerNote
*/
public static MozuClient<com.mozu.api.contracts.customer.CustomerNote> <API key>(com.mozu.api.contracts.customer.CustomerNote note, Integer accountId, Integer noteId) throws Exception
{
return <API key>( note, accountId, noteId, null);
}
/**
* Modifies an existing note for a customer account.
* <p><pre><code>
* MozuClient<com.mozu.api.contracts.customer.CustomerNote> mozuClient=<API key>( note, accountId, noteId, responseFields);
* client.setBaseAddress(url);
* client.executeRequest();
* CustomerNote customerNote = client.Result();
* </code></pre></p>
* @param accountId Unique identifier of the customer account.
* @param noteId Unique identifier of a particular note to retrieve.
* @param responseFields Use this field to include those fields which are not included by default.
* @param note Properties of a note configured for a customer account.
* @return Mozu.Api.MozuClient <com.mozu.api.contracts.customer.CustomerNote>
* @see com.mozu.api.contracts.customer.CustomerNote
* @see com.mozu.api.contracts.customer.CustomerNote
*/
public static MozuClient<com.mozu.api.contracts.customer.CustomerNote> <API key>(com.mozu.api.contracts.customer.CustomerNote note, Integer accountId, Integer noteId, String responseFields) throws Exception
{
MozuUrl url = com.mozu.api.urls.commerce.customer.accounts.CustomerNoteUrl.<API key>(accountId, noteId, responseFields);
String verb = "PUT";
Class<?> clz = com.mozu.api.contracts.customer.CustomerNote.class;
MozuClient<com.mozu.api.contracts.customer.CustomerNote> mozuClient = (MozuClient<com.mozu.api.contracts.customer.CustomerNote>) MozuClientFactory.getInstance(clz);
mozuClient.setVerb(verb);
mozuClient.setResourceUrl(url);
mozuClient.setBody(note);
return mozuClient;
}
/**
* Removes a note from the specified customer account.
* <p><pre><code>
* MozuClient mozuClient=<API key>( accountId, noteId);
* client.setBaseAddress(url);
* client.executeRequest();
* </code></pre></p>
* @param accountId Unique identifier of the customer account.
* @param noteId Unique identifier of a particular note to retrieve.
* @return Mozu.Api.MozuClient
*/
public static MozuClient <API key>(Integer accountId, Integer noteId) throws Exception
{
MozuUrl url = com.mozu.api.urls.commerce.customer.accounts.CustomerNoteUrl.<API key>(accountId, noteId);
String verb = "DELETE";
MozuClient mozuClient = (MozuClient) MozuClientFactory.getInstance();
mozuClient.setVerb(verb);
mozuClient.setResourceUrl(url);
return mozuClient;
}
}
|
using System;
using System.Linq;
namespace CapnProto.Schema.Parser
{
class CapnpVisitor
{
protected Boolean mEnableNestedType = true;
protected CapnpModule mActiveModule;
protected void EnableNestedType()
{
mEnableNestedType = true;
}
protected void DisableNestedType()
{
mEnableNestedType = false;
}
public virtual CapnpType Visit(CapnpType target)
{
if (target == null) return null;
return target.Accept(this);
}
protected internal virtual CapnpType VisitPrimitive(CapnpPrimitive primitive)
{
return primitive;
}
protected internal virtual CapnpType VisitList(CapnpList list)
{
list.Parameter = Visit(list.Parameter);
return list;
}
protected internal virtual Value VisitValue(Value value)
{
return value;
}
protected internal virtual CapnpModule VisitModule(CapnpModule module)
{
// An imported module has already been processed.
if (mActiveModule != null && mActiveModule != module) return module;
mActiveModule = module;
module.Structs = module.Structs.Select(s => VisitStruct(s)).ToArray();
module.Interfaces = module.Interfaces.Select(i => VisitInterface(i)).ToArray();
module.Constants = module.Constants.Select(c => VisitConst(c)).ToArray();
module.Enumerations = module.Enumerations.Select(e => VisitEnum(e)).ToArray();
module.AnnotationDefs = module.AnnotationDefs.Select(a => VisitAnnotationDecl(a)).ToArray();
module.Usings = module.Usings.Select(u => VisitUsing(u)).ToArray();
module.Annotations = module.Annotations.Select(a => VisitAnnotation(a)).ToArray();
return module;
}
protected internal virtual Annotation VisitAnnotation(Annotation annotation)
{
if (annotation == null) return null;
annotation.Declaration = Visit(annotation.Declaration);
annotation.Argument = VisitValue(annotation.Argument);
return annotation;
}
protected internal virtual CapnpStruct VisitStruct(CapnpStruct @struct)
{
if (!mEnableNestedType) return @struct;
@struct.Structs = @struct.Structs.Select(s => VisitStruct(s)).ToArray();
@struct.Interfaces = @struct.Interfaces.Select(i => VisitInterface(i)).ToArray();
DisableNestedType();
@struct.Enumerations = @struct.Enumerations.Select(e => VisitEnum(e)).ToArray();
@struct.Fields = @struct.Fields.Select(f => VisitField(f)).ToArray();
@struct.AnnotationDefs = @struct.AnnotationDefs.Select(ad => VisitAnnotationDecl(ad)).ToArray();
@struct.Annotations = @struct.Annotations.Select(a => VisitAnnotation(a)).ToArray();
@struct.Usings = @struct.Usings.Select(u => VisitUsing(u)).ToArray();
@struct.Constants = @struct.Constants.Select(c => VisitConst(c)).ToArray();
EnableNestedType();
return @struct;
}
protected internal virtual CapnpInterface VisitInterface(CapnpInterface @interface)
{
if (!mEnableNestedType) return @interface;
@interface.Structs = @interface.Structs.Select(s => VisitStruct(s)).ToArray();
@interface.Interfaces = @interface.Interfaces.Select(i => VisitInterface(i)).ToArray();
DisableNestedType();
@interface.Enumerations = @interface.Enumerations.Select(e => VisitEnum(e)).ToArray();
@interface.BaseInterfaces = @interface.BaseInterfaces.Select(i => Visit(i)).ToArray();
@interface.AnnotationDefs = @interface.AnnotationDefs.Select(ad => VisitAnnotationDecl(ad)).ToArray();
@interface.Annotations = @interface.Annotations.Select(a => VisitAnnotation(a)).ToArray();
@interface.Methods = @interface.Methods.Select(m => VisitMethod(m)).ToArray();
@interface.Usings = @interface.Usings.Select(u => VisitUsing(u)).ToArray();
@interface.Constants = @interface.Constants.Select(c => VisitConst(c)).ToArray();
EnableNestedType();
return @interface;
}
protected internal virtual <API key> <API key>(<API key> @param)
{
return @param;
}
protected internal virtual <API key> VisitClosedType(<API key> closed)
{
closed.OpenType = (CapnpNamedType)Visit(closed.OpenType);
if (closed.ParentScope != null)
closed.ParentScope = VisitClosedType(closed.ParentScope);
return closed;
}
protected internal virtual CapnpEnum VisitEnum(CapnpEnum @enum)
{
@enum.Annotations = @enum.Annotations.Select(a => VisitAnnotation(a)).ToArray();
@enum.Enumerants = @enum.Enumerants.Select(e => VisitEnumerant(e)).ToArray();
return @enum;
}
protected internal virtual Enumerant VisitEnumerant(Enumerant e)
{
e.Annotation = VisitAnnotation(e.Annotation);
return e;
}
protected internal virtual Field VisitField(Field fld)
{
fld.Type = Visit(fld.Type);
fld.Value = VisitValue(fld.Value);
fld.Annotation = VisitAnnotation(fld.Annotation);
return fld;
}
protected internal virtual Method VisitMethod(Method method)
{
if (method.Arguments.Params != null)
method.Arguments.Params = method.Arguments.Params.Select(p => VisitParameter(p)).ToArray();
else
method.Arguments.Struct = Visit(method.Arguments.Struct);
if (method.ReturnType.Params != null)
method.ReturnType.Params = method.ReturnType.Params.Select(p => VisitParameter(p)).ToArray();
else
method.ReturnType.Struct = Visit(method.ReturnType.Struct);
method.Annotation = VisitAnnotation(method.Annotation);
return method;
}
protected internal virtual Parameter VisitParameter(Parameter p)
{
p.Type = Visit(p.Type);
p.Annotation = VisitAnnotation(p.Annotation);
p.DefaultValue = VisitValue(p.DefaultValue);
return p;
}
protected internal virtual CapnpGroup VisitGroup(CapnpGroup grp)
{
grp.Fields = grp.Fields.Select(f => VisitField(f)).ToArray();
return grp;
}
protected internal virtual CapnpUnion VisitUnion(CapnpUnion union)
{
union.Fields = union.Fields.Select(u => VisitField(u)).ToArray();
return union;
}
protected internal virtual CapnpType VisitReference(CapnpReference @ref)
{
return @ref;
}
protected internal virtual CapnpConst VisitConst(CapnpConst @const)
{
@const.Value = VisitValue(@const.Value);
return @const;
}
protected internal virtual CapnpType VisitImport(CapnpImport import)
{
import.Type = Visit(import.Type);
return import;
}
protected internal virtual CapnpUsing VisitUsing(CapnpUsing @using)
{
@using.Target = Visit(@using.Target);
return @using;
}
protected internal virtual CapnpAnnotation VisitAnnotationDecl(CapnpAnnotation annotation)
{
annotation.ArgumentType = Visit(annotation.ArgumentType);
return annotation;
}
}
}
|
$:.unshift(File.dirname(__FILE__)) unless
$:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__)))
require 'rake'
require 'rake/tasklib'
require '<API key>/redmine_helper'
require '<API key>/general_task'
require '<API key>/environment_task'
require '<API key>/database_task'
require '<API key>/cucumber_task'
require '<API key>/metrics_task'
require '<API key>/rdoc_task'
require '<API key>/release_task'
require '<API key>/rspec_task'
require '<API key>/stats_task'
require '<API key>/test_unit_task'
module <API key>
VERSION = '0.0.4'
@@options = { }
class Base
include Singleton
attr_accessor :project_name
attr_accessor :tasks
attr_accessor :plugin_root
attr_accessor :redmine_root
attr_accessor :default_task
attr_accessor :plugin
# :plugin_root => File.expand_path(File.dirname(__FILE__))
def self.setup(options = { }, &block)
plugin = self.instance
plugin.project_name = 'undefined'
plugin.tasks = [:db, :doc, :spec, :cucumber, :release, :clean, :test, :stats]
plugin.plugin_root = '.'
plugin.redmine_root = ENV["REDMINE_ROOT"] || File.expand_path(File.dirname(__FILE__) + '/../../../')
plugin.default_task = :doc
plugin.instance_eval(&block)
<API key>::EnvironmentTask.new(:environment)
plugin.tasks.each do |task|
case task
when :db
<API key>::DatabaseTask.new(:db)
when :doc
<API key>::RDocTask.new(:doc)
when :spec
<API key>::RspecTask.new(:spec)
when :test
<API key>::TestUnitTask.new(:test)
when :cucumber
<API key>::CucumberTask.new(:features)
when :release
<API key>::ReleaseTask.new(:release)
when :stats
<API key>::StatsTask.new(:stats)
when :metrics
<API key>::MetricsTask.new(:metrics)
when :clean
require 'rake/clean'
CLEAN.include('**/semantic.cache', "**/#{plugin.project_name}.zip", "**/#{plugin.project_name}.tar.gz")
end
end
task :default => plugin.default_task
end
end
end
|
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http:
<html xmlns="http:
<head>
<title>Nitrogen 2.x Documentation</title>
<meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1"/>
<meta name="title" content="Nitrogen 2.x Documentation"/>
<meta name="generator" content="Org-mode"/>
<meta name="generated" content="2012-10-31 21:51:19 CDT"/>
<meta name="author" content="Rusty Klophaus (@rustyio)"/>
<meta name="description" content=""/>
<meta name="keywords" content=""/>
<style type="text/css">
<!--/*--><![CDATA[/*><!--*/
html { font-family: Times, serif; font-size: 12pt; }
.title { text-align: center; }
.todo { color: red; }
.done { color: green; }
.tag { background-color: #add8e6; font-weight:normal }
.target { }
.timestamp { color: #bebebe; }
.timestamp-kwd { color: #5f9ea0; }
.right {margin-left:auto; margin-right:0px; text-align:right;}
.left {margin-left:0px; margin-right:auto; text-align:left;}
.center {margin-left:auto; margin-right:auto; text-align:center;}
p.verse { margin-left: 3% }
pre {
border: 1pt solid #AEBDCC;
background-color: #F3F5F7;
padding: 5pt;
font-family: courier, monospace;
font-size: 90%;
overflow:auto;
}
table { border-collapse: collapse; }
td, th { vertical-align: top; }
th.right { text-align:center; }
th.left { text-align:center; }
th.center { text-align:center; }
td.right { text-align:right; }
td.left { text-align:left; }
td.center { text-align:center; }
dt { font-weight: bold; }
div.figure { padding: 0.5em; }
div.figure p { text-align: center; }
div.inlinetask {
padding:10px;
border:2px solid gray;
margin:10px;
background: #ffffcc;
}
textarea { overflow-x: auto; }
.linenr { font-size:smaller }
.code-highlighted {background-color:#ffff00;}
.<API key> { border-style:none; }
#<API key> { font-size:10px; font-weight:bold;
white-space:nowrap; }
.<API key> {background-color:#ffff00; color:#000000;
font-weight:bold; }
-->
</style>
<LINK href="stylesheet.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
<!--/*--><![CDATA[/*><!--*/
function CodeHighlightOn(elem, id)
{
var target = document.getElementById(id);
if(null != target) {
elem.cacheClassElem = elem.className;
elem.cacheClassTarget = target.className;
target.className = "code-highlighted";
elem.className = "code-highlighted";
}
}
function CodeHighlightOff(elem, id)
{
var target = document.getElementById(id);
if(elem.cacheClassElem)
elem.className = elem.cacheClassElem;
if(elem.cacheClassTarget)
target.className = elem.cacheClassTarget;
}
//-->
</script>
</head>
<body>
<div id="preamble">
</div>
<div id="content">
<h1 class="title">Nitrogen 2.x Documentation</h1>
<p><a href="./index.html">Getting Started</a> | <a href="./api.html">API</a> | <a href="./elements.html">Elements</a> | <b>Actions</b> | <a href="./validators.html">Validators</a> | <a href="./handlers.html">Handlers</a> | <a href="./config.html">Configuration Options</a> | <a href="./about.html">About</a>
</p>
<div class=headline>Nitrogen Actions</div>
<div id="table-of-contents">
<h2>Table of Contents</h2>
<div id="<API key>">
<ul>
<li><a href="#sec-1">1 Base Action</a></li>
<li><a href="#sec-2">2 Page Manipulation</a></li>
<li><a href="#sec-3">3 Effects</a></li>
<li><a href="#sec-4">4 Feedback</a></li>
<li><a href="#sec-5">5 See Also</a></li>
</ul>
</div>
</div>
<div id="outline-container-1" class="outline-2">
<h2 id="sec-1"><span class="section-number-2">1</span> Base Action</h2>
<div class="outline-text-2" id="text-1">
<ul>
<li><a href="./actions/base.html">Base Action</a> - All actions contain these attributes.
</li>
</ul>
</div>
</div>
<div id="outline-container-2" class="outline-2">
<h2 id="sec-2"><span class="section-number-2">2</span> Page Manipulation</h2>
<div class="outline-text-2" id="text-2">
<ul>
<li><a href="./actions/event.html">Event</a>
</li>
<li><a href="./actions/script.html">Script</a>
</li>
<li><a href="./actions/validate.html">Validate</a>
</li>
<li><a href="./actions/clear_validation.html">Clear Validation</a>
</li>
<li><a href="./actions/api.html">Ajax API</a>
</li>
</ul>
</div>
</div>
<div id="outline-container-3" class="outline-2">
<h2 id="sec-3"><span class="section-number-2">3</span> Effects</h2>
<div class="outline-text-2" id="text-3">
<ul>
<li><a href="./actions/show.html">Show</a>
</li>
<li><a href="./actions/hide.html">Hide</a>
</li>
<li><a href="./actions/appear.html">Appear</a>
</li>
<li><a href="./actions/fade.html">Fade</a>
</li>
<li><a href="./actions/slide_down.html">Slide Down</a>
</li>
<li><a href="./actions/slide_up.html">Slide Up</a>
</li>
<li><a href="./actions/animate.html">Animate</a>
</li>
<li><a href="./actions/toggle.html">Toggle</a>
</li>
<li><a href="./actions/effect.html">Effect</a>
</li>
<li><a href="./actions/add_class.html">Add Class</a>
</li>
<li><a href="./actions/remove_class.html">Remove Class</a>
</li>
<li><a href="./actions/disable.html">Disable</a>
</li>
</ul>
</div>
</div>
<div id="outline-container-4" class="outline-2">
<h2 id="sec-4"><span class="section-number-2">4</span> Feedback</h2>
<div class="outline-text-2" id="text-4">
<ul>
<li><a href="./actions/alert.html">Alert</a>
</li>
<li><a href="./actions/confirm.html">Confirm</a>
</li>
<li><a href="./actions/other.html">Other</a>
</li>
</ul>
</div>
</div>
<div id="outline-container-5" class="outline-2">
<h2 id="sec-5"><span class="section-number-2">5</span> See Also</h2>
<div class="outline-text-2" id="text-5">
<ul>
<li><a href="./paths.html">Nitrogen Element Paths</a>
</li>
</ul>
</div>
</div>
</div>
<div id="postamble">
<p class="date">Date: 2012-10-31 21:51:19 CDT</p>
<p class="author">Author: Rusty Klophaus (@rustyio)</p>
<p class="creator">Org version 7.8.02 with Emacs version 23</p>
<a href="http://validator.w3.org/check?uri=referer">Validate XHTML 1.0</a>
</div><h2>Comments</h2>
<b>Note:</b><!-- Disqus does not currently support Erlang for its syntax highlighting, so t-->To specify <!--Erlang--> code blocks, just use the generic code block syntax: <pre><b><pre><code>your code here</code></pre></b></pre>
<br />
<br />
<div id="disqus_thread"></div>
<script type="text/javascript">
/* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */
var disqus_shortname = 'nitrogenproject'; // required: replace example with your forum shortname
var disqus_identifier = 'html/actions.html'; //This will be replaced with the path part of the url
/* * * DON'T EDIT BELOW THIS LINE * * */
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js';
(document.<API key>('head')[0] || document.<API key>('body')[0]).appendChild(dsq);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
<a href="http://disqus.com" class="dsq-brlink">comments powered by <span class="logo-disqus">Disqus</span></a>
</body>
</html>
|
.dividend-wrap {
display: none;
}
.dividend-wrap.active {
display: flex;
width: 100%;
}
.overflow.dividendModal > form input::-<API key> { /* Chrome/Opera/Safari */
opacity: .8;
color: #fff;
font-size: 14px;
}
.overflow.dividendModal > form input::-moz-placeholder { /* Firefox 19+ */
opacity: .8;
color: #fff;
font-size: 14px;
}
.overflow.dividendModal > form input:-moz-placeholder { /* Firefox 18- */
opacity: .8;
color: #fff;
font-size: 14px;
}
.overflow.dividendModal > form input:-<API key> { /* IE 10+ */
opacity: .8;
color: #fff;
font-size: 14px;
}
|
package pipe.actions.gui;
import pipe.controllers.PetriNetController;
import pipe.controllers.PlaceController;
import uk.ac.imperial.pipe.models.petrinet.Connectable;
import uk.ac.imperial.pipe.models.petrinet.Place;
import java.awt.event.MouseEvent;
import java.util.Map;
/**
* Abstract action responsible for adding and deleting tokens to places
*/
public abstract class TokenAction extends CreateAction {
/**
*
* @param name image name
* @param tooltip tooltip message
* @param key keyboard shortcut
* @param modifiers keyboard accelerator
* @param applicationModel current PIPE application model
*/
public TokenAction(String name, String tooltip, int key, int modifiers, <API key> applicationModel) {
super(name, tooltip, key, modifiers, applicationModel);
}
/**
* Noop action when a component has not been clicked on
* @param event mouse event
* @param petriNetController controller for the petri net
*/
@Override
public void doAction(MouseEvent event, PetriNetController petriNetController) {
// Do nothing unless clicked a connectable
}
/**
* Performs the subclass token action on the place
* @param connectable item clicked
* @param petriNetController controller for the petri net
*/
@Override
public void doConnectableAction(Connectable connectable, PetriNetController petriNetController) {
//TODO: Maybe a method, connectable.containsTokens() or visitor pattern
if (connectable instanceof Place) {
Place place = (Place) connectable;
String <API key>.getSelectedToken();
performTokenAction(petriNetController.getPlaceController(place), token);
}
}
/**
* Subclasses should perform their relevant action on the token e.g. add/delete
*
* @param placeController
* @param token
*/
protected abstract void performTokenAction(PlaceController placeController, String token);
/**
* Sets the place to contain counts.
* <p/>
* Creates a new history edit
*
* @param placeController
* @param counts
*/
protected void setTokenCounts(PlaceController placeController, Map<String, Integer> counts) {
placeController.setTokenCounts(counts);
}
}
|
layout: page
title: Adding Atom to Your Dotfiles
Keeping all your dotfiles and system configurations together, under version control, and stored somewhere accessible (say on GitHub) is a good practice. It allows you to easily access and install everything from bash/zsh settings to environment variables to git aliases (and more) across all your machines. Plus others can use clever bits and pieces from your dotfiles in their own. Why not include your Atom files (those in `~/.atom`) in all of this?
If you don't know what dotfiles are or you don't already have your own dotfiles setup, [GitHub can help get you up to speed](http://dotfiles.github.io/).
## What to include
We recommend that you store `config.cson`, `init.coffee`, `keymap.cson`, `snippets.cson`, and `styles.less` in your dotfiles. The `packages/` and `storage/` directories should not be included. In fact you will even want to add them to your `.gitignore` file.
## How to include them
There are as many ways to include these in your dotfiles as there are ways to setup your dotfiles. We are not going to go through all of them here. A common approach to having a dotfile configuration installed is with symlinks. This is the approach we will discuss.
First, figure out the naming scheme for directories that is used by your installation script. It is likely either `directory.symlink` or `.directory`.
Move the `~/.atom` directory to your dotfiles directory renaming it according to the appropriate naming scheme. For example,
mv ~/.atom ~/.dotfiles/atom.symlink
Following the naming scheme is important because that is the basis on which your installation script will decide what to symlink.
Now test out that things are working properly. Run your installation script and then check if there again exists `~/.atom`. If you run `ls -la ~` you should be able to see if it is there. You will also notice that it tells you the directory that it is symlinked to. Success.
You can now commit the files we discussed above to your dotfiles repository. At this point you should be all set and ready to go.
## Concerns
You may be wondering if there is any risk in committing certain data from `config.cson` to a public repository. Values like the `userId` values under `exception-reporting` and `metric` might look like they contain sensitive information. Fortunately, these are hashed values that won't reveal anything sensitive ([exception-reporting source](https:
|
var Type = require("@kaoscript/runtime").Type;
module.exports = function(expect) {
class Shape {
constructor() {
this.__ks_init();
this.__ks_cons(arguments);
}
__ks_init_0() {
this._color = "";
}
__ks_init() {
Shape.prototype.__ks_init_0.call(this);
}
__ks_cons_0(color) {
if(arguments.length < 1) {
throw new SyntaxError("Wrong number of arguments (" + arguments.length + " for 1)");
}
if(color === void 0 || color === null) {
throw new TypeError("'color' is not nullable");
}
else if(!Type.isString(color)) {
throw new TypeError("'color' is not of type 'String'");
}
this._color = color;
}
__ks_cons(args) {
if(args.length === 1) {
Shape.prototype.__ks_cons_0.apply(this, args);
}
else {
throw new SyntaxError("Wrong number of arguments");
}
}
__ks_func_color_0() {
return this._color;
}
color() {
if(arguments.length === 0) {
return Shape.prototype.__ks_func_color_0.apply(this);
}
throw new SyntaxError("Wrong number of arguments");
}
__ks_func_draw_0() {
return "I'm drawing a " + this._color + " rectangle.";
}
draw() {
if(arguments.length === 0) {
return Shape.prototype.__ks_func_draw_0.apply(this);
}
throw new SyntaxError("Wrong number of arguments");
}
}
Shape.prototype.__ks_cons_1 = function() {
this._color = "red";
};
Shape.prototype.__ks_cons = function(args) {
if(args.length === 0) {
Shape.prototype.__ks_cons_1.apply(this);
}
else if(args.length === 1) {
Shape.prototype.__ks_cons_0.apply(this, args);
}
else {
throw new SyntaxError("Wrong number of arguments");
}
}
let shape = new Shape();
expect(shape.draw()).to.equals("I'm drawing a red rectangle.");
};
|
module TasksFileMutations
AddFilesToTask = GraphQL::Relay::Mutation.define do
name 'AddFilesToTask'
input_field :id, !types.ID
return_field :task, TaskType
resolve -> (_root, inputs, ctx) {
task = <API key>.<API key>(inputs['id'], ctx['ability'])
files = [ctx[:file]].flatten.reject{ |f| f.blank? }
if task.is_a?(Task) && !files.empty?
task.add_files(files)
end
{ task: task }
}
end
RemoveFilesFromTask = GraphQL::Relay::Mutation.define do
name 'RemoveFilesFromTask'
input_field :id, !types.ID
input_field :filenames, types[types.String]
return_field :task, TaskType
resolve -> (_root, inputs, ctx) {
task = <API key>.<API key>(inputs['id'], ctx['ability'])
filenames = inputs['filenames']
if task.is_a?(Task) && !filenames.empty?
task.remove_files(filenames)
end
{ task: task }
}
end
end
|
package uk.co.nevarneyok.entities.product;
import com.google.gson.annotations.SerializedName;
public class ProductSize {
private long id;
@SerializedName("remote_id")
private long remoteId;
private String value;
public ProductSize() {
}
public ProductSize(long id, long remoteId, String value) {
this.id = id;
this.remoteId = remoteId;
this.value = value;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getRemoteId() {
return remoteId;
}
public void setRemoteId(long remoteId) {
this.remoteId = remoteId;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ProductSize that = (ProductSize) o;
if (id != that.id) return false;
if (remoteId != that.remoteId) return false;
return !(value != null ? !value.equals(that.value) : that.value != null);
}
@Override
public int hashCode() {
int result = (int) (id ^ (id >>> 32));
result = 31 * result + (int) (remoteId ^ (remoteId >>> 32));
result = 31 * result + (value != null ? value.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "ProductSize{" +
"id=" + id +
", remoteId=" + remoteId +
", value='" + value + '\'' +
'}';
}
}
|
# -*- coding: utf-8 -*-
"""
json
"""
import requests
import json
import os
from word.models import (Word, EnDefinition, CnDefinition, Audio, Pronunciation, Example, Note)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
print(BASE_DIR)
def process_data(data):
data = data['data']['reviews']
print('len', len(data))
for item in data:
content = item['content']
print('uk_audio', item['uk_audio'])
print('us_audio', item['us_audio'])
obj = Word.objects.create(content=content)
if item['uk_audio']:
uk_audio_filepath = save_files('uk', item['content'], item['uk_audio'])
if item['us_audio']:
us_audio_filepath = save_files('us', item['content'], item['us_audio'])
if filepath is not None:
pass
Audio.objects.create(word=obj, us_audio=us_audio_filepath, uk_audio=uk_audio_filepath)
def save_files(tp, word, url):
filepath = '%s/media/audio/%stp/%s.mp3' % (BASE_DIR, tp, word)
with open(BASE_DIR + '/media/audio/'+ tp +'/'+word+'.mp3', 'wb') as handle:
response = requests.get(url, stream=True)
if response.ok:
# Something went wrong
for block in response.iter_content(1024):
handle.write(block)
return filepath
return None
def serialize_data(file_name):
with open(file_name, 'r') as f:
data = json.loads(f.read())
process_data(data)
# data = requests.get('', stream=True)
if __name__ == "__main__":
serialize_data("data1.json")
|
layout: post
title: All Roads Lead to Shenzhen (for Electronics)
excerpt: "An account of my first visit to Shenzhen, China - the modern day Mecca of electronics manufacturing."
tags: [electronics, Shenzhen, China]
categories: [Electronics]
comments: true
modified: 2015-01-17
thumbnail: images/2016/01/shenzhen-bldg.jpg
images: images/2016/01/shenzhen-bldg.jpg
image:
feature: header.jpg
*This is a brief account of my four day visit in January 2016 to Shenzhen,
China. Due to my unfamiliarity with the language and brevity of
the trip, this is only a superficial perspective.*

## Why Shenzhen?
If you are doing anything related to electronics today, you will come
to know about Shenzhen soon enough. In my case, [snapVCC][1], a
product that I succesfully crowd-funded recently, brought me
here. Although it was not a requirement for me to be present here for
production, I decided to make the trip to get a feel for the place -
especially considering future projects.
## Getting There
Here's a brief overview of the formalities involved in getting to
Shenzhen - from an Indian point of view.
Chinese Visa
I applied for a visa through a travel agent in Bangalore, since the
Chinese consulate is in Mumbai. The visa fee was INR 8000 (plus the
travel agent charged a small fee). I applied for a *business* visa,
and the only supporting docunent I needed was an invitation letter
from Seeed Studio, the company that's manufacturing my product in
Shenzhen. I got the visa in hand in about a week - a single entry
visa valid for three months.
Tickets
When I asked around, I was advised to fly to Hong Kong and take ground
transportation rather than fly directly to Shenzhen. Ticket prices from
Bangalore to Shenzhen ranged from around INR 25000 to 35000,
depending on airlines, dates and stop-overs. I opted for a direct
flight - a five hour journey. I think you can do it on the cheap if
you don't mind breaking your journey and are flexible with dates.
Currency
The currency in China is Chinese Yuan (CNY), but it's more commonly
referred to with its older name RMB. A quick approximate conversion
to INR is to just multiply CNY by 10. I took USD from India and
converted it in Hong Kong. The conversion rate of Hong Kong Dollar to
INR is about 7.5 at the moment.
Crossing from Hong Kong
Immigration at Hong Kong was straightforward. I just needed to fill a
form, and there was no visa as such for short visits from India. I
then collected my luggage and followed the "transport to mainland"
signs. I opted for a "limo service" which is actually a shared taxi. I
had my Shenzhen hotel address printed in Chinese characters (using
google Translate), so all I had to is point to it, and pay 200 HKD at
the counter. They slapped a sticker on to my jacket (which probably said
"illiterate man") and I was handed over to an attendant who shooed me
towards the taxi gates. From then on, I was in "point and sign" mode.

The "limo" was actually a van which takes a driver plus seven
passengers. I was wedged between two passengers in the middle
row. After my initial bewildrement, I had a nice conversation (in
English) with the fellow to my left - an Engineer from Taiwan who
worked for Foxconn. The driver provided us with yellow immigration
forms to fill, and in less than hour, we were at the border. We first
passed through the Hong Kong gates, and then the Chinese gates. In
both cases, we did not need to get out of the car. The officers just
inspected out passports and peered into the car which had the
interiors lighst on and the doors open. The taxis all had their trunks
open, but in our case atleast, there was no inspection. Once we
crossed the Chinese border, the taxi went into a mall where passengers
were switched to other cars based on their Shenzhen destinations. In
another 20 minutes, I was dropped off at my hotel.
Hotel
I wanted to stay close to the electronics markets, and I (mostly by
accident) ended up choosing the Shenzhen Shanghai Hotel, which was at
a walking distance to the Huaqiangbei markets. The cost of the room
was about 500 RMB per night, which did not include a meal plan. My room was
nice and cozy and the service in general was good. The buffet breakfast was
atrociously bad, though. Definitely not worth the 75 RMB charge.
## Shenzhen
Shenzhen is one of China's first Special Economic Zones set up in the
1980s and has grown to become the world's destination for electronics
manufacturing. Shenzhen is a huge city, and I visited only
parts of Futian, Nanshan, and Luohu districts during my stay.
Getting Around

You can get around Shenzhen in a taxi, but using the metro or bus is much
cheaper. I used the metro, and found it to be very convenient. You can
buy subway tokens at all stations, and the main menu has an English
option which you can use. The machines I saw accepted only 5 Yuan
notes or coins. A better option (which I plan to try next time) is to
buy a *Shenzhen Tong Card* - a prepaid card that be used for both the
bus and the metro. If you do take a taxi, ask for a *fa-piao* - a "tax
receipt" - this apparently reduces the chance that you will be
overcharged for the trip.
Food
Being a vegetarian (not vegan) my expectation was that I was screwed
in China as far food goes. But this was actually not the case.

As long as I was with someone who
could speak Mandarin, I got excellent vegetarian food. Left to myself,
I exercised my pathetic point and mime skills, and usually ended up
with weird stuff like tentacles on noodles. But even then I was always
able to drown my (temporary) sorrow in a bottle of Tsingtao and some
fried Tofu. I had learned the phrases *wo chi su* (I eat vegetables.)
and *wo bu chi roe* (I don't eat meat.) - but Chinese language is
*tonal* which meant that most of the time people just stared at my
(apparent) gibberish, and I beat a hasty retreat to sign language.
Language
As I was preparing for the trip, one of my friends who had travelled
in China remarked - "you will get to experience what illiteracy
means". It's not just that I was in a place where I didn't know the
local language - I had travelled in Thailand, Cambodia and
Indonesia. But those were tourist friendly destinations where it was
easy to find someone who spoke English. But in Shezhen, the isolation
was complete. I had no idea what I was looking at - almost all shop
signs were in Chinese, and hardly anyone spoke English.
Technology can help, *Pleco* is an app I found to be useful - it
provides an off-line translation from English to Chinese, including
pronunciation. But this app can be confusing as well. A given English
word can have multiple translations and most may make no sense for
your particular situation.You can also use google to translate the
Chinese characters. I am sure there's plenty of other software you
could use to do similar things.
One useful thing to learn (thanks Charles, for teaching me) is Chinese
hand gestures for numbers:

*(Image credit: https://pdsworldservice.files.wordpress.com/2013/06/<API key>.jpg)*
By the way, Shenzhen is pronounced more like *shen-jen* rather than
*shen-zen*.
Safety
During my trip, I found the Chinese people to be friendly and Shenzhen
streets to be safe. I routinely walked a couple of kilometers back to
the hotel late at night, and I faced no problems whatsoever. Every few
blocks, I saw Police kiosks and a uniformed officer. The streets were
so brightly lit at some places that it felt like daylight at 11:30 PM.
Internet
As you might have heard, a lot of the internet that you take for
granted (Facebook, Twitter, Google services, etc.) are blocked in
China. But almost everyone I met used VPN software, so it's important to
set one up before making the trip. Another idea is to get a SIM from
Hong Kong for your phone, have in on roaming, and you have unfiltered
internet on your phone in Shenzhen for the duration of your trip.
Visit to Seeed Studio
The primary purpose of my trip was to be at Seeed Studio in time
for the production of snapVCC.

Seeed is in Xili, which was a 40 minute ride by taxi from my hotel,
and cost about 80 RMB. I won't go into details of my Seeed visit
here, except to say that they are a great bunch of people, and that I
was very happy to be present to see the first pieces of snapVCC come
out of production.
Haquiangbei Electronics Market
One of the big attractions of Shenzhen is the Haquiangbei (HQB)
electronics market. For folks from Bangalore, think of it as
$$(S.P.Road)^N$$ where $$N$$ is a very large number. A good guide to
this area is the *Shenzhen Map for Makers* created by Seeed Studio,
the PDF for which is available free online. When I was in town they also
gave me a printed copy, which was very handy.

You can think of HQB as a big spread of multi-storied malls densely
packed with shops selling all kinds of electronics - right from
discrete components to fully assembled computers. There are zones for
specific components - power supplies or motors, for instance. The most
impressive sight in that area is the 70+ storied SEG building, the
first 8 floors of which consist of electronics markets, and the rest
filled with restaurants, offices and such. It was so tall that I could used
the building as a marker to orient myself as I walked around it that
area.

One interesting sight outside HQB malls is stalls selling remote
controlled drones. These can be as cheap as 100 RMB. It's great fun to
watch the sellers fly these things - they can make them shoot up to
the sky and do all kinds of crazy maneuvers. Added to this is their
sales pitch. My seller stood on top of a drone to demonstrate its
crash recoverability. So of course I bought one.
Looking at HQB, you understand why so many companies from the west
have operations here. Need a reel of MOSFETs for your assembly line? No
problem - just walk to HQB and get one. It's like buying vegetables in
a supermarket.
Ian & HQB Hackers
I was in touch with Ian (of *Dangerous Prototypes* fame) who has his
base in Shenzhen now. He was kind enough to connect me with his
HQB hacker group on *WeChat*. Every evening we hung out in the HQB area
and I great fun speaking to folks from US, Germany, Australia and
other places who were using the Shenzhen infrastructure to work on
their projects.

If you are in the HQB area, I'd be happy to put you in touch with Ian's group.
Sightseeing
Although most folks come to Shenzhen for electronics, the place offers
plenty of sightseeing opportunites as well. One place I visited is the
Dafen oil painting village, where I purchased a couple of paintings by
local artists.

I wanted to visit the Fairly Lake botanical gardens, but didn't have
time. It's supposed to be one of the most beautful parks in China. Do
check the wikitravel guide to Shenzhen for other suggestions.
## Conclusion
Although my trip was short, a visit to Shenzhen gave me a much clearer
picture of its electronics manufacturing infrastructure. I hope to leverage
my knowledge and contacts for future projects. Looking forward to my
next visit!
## References
1. [Wikitravel guide to Shenzhen][2]
[1]: https:
[2]: http://wikitravel.org/en/Shenzhen
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>wCMF 4.1: Member List</title>
<meta name="generator" content="Doxygen 1.8.17"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="A MDSD framework for building reliable, maintainable and extendable web applications with PHP">
<meta name="keywords" content="PHP, web application framework, model driven development">
<meta name="author" content="wemove digital solutions">
<link rel="shortcut icon" href="theme/images/favicon.ico">
<script src="jquery.js"></script>
<script src="theme/vendor/popper/popper.min.js"></script>
<script src="theme/vendor/bootstrap/js/bootstrap.min.js"></script>
<link href="theme/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link href="theme/vendor/fontawesome/css/all.min.css" rel="stylesheet">
<script src="theme/vendor/bootstrap-toc/bootstrap-toc.min.js"></script>
<link href="theme/vendor/bootstrap-toc/bootstrap-toc.min.css" rel="stylesheet">
<script src="theme/vendor/<API key>/<API key>.min.js"></script>
<script src="theme/vendor/highlight/highlight.pack.js"></script>
<link href="theme/vendor/highlight/styles/solarized-dark.css" rel="stylesheet">
<script src="theme/js/application.js"></script>
<script src="dynsections.js"></script>
<link href="theme/css/style.css" rel="stylesheet">
</head>
<body data-spy="scroll" data-target="#toc">
<nav class="navbar navbar-expand-lg navbar-dark bg-dark sticky-top">
<a class="navbar-brand" href="index.html">wCMF 4.1</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggler" aria-controls="navbarToggler" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarToggler">
<ul class="navbar-nav mr-auto mt-2 mt-lg-0">
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="<API key>" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<i class="far fa-hand-point-right"></i> Guides <b class="caret"></b>
</a>
<div class="dropdown-menu" aria-labelledby="<API key>">
<a class="dropdown-item" href="gettingstarted.html">Getting started</a>
<a class="dropdown-item" href="architecture.html">Architecture</a>
<a class="dropdown-item" href="model.html">Model</a>
<a class="dropdown-item" href="persistence.html">Persistence</a>
<a class="dropdown-item" href="presentation.html">Presentation</a>
<a class="dropdown-item" href="configuration.html">Configuration</a>
<a class="dropdown-item" href="security.html">Security</a>
<a class="dropdown-item" href="i18n_l10n.html">I18n & l10n</a>
<a class="dropdown-item" href="tests.html">Tests</a>
</div>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="<API key>" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<i class="fas fa-tags"></i> Versions <b class="caret"></b>
</a>
<div class="dropdown-menu" aria-labelledby="<API key>">
<a class="dropdown-item" href="4.1/index.html">4.1.x</a>
<a class="dropdown-item" href="4.0/index.html">4.0.x</a>
</div>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="apiDropdownMenuLink" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<i class="fas fa-file-alt"></i> API <b class="caret"></b>
</a>
<div class="dropdown-menu" aria-labelledby="apiDropdownMenuLink">
<a class="dropdown-item" href="annotated.html">Classes</a>
<a class="dropdown-item" href="hierarchy.html">Hierarchy</a>
</div>
</li>
<li class="nav-item"><a class="nav-link" href="https://github.com/iherwig/wcmf"><i class="fab fa-github"></i> Code</a></li>
<li class="nav-item"><a class="nav-link" href="support.html"><i class="fas fa-life-ring"></i> Support</a></li>
</ul>
<form class="form-inline my-2 my-lg-0">
<input id="search-field" class="form-control mr-sm-2" type="search" placeholder="Search API" disabled>
</form>
</div>
</nav>
<a class="anchor" id="top"></a>
<div class="content" id="content">
<div class="container">
<div class="row mt-4">
<div id="toc-container" class="col-lg-3 d-none d-lg-block d-none">
<nav id="toc" class="sticky-top"></nav>
</div>
<div id="content-container" class="col-md-12 col-lg-12">
<div>
<!-- end header part --><!-- Generated by Doxygen 1.8.17 -->
<script type="text/javascript">
//var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="namespacewcmf.html">wcmf</a></li><li class="navelem"><a class="el" href="<API key>.html">lib</a></li><li class="navelem"><a class="el" href="<API key>.html">config</a></li><li class="navelem"><a class="el" href="<API key>.html">impl</a></li><li class="navelem"><a class="el" href="<API key>.html"><API key></a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="headertitle">
<div class="title"><API key> Member List</div> </div>
</div><!--header
<div class="contents">
<p>This is the complete list of members for <a class="el" href="<API key>.html"><API key></a>, including all inherited members.</p>
<table class="directory">
<tr class="even"><td class="entry"><a class="el" href="<API key>.html#<API key>">__construct</a>(Configuration $configuration, $configSection)</td><td class="entry"><a class="el" href="<API key>.html"><API key></a></td><td class="entry"></td></tr>
<tr><td class="entry"><a class="el" href="<API key>.html#<API key>">containsKey</a>($actionKey)</td><td class="entry"><a class="el" href="<API key>.html"><API key></a></td><td class="entry"></td></tr>
<tr class="even"><td class="entry"><a class="el" href="<API key>.html#<API key>">getId</a>()</td><td class="entry"><a class="el" href="<API key>.html"><API key></a></td><td class="entry"></td></tr>
<tr><td class="entry"><a class="el" href="<API key>.html#<API key>">getKeyValue</a>($actionKey)</td><td class="entry"><a class="el" href="<API key>.html"><API key></a></td><td class="entry"></td></tr>
</table></div><!-- contents -->
<!-- start footer part -->
</div>
</div>
</div>
</div>
<hr>
<footer>
<div class="container">
<div class="row">
<div class="col-md-9">
<small>© 2020 <a href="http:
Generated on Mon Dec 21 2020 22:40:28 for wCMF by &
</div>
</div>
</div>
</footer>
<!-- Matomo -->
<script type="text/javascript">
var _paq = _paq || [];
/* tracker methods like "setCustomDimension" should be called before "trackPageView" */
_paq.push(['trackPageView']);
_paq.push(['enableLinkTracking']);
(function() {
var u="https://piwik.wemove.com/";
_paq.push(['setTrackerUrl', u+'piwik.php']);
_paq.push(['setSiteId', '7']);
var d=document, g=d.createElement('script'), s=d.<API key>('script')[0];
g.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'piwik.js'; s.parentNode.insertBefore(g,s);
})();
</script>
<noscript><img src="https://piwik.wemove.com/piwik.php?idsite=7&rec=1" style="border:0" alt="" /></noscript>
<!-- End Matomo -->
</body>
</html>
|
.icons > [class^="icon-"] {
position: relative;
text-align: left;
font-size: 32px;
}
.icons > [class^="icon-"] > span {
display: none;
padding: 20px 23px 18px 23px;
background: #00101c;
width: auto;
color: #fff;
font-family: 'Roboto', Arial, sans-serif;
font-size: 16px;
}
.icons > [class^="icon-"]:hover > span {
display: block;
position: absolute;
top: -64px;
right: 35px;
white-space: nowrap;
z-index: 5;
}
.arrow-down {
width: 0;
height: 0;
border-left: 10px solid transparent;
border-right: 10px solid transparent;
display: none;
border-top: 10px solid #00101c;
}
.icons > [class^="icon-"]:hover > .arrow-down {
display: block;
position: absolute;
top: -10px;
right: 50px;
}
|
<?php namespace System\Classes;
use App;
use Url;
use File;
use Lang;
use Event;
use Cache;
use Route;
use Config;
use Request;
use Response;
use Assetic\Asset\FileAsset;
use Assetic\Asset\GlobAsset;
use Assetic\Asset\AssetCache;
use Assetic\Asset\AssetCollection;
use Assetic\Factory\AssetFactory;
use October\Rain\Parse\Assetic\FilesystemCache;
use System\Helpers\Cache as CacheHelper;
use <API key>;
use DateTime;
class CombineAssets
{
use \October\Rain\Support\Traits\Singleton;
/**
* @var array A list of known JavaScript extensions.
*/
protected static $jsExtensions = ['js'];
/**
* @var array A list of known StyleSheet extensions.
*/
protected static $cssExtensions = ['css', 'less', 'scss', 'sass'];
/**
* @var array Aliases for asset file paths.
*/
protected $aliases = [];
/**
* @var array Bundles that are compiled to the filesystem.
*/
protected $bundles = [];
/**
* @var array Filters to apply to each file.
*/
protected $filters = [];
/**
* @var string The local path context to find assets.
*/
protected $localPath;
/**
* @var string The output folder for storing combined files.
*/
protected $storagePath;
/**
* @var bool Cache untouched files.
*/
public $useCache = false;
/**
* @var bool Compress (minify) asset files.
*/
public $useMinify = false;
/**
* @var bool When true, cache will be busted when an import is modified.
* Enabling this feature will make page loading slower.
*/
public $useDeepHashing = false;
/**
* @var array Cache of registration callbacks.
*/
private static $callbacks = [];
/**
* Constructor
*/
public function init()
{
/*
* Register preferences
*/
$this->useCache = Config::get('cms.enableAssetCache', false);
$this->useMinify = Config::get('cms.enableAssetMinify', null);
$this->useDeepHashing = Config::get('cms.<API key>', null);
if ($this->useMinify === null) {
$this->useMinify = !Config::get('app.debug', false);
}
if ($this->useDeepHashing === null) {
$this->useDeepHashing = Config::get('app.debug', false);
}
/*
* Register JavaScript filters
*/
$this->registerFilter('js', new \October\Rain\Parse\Assetic\JavascriptImporter);
/*
* Register CSS filters
*/
$this->registerFilter('css', new \Assetic\Filter\CssImportFilter);
$this->registerFilter(['css', 'less', 'scss'], new \Assetic\Filter\CssRewriteFilter);
$this->registerFilter('less', new \October\Rain\Parse\Assetic\LessCompiler);
$this->registerFilter('scss', new \October\Rain\Parse\Assetic\ScssCompiler);
/*
* Minification filters
*/
if ($this->useMinify) {
$this->registerFilter('js', new \Assetic\Filter\JSMinFilter);
$this->registerFilter(['css', 'less', 'scss'], new \October\Rain\Parse\Assetic\StylesheetMinify);
}
/*
* Common Aliases
*/
$this->registerAlias('jquery', '~/modules/backend/assets/js/vendor/jquery.min.js');
$this->registerAlias('framework', '~/modules/system/assets/js/framework.js');
$this->registerAlias('framework.extras', '~/modules/system/assets/js/framework.extras.js');
$this->registerAlias('framework.extras', '~/modules/system/assets/css/framework.extras.css');
/*
* Deferred registration
*/
foreach (static::$callbacks as $callback) {
$callback($this);
}
}
/**
* Combines JavaScript or StyleSheet file references
* to produce a page relative URL to the combined contents.
*
* $assets = [
* 'assets/vendor/mustache/mustache.js',
* 'assets/js/vendor/jquery.ui.widget.js',
* 'assets/js/vendor/canvas-to-blob.js',
* ];
*
* CombineAssets::combine($assets, base_path('plugins/acme/blog'));
*
* @param array $assets Collection of assets
* @param string $localPath Prefix all assets with this path (optional)
* @return string URL to contents.
*/
public static function combine($assets = [], $localPath = null)
{
return self::instance()->prepareRequest($assets, $localPath);
}
/**
* Combines a collection of assets files to a destination file
*
* $assets = [
* 'assets/less/header.less',
* 'assets/less/footer.less',
* ];
*
* CombineAssets::combineToFile(
* $assets,
* base_path('themes/website/assets/theme.less'),
* base_path('themes/website')
* );
*
* @param array $assets Collection of assets
* @param string $destination Write the combined file to this location
* @param string $localPath Prefix all assets with this path (optional)
* @return void
*/
public function combineToFile($assets = [], $destination, $localPath = null)
{
// Disable cache always
$this->storagePath = null;
list($assets, $extension) = $this->prepareAssets($assets);
$rewritePath = File::localToPublic(dirname($destination));
$combiner = $this->prepareCombiner($assets, $rewritePath);
$contents = $combiner->dump();
File::put($destination, $contents);
}
/**
* Returns the combined contents from a prepared cache identifier.
* @param string $cacheKey Cache identifier.
* @return string Combined file contents.
*/
public function getContents($cacheKey)
{
$cacheInfo = $this->getCache($cacheKey);
if (!$cacheInfo) {
throw new <API key>(Lang::get('system::lang.combiner.not_found', ['name'=>$cacheKey]));
}
$this->localPath = $cacheInfo['path'];
$this->storagePath = storage_path('cms/combiner/assets');
/*
* Analyse cache information
*/
$lastModifiedTime = gmdate("D, d M Y H:i:s \G\M\T", array_get($cacheInfo, 'lastMod'));
$etag = array_get($cacheInfo, 'etag');
$mime = (array_get($cacheInfo, 'extension') == 'css')
? 'text/css'
: 'application/javascript';
/*
* Set 304 Not Modified header, if necessary
*/
header_remove();
$response = Response::make();
$response->header('Content-Type', $mime);
$response->header('Cache-Control', 'private, max-age=604800');
$response->setLastModified(new DateTime($lastModifiedTime));
$response->setEtag($etag);
$response->setPublic();
$modified = !$response->isNotModified(App::make('request'));
/*
* Request says response is cached, no code evaluation needed
*/
if ($modified) {
$this-><API key>($cacheKey);
$combiner = $this->prepareCombiner($cacheInfo['files']);
$contents = $combiner->dump();
$response->setContent($contents);
}
return $response;
}
/**
* Prepares an array of assets by normalizing the collection
* and processing aliases.
* @param array $assets
* @return array
*/
protected function prepareAssets(array $assets)
{
if (!is_array($assets)) {
$assets = [$assets];
}
/*
* Split assets in to groups.
*/
$combineJs = [];
$combineCss = [];
foreach ($assets as $asset) {
/*
* Allow aliases to go through without an extension
*/
if (substr($asset, 0, 1) == '@') {
$combineJs[] = $asset;
$combineCss[] = $asset;
continue;
}
$extension = File::extension($asset);
if (in_array($extension, self::$jsExtensions)) {
$combineJs[] = $asset;
continue;
}
if (in_array($extension, self::$cssExtensions)) {
$combineCss[] = $asset;
continue;
}
}
/*
* Determine which group of assets to combine.
*/
if (count($combineCss) > count($combineJs)) {
$extension = 'css';
$assets = $combineCss;
}
else {
$extension = 'js';
$assets = $combineJs;
}
/*
* Apply registered aliases
*/
if ($aliasMap = $this->getAliases($extension)) {
foreach ($assets as $key => $asset) {
if (substr($asset, 0, 1) !== '@') {
continue;
}
$_asset = substr($asset, 1);
if (isset($aliasMap[$_asset])) {
$assets[$key] = $aliasMap[$_asset];
}
}
}
return [$assets, $extension];
}
/**
* Combines asset file references of a single type to produce
* a URL reference to the combined contents.
* @param array $assets List of asset files.
* @param string $localPath File extension, used for aesthetic purposes only.
* @return string URL to contents.
*/
protected function prepareRequest(array $assets, $localPath = null)
{
if (substr($localPath, -1) != '/') {
$localPath = $localPath.'/';
}
$this->localPath = $localPath;
$this->storagePath = storage_path('cms/combiner/assets');
list($assets, $extension) = $this->prepareAssets($assets);
/*
* Cache and process
*/
$cacheKey = $this->getCacheKey($assets);
$cacheInfo = $this->useCache ? $this->getCache($cacheKey) : false;
if (!$cacheInfo) {
$this-><API key>($cacheKey);
$combiner = $this->prepareCombiner($assets);
if ($this->useDeepHashing) {
$factory = new AssetFactory($this->localPath);
$lastMod = $factory->getLastModified($combiner);
}
else {
$lastMod = $combiner->getLastModified();
}
$cacheInfo = [
'version' => $cacheKey.'-'.$lastMod,
'etag' => $cacheKey,
'lastMod' => $lastMod,
'files' => $assets,
'path' => $this->localPath,
'extension' => $extension
];
$this->putCache($cacheKey, $cacheInfo);
}
return $this->getCombinedUrl($cacheInfo['version']);
}
/**
* Returns the combined contents from a prepared cache identifier.
* @param array $assets List of asset files.
* @param string $rewritePath
* @return string Combined file contents.
*/
protected function prepareCombiner(array $assets, $rewritePath = null)
{
/*
* Extensibility
*/
Event::fire('cms.combiner.beforePrepare', [$this, $assets]);
$files = [];
$filesSalt = null;
foreach ($assets as $asset) {
$filters = $this->getFilters(File::extension($asset)) ?: [];
$path = file_exists($asset) ? $asset : File::symbolizePath($asset, null) ?: $this->localPath . $asset;
$files[] = new FileAsset($path, $filters, public_path());
$filesSalt .= $this->localPath . $asset;
}
$filesSalt = md5($filesSalt);
$collection = new AssetCollection($files, [], $filesSalt);
$collection->setTargetPath($this->getTargetPath($rewritePath));
if ($this->storagePath === null) {
return $collection;
}
if (!File::isDirectory($this->storagePath)) {
@File::makeDirectory($this->storagePath);
}
$cache = new FilesystemCache($this->storagePath);
$cachedFiles = [];
foreach ($files as $file) {
$cachedFiles[] = new AssetCache($file, $cache);
}
$cachedCollection = new AssetCollection($cachedFiles, [], $filesSalt);
$cachedCollection->setTargetPath($this->getTargetPath($rewritePath));
return $cachedCollection;
}
/**
* Busts the cache based on a different cache key.
* @return void
*/
protected function <API key>($hash)
{
$allFilters = <API key>('array_merge', $this->getFilters());
foreach ($allFilters as $filter) {
if (method_exists($filter, 'setHash')) {
$filter->setHash($hash);
}
}
}
/**
* Returns a deep hash on filters that support it.
* @param array $assets List of asset files.
* @return void
*/
protected function <API key>($assets)
{
$key = '';
$assetFiles = array_map(function ($file) {
return file_exists($file) ? $file : File::symbolizePath($file, null) ?: $this->localPath . $file;
}, $assets);
foreach ($assetFiles as $file) {
$filters = $this->getFilters(File::extension($file));
foreach ($filters as $filter) {
if (method_exists($filter, 'hashAsset')) {
$key .= $filter->hashAsset($file, $this->localPath);
}
}
}
return $key;
}
/**
* Returns the URL used for accessing the combined files.
* @param string $outputFilename A custom file name to use.
* @return string
*/
protected function getCombinedUrl($outputFilename = 'undefined.css')
{
$combineAction = 'System\Classes\Controller@combine';
$actionExists = Route::getRoutes()->getByAction($combineAction) !== null;
if ($actionExists) {
return Url::action($combineAction, [$outputFilename], false);
}
else {
return '/combine/'.$outputFilename;
}
}
/**
* Returns the target path for use with the combiner. The target
* path helps generate relative links within CSS.
*
* /combine returns combine/
* /index.php/combine returns index-php/combine/
*
* @param string|null $path
* @return string The new target path
*/
protected function getTargetPath($path = null)
{
if ($path === null) {
$baseUri = substr(Request::getBaseUrl(), strlen(Request::getBasePath()));
$path = $baseUri.'/combine';
}
if (strpos($path, '/') === 0) {
$path = substr($path, 1);
}
$path = str_replace('.', '-', $path).'/';
return $path;
}
// Registration
/**
* Registers a callback function that defines bundles.
* The callback function should register bundles by calling the manager's
* `registerBundle` method. This instance is passed to the callback
* function as an argument. Usage:
*
* CombineAssets::registerCallback(function($combiner){
* $combiner->registerBundle('~/modules/backend/assets/less/october.less');
* });
*
* @param callable $callback A callable function.
*/
public static function registerCallback(callable $callback)
{
self::$callbacks[] = $callback;
}
// Filters
/**
* Register a filter to apply to the combining process.
* @param string|array $extension Extension name. Eg: css
* @param object $filter Collection of files to combine.
* @return self
*/
public function registerFilter($extension, $filter)
{
if (is_array($extension)) {
foreach ($extension as $_extension) {
$this->registerFilter($_extension, $filter);
}
return;
}
$extension = strtolower($extension);
if (!isset($this->filters[$extension])) {
$this->filters[$extension] = [];
}
if ($filter !== null) {
$this->filters[$extension][] = $filter;
}
return $this;
}
/**
* Clears any registered filters.
* @param string $extension Extension name. Eg: css
* @return self
*/
public function resetFilters($extension = null)
{
if ($extension === null) {
$this->filters = [];
}
else {
$this->filters[$extension] = [];
}
return $this;
}
/**
* Returns filters.
* @param string $extension Extension name. Eg: css
* @return self
*/
public function getFilters($extension = null)
{
if ($extension === null) {
return $this->filters;
}
elseif (isset($this->filters[$extension])) {
return $this->filters[$extension];
}
else {
return null;
}
}
// Bundles
/**
* Registers bundle.
* @param string|array $files Files to be registered to bundle
* @param string $destination Destination file will be compiled to.
* @param string $extension Extension name. Eg: css
* @return self
*/
public function registerBundle($files, $destination = null, $extension = null)
{
if (!is_array($files)) {
$files = [$files];
}
$firstFile = array_values($files)[0];
if ($extension === null) {
$extension = File::extension($firstFile);
}
$extension = strtolower(trim($extension));
if ($destination === null) {
$file = File::name($firstFile);
$path = dirname($firstFile);
$preprocessors = array_except(self::$cssExtensions, 'css');
if (in_array($extension, $preprocessors)) {
$cssPath = $path.'/../css';
if (
in_array(strtolower(basename($path)), $preprocessors) &&
File::isDirectory(File::symbolizePath($cssPath))
) {
$path = $cssPath;
}
$destination = $path.'/'.$file.'.css';
}
else {
$destination = $path.'/'.$file.'-min.'.$extension;
}
}
$this->bundles[$extension][$destination] = $files;
return $this;
}
/**
* Returns bundles.
* @param string $extension Extension name. Eg: css
* @return self
*/
public function getBundles($extension = null)
{
if ($extension === null) {
return $this->bundles;
}
elseif (isset($this->bundles[$extension])) {
return $this->bundles[$extension];
}
else {
return null;
}
}
// Aliases
/**
* Register an alias to use for a longer file reference.
* @param string $alias Alias name. Eg: framework
* @param string $file Path to file to use for alias
* @param string $extension Extension name. Eg: css
* @return self
*/
public function registerAlias($alias, $file, $extension = null)
{
if ($extension === null) {
$extension = File::extension($file);
}
$extension = strtolower($extension);
if (!isset($this->aliases[$extension])) {
$this->aliases[$extension] = [];
}
$this->aliases[$extension][$alias] = $file;
return $this;
}
/**
* Clears any registered aliases.
* @param string $extension Extension name. Eg: css
* @return self
*/
public function resetAliases($extension = null)
{
if ($extension === null) {
$this->aliases = [];
}
else {
$this->aliases[$extension] = [];
}
return $this;
}
/**
* Returns aliases.
* @param string $extension Extension name. Eg: css
* @return self
*/
public function getAliases($extension = null)
{
if ($extension === null) {
return $this->aliases;
}
elseif (isset($this->aliases[$extension])) {
return $this->aliases[$extension];
}
else {
return null;
}
}
// Cache
/**
* Stores information about a asset collection against
* a cache identifier.
* @param string $cacheKey Cache identifier.
* @param array $cacheInfo List of asset files.
* @return bool Successful
*/
protected function putCache($cacheKey, array $cacheInfo)
{
$cacheKey = 'combiner.'.$cacheKey;
if (Cache::has($cacheKey)) {
return false;
}
$this->putCacheIndex($cacheKey);
Cache::forever($cacheKey, base64_encode(serialize($cacheInfo)));
return true;
}
/**
* Look up information about a cache identifier.
* @param string $cacheKey Cache identifier
* @return array Cache information
*/
protected function getCache($cacheKey)
{
$cacheKey = 'combiner.'.$cacheKey;
if (!Cache::has($cacheKey)) {
return false;
}
return @unserialize(@base64_decode(Cache::get($cacheKey)));
}
/**
* Builds a unique string based on assets
* @param array $assets Asset files
* @return string Unique identifier
*/
protected function getCacheKey(array $assets)
{
$cacheKey = $this->localPath . implode('|', $assets);
/*
* Deep hashing
*/
if ($this->useDeepHashing) {
$cacheKey .= $this-><API key>($assets);
}
/*
* Extensibility
*/
$dataHolder = (object) ['key' => $cacheKey];
Event::fire('cms.combiner.getCacheKey', [$this, $dataHolder]);
$cacheKey = $dataHolder->key;
return md5($cacheKey);
}
/**
* Resets the combiner cache
* @return void
*/
public static function resetCache()
{
if (Cache::has('combiner.index')) {
$index = (array) @unserialize(@base64_decode(Cache::get('combiner.index'))) ?: [];
foreach ($index as $cacheKey) {
Cache::forget($cacheKey);
}
Cache::forget('combiner.index');
}
CacheHelper::instance()->clearCombiner();
}
/**
* Adds a cache identifier to the index store used for
* performing a reset of the cache.
* @param string $cacheKey Cache identifier
* @return bool Returns false if identifier is already in store
*/
protected function putCacheIndex($cacheKey)
{
$index = [];
if (Cache::has('combiner.index')) {
$index = (array) @unserialize(@base64_decode(Cache::get('combiner.index'))) ?: [];
}
if (in_array($cacheKey, $index)) {
return false;
}
$index[] = $cacheKey;
Cache::forever('combiner.index', base64_encode(serialize($index)));
return true;
}
}
|
raspi led
> basic LED interactions on a raspberry pi

# Setup
Follow the base setup of the johnny-five LED example

# Usage
`Make sure you do these steps on a raspberry pi`
* install prerequisites `sudo apt-get install wiringpi` (might crash if you don't have git)
* install dependencies (`yarn` seems to cause errors, use `npm install` instead)
* run the code with root priviledges ``sudo `which node` index``
* see your LED blinking
> You can also use [remote-code](https://github.com/anoff/remote-code) if you don't want to work manually on your pi.
|
<?php
## CREATE APPLICATION DEFINITIONS ##
define('APPLICATION', 'application');
define('CONFIG', 'config');
define('CONTROLLER', 'controllers');
define('CORE', 'core');
define('DS', DIRECTORY_SEPARATOR);
define('ERRORS', 'errors');
define('LIBRARY', 'libraries');
define('MODEL', 'models');
define('RUN', true);
define('PHP', '.php');
define('VIEW', 'views');
## GET UTILITIES ##
require_once(APPLICATION.DS.CORE.DS.'Utilities'.PHP);
## BOOTSTRAP ##
load_class('Logging', CORE);
load_class('Controller', CORE);
load_class('Security', CORE);
load_class('Router', CORE);
|
#include "<API key>.h"
#include <iostream>
#include <fstream>
#include <algorithm>
#include "boost\filesystem.hpp"
using namespace std;
namespace bst = boost::filesystem;
<API key>::~<API key>()
{
}
<API key>::<API key>(std::string folderName)
{
noOfFiles = 0;
noOfTrainingFiles = 0;
noOfScoringFiles = 0;
this->malwareFamilyName = folderName;
}
void <API key>::getFileList() {
string folderName = "D:/Aditya/CS_266/Project/Dataset/" + this->malwareFamilyName + "/";
cout << folderName << endl;
bst::path p(folderName);
for (auto i = bst::directory_iterator(p); i != bst::directory_iterator(); i++)
{
if (!bst::is_directory(i->path()))
{
string fullFileName = folderName + i->path().filename().string();
this->fileNameList.push_back(fullFileName);
}
}
}
void <API key>::getFileStream()
{
this->noOfFiles = this->fileNameList.size();
for (int index = 0; index < this->noOfFiles; index++)
{
vector<int> tempFileStream;
vector<string> opCodeStream;
string tempFileName = this->fileNameList.at(index);
ifstream tempReadFile;
tempReadFile.open(tempFileName);
string line;
while (getline(tempReadFile, line))
{
int opCodeIndex = find(this->distinctOpCodesList.begin(), this->distinctOpCodesList.end(), line) - this->distinctOpCodesList.begin();
int endIndex = this->distinctOpCodesList.size();
if (opCodeIndex != endIndex)
{
tempFileStream.push_back(opCodeIndex);
}
else
{
this->distinctOpCodesList.push_back(line);
int newOpCodeIndex = this->distinctOpCodesList.size()-1;
tempFileStream.push_back(newOpCodeIndex);
}
opCodeStream.push_back(line);
}
this->obsSequenceList.push_back(tempFileStream);
}
cout << this->distinctOpCodesList.size();
}
|
'use strict'
angular
.module('softvApp')
.controller('ModalAddhubCtrl', function (clusterFactory, tapFactory, $rootScope, areaTecnicaFactory, $uibModalInstance, opcion, ngNotify, $state) {
function init() {
if (opcion.opcion === 1) {
vm.blockForm2 = true;
muestraColonias();
muestrarelaciones();
vm.Titulo = 'Nuevo HUB';
} else if (opcion.opcion === 2) {
areaTecnicaFactory.GetConHub(opcion.id, '', '', 3).then(function (data) {
console.log();
vm.blockForm2 = false;
var hub = data.GetConHubResult[0];
vm.Clv_Txt = hub.Clv_txt;
vm.Titulo = 'Editar HUB - '+hub.Clv_txt;
vm.Descripcion = hub.Descripcion;
vm.clv_hub = hub.Clv_Sector;
muestraColonias();
muestrarelaciones();
});
}
else if (opcion.opcion === 3) {
areaTecnicaFactory.GetConHub(opcion.id, '', '', 3).then(function (data) {
vm.blockForm2 = true;
vm.blocksave = true;
var hub = data.GetConHubResult[0];
vm.Clv_Txt = hub.Clv_txt;
vm.Titulo = 'Consultar HUB - '+hub.Clv_txt;
vm.Descripcion = hub.Descripcion;
vm.clv_hub = hub.Clv_Sector;
muestraColonias();
muestrarelaciones();
});
}
}
function muestraColonias() {
areaTecnicaFactory.<API key>(0, 0, 0)
.then(function (data) {
vm.colonias = data.<API key>;
});
}
function AddSector() {
if (opcion.opcion === 1) {
areaTecnicaFactory.GetNueHub(0, vm.Clv_Txt, vm.Descripcion).then(function (data) {
if (data.GetNueHubResult > 0) {
vm.clv_hub = data.GetNueHubResult;
ngNotify.set('El HUB se ha registrado correctamente ,ahora puedes agregar la relación con las colonias', 'success');
$rootScope.$broadcast('reloadlista');
vm.blockForm2 = false;
vm.blocksave = true;
} else {
ngNotify.set('La clave del HUB ya existe', 'error');
}
});
} else if (opcion.opcion === 2) {
areaTecnicaFactory.GetModHub(vm.clv_hub, vm.Clv_Txt, vm.Descripcion).then(function (data) {
console.log(data);
ngNotify.set('El HUB se ha editado correctamente', 'success');
$rootScope.$broadcast('reloadlista');
$uibModalInstance.dismiss('cancel');
});
}
}
function cancel() {
$uibModalInstance.dismiss('cancel');
}
function validaRelacion(clv) {
var count = 0;
vm.RelColonias.forEach(function (item) {
count += (item.IdColonia === clv) ? 1 : 0;
});
return (count > 0) ? true : false;
}
function <API key>() {
if (validaRelacion(vm.Colonia.IdColonia) === true) {
ngNotify.set('La relación HUB-COLONIA ya esta establecida', 'warn');
return;
}
areaTecnicaFactory.GetNueRelHubColonia(vm.clv_hub, vm.Colonia.IdColonia)
.then(function (data) {
muestrarelaciones();
ngNotify.set('se agrego la relación correctamente', 'success');
});
}
function muestrarelaciones() {
areaTecnicaFactory.GetConRelHubColonia(vm.clv_hub)
.then(function (rel) {
console.log(rel);
vm.RelColonias = rel.<API key>;
});
}
function deleterelacion(clv) {
clusterFactory.<API key>(2, vm.clv_cluster, clv).then(function (data) {
ngNotify.set('Se eliminó la relación correctamente', 'success');
muestrarelaciones();
});
}
var vm = this;
init();
vm.cancel = cancel;
vm.clv_hub = 0;
vm.RelColonias = [];
vm.AddSector = AddSector;
vm.<API key> = <API key>;
});
|
require 'spec_helper'
require 'rails_helper'
require 'email_helper'
describe CommitteeController do
fixtures :users
fixtures :meetings
fixtures :committees
fixtures :announcements
fixtures :participations
before(:each) do
sign_in users(:tester)
# allow to do production mode
allow(Rails).to receive(:env).and_return(ActiveSupport::StringInquirer.new('production'))
@committee = Committee.create!({name: "Nice", hidden: true, inactive: true})
@test_admin = User.find_by(name: "Rspec_admin")
@test_committee = Committee.find_by(name: "Nice")
end
describe 'new committee' do
it 'renders the new committee template' do
get :new_committee
expect(response).to render_template("new_committee")
end
# it 'redirects non-admin users' do
# sign_in users(:user)
# get :new_committee
# expect(response).to redirect_to root_path
# sign_out users(:user)
# end
end
describe 'create committee' do
it 'redirects to the committee index page' do
post :create_committee, params: {committee: {name: "Good Committee"}}
expect(response).to redirect_to(<API key>)
end
it 'should not allow a blank name field' do
post :create_committee, params: {committee: {name: ""}}
expect(flash[:notice]).to eq("Committee name field cannot be blank.")
expect(response).to redirect_to(new_committee_path)
end
it 'should not allow an already used committee name field' do
expect(Committee).to receive(:has_name?).with("Good Committee").and_return(true)
post :create_committee, params: {committee: {name: "Good Committee"}}
expect(flash[:notice]).to eq("Committee name provided already exists. Please enter a different name.")
expect(response).to redirect_to(new_committee_path)
end
it 'creates a committee' do
expect(Committee).to receive(:create!).with(name: "Good Committee", :description => nil, :hidden => true, :inactive => true)
post :create_committee, params: {committee: {name: "Good Committee"}}
expect(flash[:notice]).to eq("Committee Good Committee was successfully created!")
end
it 'redirects non-admin users' do
sign_in users(:user)
post :create_committee, params: {committee: {name: "Good Committee"}}
expect(response).to redirect_to <API key>
sign_out users(:user)
end
end
describe 'CRUD create committee' do
it 'redirects to the committee index page' do
post :crud_committee, params: {committee: {name: "Good Committee"}, do_action: "create"}
expect(response).to redirect_to(<API key>)
end
it 'should not allow a blank name field' do
post :crud_committee, params: {committee: {name: ""}, do_action: "create"}
expect(flash[:notice]).to eq("Committee name field cannot be blank.")
expect(response).to redirect_to(new_committee_path)
end
it 'should not allow an already used committee name field' do
expect(Committee).to receive(:has_name?).with("Good Committee").and_return(true)
post :crud_committee, params: {committee: {name: "Good Committee"}, do_action: "create"}
expect(flash[:notice]).to eq("Committee name provided already exists. Please enter a different name.")
expect(response).to redirect_to(new_committee_path)
end
it 'creates a committee' do
expect(Committee).to receive(:create!).with(name: "Good Committee", :description => nil, :hidden => true, :inactive => true)
post :crud_committee, params: {committee: {name: "Good Committee"}, do_action: "create"}
expect(flash[:notice]).to eq("Committee Good Committee was successfully created!")
end
it 'redirects non-admin users' do
sign_in users(:user)
post :crud_committee, params: {committee: {name: "Good Committee"}, do_action: "create"}
expect(response).to redirect_to <API key>
sign_out users(:user)
end
end
describe 'edit committee' do
it 'renders the edit committee template' do
get :edit_committee, params: {id: @test_committee.id}
expect(response).to render_template("edit_committee")
end
it 'redirects non-admin users' do
sign_in users(:user)
get :edit_committee, params: {id: @test_committee.id}
expect(response).to redirect_to <API key>
sign_out users(:user)
end
end
describe 'update committee' do
it 'redirects to the committee index page' do
put :update_committee, params: {id: @test_committee.id, committee: {name: "Good Committee"}}
expect(response).to redirect_to(<API key>)
end
it 'should not allow a blank name field' do
put :update_committee, params: {id: @test_committee.id, committee: {name: ""}}
expect(flash[:notice]).to eq("Please fill in the committee name field.")
expect(response).to redirect_to(edit_committee_path)
end
it 'should not allow an already used committee name field' do
expect(Committee).to receive(:has_name?).with("Nice").and_return true
put :update_committee, params: {id: @test_committee.id, committee: {name: "Nice"}}
expect(flash[:notice]).to eq("Committee name provided already exists. Please enter a different name.")
expect(response).to redirect_to(edit_committee_path)
end
it 'updates the committee' do
put :update_committee, params: {id: @test_committee.id, committee: {name: "Good Committee"}}
expect(response).to redirect_to(<API key>)
end
it 'redirects non-admin users' do
sign_in users(:user)
put :update_committee, params: {id: @test_committee.id, committee: {name: "Good Committee"}}
expect(response).to redirect_to <API key>
sign_out users(:user)
end
end
describe 'CRUD update committee' do
it 'redirects to the committee index page' do
put :crud_committee, params: {id: @test_committee.id, committee: {name: "Good Committee"}, do_action: "update"}
expect(response).to redirect_to(<API key>)
end
it 'should not allow a blank name field' do
put :crud_committee, params: {id: @test_committee.id, committee: {name: ""}, do_action: "update"}
expect(flash[:notice]).to eq("Please fill in the committee name field.")
expect(response).to redirect_to(edit_committee_path)
end
it 'should not allow an already used committee name field' do
expect(Committee).to receive(:has_name?).with("Nice").and_return true
put :crud_committee, params: {id: @test_committee.id, committee: {name: "Nice"}, do_action: "update"}
expect(flash[:notice]).to eq("Committee name provided already exists. Please enter a different name.")
expect(response).to redirect_to(edit_committee_path)
end
it 'updates the committee' do
put :crud_committee, params: {id: @test_committee.id, committee: {name: "Good Committee"}, do_action: "update"}
expect(response).to redirect_to(<API key>)
end
it 'updates the committee description' do
put :crud_committee, params: {id: @test_committee.id, committee: {name: "Nice", description: "I am making new description"}, do_action: "update"}
expect(response).to redirect_to(<API key>)
end
it 'redirects non-admin users' do
sign_in users(:user)
put :crud_committee, params: {id: @test_committee.id, committee: {name: "Good Committee"}, do_action: "update"}
expect(response).to redirect_to <API key>
sign_out users(:user)
end
end
describe 'delete committee' do
it 'redirects to the committee index page' do
delete :delete_committee, params: {id: @test_committee.id}
expect(response).to redirect_to(<API key>)
end
it "shows a flash delete message when committee successfully deleted" do
delete :delete_committee, params: {id: @test_committee.id}
expect(flash[:notice]).to eq("Committee with name Nice deleted successfully.")
end
it 'redirects non-admin users' do
sign_in users(:user)
delete :delete_committee, params: {id: @test_committee.id}
expect(response).to redirect_to <API key>
sign_out users(:user)
end
end
describe 'CRUD delete committee' do
it 'redirects to the committee index page' do
delete :crud_committee, params: {id: @test_committee.id, do_action: "delete"}
expect(response).to redirect_to(<API key>)
end
it "shows a flash delete message when committee successfully deleted" do
delete :crud_committee, params: {id: @test_committee.id, do_action: "delete"}
expect(flash[:notice]).to eq("Committee with name Nice deleted successfully.")
end
it 'redirects non-admin users' do
sign_in users(:user)
delete :crud_committee, params: {id: @test_committee.id, do_action: "delete"}
expect(response).to redirect_to <API key>
sign_out users(:user)
end
end
describe 'hide committee' do
it 'redirects to the committee index page' do
get :action_committee, params: {id: @test_committee.id, do_action: 'hide'}
expect(response).to redirect_to(<API key>)
end
it 'shows a flash message when committee successfully hidden' do
get :action_committee, params: {id: @test_committee.id, do_action: 'hide'}
expect(flash[:notice]).to eq("Nice successfully hidden.")
end
it 'sets the committee\'s hidden attribute to true' do
<API key>(Committee).to receive(:hide)
get :action_committee, params: {id: @test_committee.id, do_action: 'hide'}
end
it 'redirects non-admin users' do
sign_in users(:user)
get :action_committee, params: {id: @test_committee.id, do_action: 'hide'}
expect(response).to redirect_to <API key>
sign_out users(:user)
end
end
describe 'show committee' do
it 'redirects to the committee index page' do
get :action_committee, params: {id: @test_committee.id, do_action: 'show'}
expect(response).to redirect_to(<API key>)
end
it 'shows a flash message when committee successfully shown' do
get :action_committee, params: {id: @test_committee.id, do_action: 'show'}
expect(flash[:notice]).to eq("Nice successfully shown.")
end
it 'sets the committee\'s hidden attribute to false' do
<API key>(Committee).to receive(:show)
get :action_committee, params: {id: @test_committee.id, do_action: 'show'}
end
it 'redirects non-admin users' do
sign_in users(:user)
get :action_committee, params: {id: @test_committee.id, do_action: 'show'}
expect(response).to redirect_to <API key>
sign_out users(:user)
end
end
describe 'activate committee' do
it 'redirects to the committee index page' do
get :action_committee, params: {id: @test_committee.id, do_action: 'active'}
expect(response).to redirect_to(<API key>)
end
it 'shows a flash message when committee successfully active' do
get :action_committee, params: {id: @test_committee.id, do_action: 'active'}
expect(flash[:notice]).to eq("Nice successfully made active.")
end
it 'sets the committee\'s hidden attribute to true' do
<API key>(Committee).to receive(:activate)
get :action_committee, params: {id: @test_committee.id, do_action: 'active'}
end
it 'redirects non-admin users' do
sign_in users(:user)
get :action_committee, params: {id: @test_committee.id, do_action: 'active'}
expect(response).to redirect_to <API key>
sign_out users(:user)
end
end
describe 'Inactivate committee' do
it 'redirects to the committee index page' do
get :action_committee, params: {id: @test_committee.id, do_action: 'inactive'}
expect(response).to redirect_to(<API key>)
end
it 'shows a flash message when committee successfully inactive' do
get :action_committee, params: {id: @test_committee.id, do_action: 'inactive'}
expect(flash[:notice]).to eq("Nice successfully made inactive.")
end
it 'sets the committee\'s hidden attribute to false' do
<API key>(Committee).to receive(:inactivate)
get :action_committee, params: {id: @test_committee.id, do_action: 'inactive'}
end
it 'redirects non-admin users' do
sign_in users(:user)
get :action_committee, params: {id: @test_committee.id, do_action: 'inactive'}
expect(response).to redirect_to <API key>
sign_out users(:user)
end
end
describe 'Add committee member' do
it 'shows a flash message when all members are successfully added to committee' do
test_user = User.find_by(name: "Rspec_user")
test_admin = User.find_by(name: "Rspec_admin")
allow(Rails).to receive(:env).and_return(ActiveSupport::StringInquirer.new('production'))
# puts test_user.id: 227792459
# puts test_admin.id: 1011897928
put :update_members, params: {id: @test_committee.id, check: {"227792459": 1, "1011897928": 1}}
expect(flash[:notice]).to eq("Successfully updated members in #{@test_committee.name}.")
end
it 'remove all the members in committee' do
test_user = User.find_by(name: "Rspec_user")
test_admin = User.find_by(name: "Rspec_admin")
put :update_members, params: {id: @test_committee.id, check: {"227792459": 0, "1011897928": 0}}
expect(flash[:notice]).to eq("Successfully updated members in #{@test_committee.name}.")
end
end
end
|
package permafrost.tundra.math;
import java.text.MessageFormat;
/**
* A collection of convenience methods for working with integers.
*/
public final class IntegerHelper {
/**
* The default value used when parsing a null string.
*/
private static int DEFAULT_INT_VALUE = 0;
/**
* Disallow instantiation of this class.
*/
private IntegerHelper() {}
/**
* Converts the given object to a Integer.
*
* @param object The object to be converted.
* @return The converted object.
*/
public static Integer normalize(Object object) {
Integer value = null;
if (object instanceof Number) {
value = ((Number)object).intValue();
} else if (object instanceof String) {
value = parse((String)object);
}
return value;
}
/**
* Parses the given string as an integer.
*
* @param input A string to be parsed as integer.
* @return Integer representing the given string, or 0 if the given string was null.
*/
public static int parse(String input) {
return parse(input, DEFAULT_INT_VALUE);
}
/**
* Parses the given string as an integer.
*
* @param input A string to be parsed as integer.
* @param defaultValue The value returned if the given string is null.
* @return Integer representing the given string, or defaultValue if the given string is null.
*/
public static int parse(String input, int defaultValue) {
if (input == null) return defaultValue;
return Integer.parseInt(input);
}
/**
* Parses the given strings as integers.
*
* @param input A list of strings to be parsed as integers.
* @return A list of integers representing the given strings.
*/
public static int[] parse(String[] input) {
return parse(input, DEFAULT_INT_VALUE);
}
/**
* Parses the given strings as integers.
*
* @param input A list of strings to be parsed as integers.
* @param defaultValue The value returned if a string in the list is null.
* @return A list of integers representing the given strings.
*/
public static int[] parse(String[] input, int defaultValue) {
if (input == null) return null;
int[] output = new int[input.length];
for (int i = 0; i < input.length; i++) {
output[i] = parse(input[i], defaultValue);
}
return output;
}
/**
* Serializes the given integer as a string.
*
* @param input The integer to be serialized.
* @return A string representation of the given integer.
*/
public static String emit(int input) {
return Integer.toString(input);
}
/**
* Serializes the given integers as strings.
*
* @param input A list of integers to be serialized.
* @return A list of string representations of the given integers.
*/
public static String[] emit(int[] input) {
if (input == null) return null;
String[] output = new String[input.length];
for (int i = 0; i < input.length; i++) {
output[i] = emit(input[i]);
}
return output;
}
}
|
'use strict';
var path = require('path');
var fs = require('fs');
module.exports = function(gen,cb) {
var sections;
if (gen.config.get('framework')==='bigwheel') {
var model = require(path.join(process.cwd(),'src/model/index.js'));
sections = ['Preloader'];
Object.keys(model).forEach(function(key) {
if (key.charAt(0)==="/") sections.push(key.substr(1) || 'Landing');
});
} else {
sections = ['Landing'];
}
nextSection(sections,gen,cb);
};
function nextSection(arr,gen,cb) {
if (arr.length>0) {
createSection(arr.shift(),gen,function() {
nextSection(arr,gen,cb);
});
} else {
if (cb) cb();
}
}
function createSection(cur,gen,cb) {
var name = gen.config.get('sectionNames') ? '{{section}}.js' : 'index.js';
var style = gen.config.get('sectionNames') ? '{{section}}.{{css}}' : 'style.{{css}}';
var count = 0;
var total = 0;
var done = function() {
count++;
if (count>=total) cb();
};
fs.stat('src/sections/'+cur+'/',function(err,stat) {
if (err) {
gen.config.set('section',cur);
if (gen.config.get('framework')==='bigwheel') {
var type = cur==='Preloader' ? 'preloader' : 'normal';
gen.copy('templates/sections/{{framework}}/'+type+'/index.js','src/sections/{{section}}/'+name,done);
gen.copy('templates/sections/{{framework}}/'+type+'/style.css','src/sections/{{section}}/'+style,done);
gen.copy('templates/sections/{{framework}}/'+type+'/template.hbs','src/sections/{{section}}/template.hbs',done);
gen.copy('templates/.gitkeep','src/ui/{{section}}/.gitkeep',done);
total += 4;
} else if (gen.config.get('framework')==='react') {
gen.copy('templates/sections/{{framework}}/index.js','src/sections/{{section}}/'+name,done);
gen.copy('templates/sections/{{framework}}/style.css','src/sections/{{section}}/'+style,done);
total += 2;
}
} else {
done();
}
});
};
|
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>Aarthi Gurusami</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="../stylesheets/stylesheet.css">
<link rel = "stylesheet" type = "text/css" href = "../stylesheets/stylesheet-mobile.css">
<link rel="stylesheet" type="text/css" href="../stylesheets/<API key>.css">
<link rel="stylesheet" type="text/css" href="../stylesheets/<API key>.css">
<script type = "text/javascript" src = "../stylesheets/<API key>.js"></script>
<script type = "text/javascript" src = "../stylesheets/blog-post.js"></script>
</head>
<body>
<nav class = "main_nav">
<ul class="transition">
<li id= "first"><a href="../index.html">home</a>
<li id="second"><a href="../about.html">about</a></li>
<li id="third"><a href="index.html">blog</a></li>
<li id="fourth"><a href="../projects/index.html">projects</a></li>
<li id = "resume"><a href="https://resume.creddle.io/resume/fgzuvelzjsf">resume</a></li>
<li id = "contact"><a href="../contact.html">contact</a></li>
</ul>
</nav>
<header>
<h1>
What's it like to blog?
</h1>
<h2>
04/08/2016.
</h2>
</header>
<main>
<figure>
<img src="imgs/sample-image.png" alt= "">
<br>
<figcaption>
blog.
</figcaption>
</figure>
<p>
I enjoy how much more I learn when I'm blogging for an audience. It helps me understand concepts I was having a lot of trouble with, and I typically find myself wanting to go above and beyond to help them understand new concepts.
</p>
<p>
That being said, it's incredibly cumbersome to go through multiple drafts of the same post, and make sure each line of code is as succinct and "pretty" as it should be for an audience.
</p>
<p>
I learned a lot through this process, both technically and personally. I felt like I developed a fun and interesting blogging style, and had really dig into some creative juices to make these topics interesting. It was a really nice way to combine my new found technical knowledge with my artistic and communication skills!
</p>
<div id = "tabs">
<ul id = "tab">
<li id = "previous"><a href = "">Previous</a></li>
<li id = "next"><a href = "">Next</a></li>
</ul>
</div>
</main>
<footer>
<p>
Aarthi Gurusami
<br>
(607) 738-9214
</p>
</footer>
<nav>
<aside>
<h2>other posts.</h2>
<ul>
<li><a href="git.html">Gits Using Git</a></li>
<li><a href="css-concepts.html">Elements With Benefits</a></li>
<li><a href="arrays-hashes.html">#hashlikeyoumeanit</a></li>
<li><a href="enumerable-methods.html">Paul: Give me my money.</a></li>
<li><a href="ruby-classes.html">I'm drunk.</a></li>
<li><a href="javascript.html">I'm not drunk, but I could be.</a></li>
<li><a href="tech.html">toma[yh]to.</a></li>
</ul>
</aside>
</nav>
</body>
</html>
|
{% extends "../base.html" %}
{% block content %}
<div class="row">
<div class="col-sm-6">
<legend translate>Platform Information</legend>
<!--ajax_result
<div class="ajax_result">
{% if msg %}
<div class="alert alert-info" role="alert">{{msg}}</div>
{% endif %}
<table width="100%" class="table table-striped table-hover">
<thead>
<tr>
<th translate>Height</th>
<th translate>Millimeter</th>
<th translate>Pulse</th>
</tr>
</thead>
<tbody>
<tr>
<td translate>Zero Level</td>
<td>0</td>
<td>0</td>
</tr>
<tr class="success">
<td translate>Current</td>
<td><b>{{CurrentHeightMm}}</b></td>
<td><b>{{Status.CurrentHeight}}</b></td>
</tr>
<tr>
<td translate>End Level</td>
<td><b>{{ZAxisHeightMm}}</b></td>
<td><b>{{Config.ZAxisHeight}}</b></td>
</tr>
</tbody>
</table>
{% if ZAxisPin %}
<br>
<a href="/z-axis/touch-limit" type="button" class="btn btn-primary" translate>Calibrate Zero Position ⇧</a>
<br>
<br>
<legend translate>Save Z Axis Calibration</legend>
<a href="/z-axis/calibrate" class="btn btn-danger btn-lg ask" data-ask="measure-confirm" role="button" translate>Measure Z-Axis Length ⇧ </a>
<translate class="hide" id="measure-confirm">Are you sure you want to set this height as the bottom?</translate>
<br>
<br>
{% if ZAxisEnable>0 %}
<a href="/z-axis/enable/1" type="button" class="btn btn-success" translate>Enable Motor</a>
<a href="/z-axis/enable/0" type="button" class="btn btn-warning" translate>Disable Motor</a>
{% endif %}
{% endif %}
</div>
<!--ajax_result
<br><br>
{{ buttonsView(buttons,"/z-calibration") }}
</div>
<div class="col-sm-6">
<legend translate>Move</legend>
<div class="row calibration">
<div class="col-xs-6 right_link">
<a href="/z-axis/bottom" type="button" class="btn btn-danger btn-sm" translate>Floor ⇩</a>
<a href="/z-axis/move/down/micron/200000" type="button" class="btn btn-warning btn-sm">200mm ⇩</a>
<a href="/z-axis/move/down/micron/100000" type="button" class="btn btn-warning btn-sm">100mm ⇩</a>
<a href="/z-axis/move/down/micron/50000" type="button" class="btn btn-warning btn-sm">50mm ⇩</a>
<a href="/z-axis/move/down/micron/10000" type="button" class="btn btn-warning btn-sm">10mm ⇩</a>
<a href="/z-axis/move/down/micron/1000" type="button" class="btn btn-warning btn-sm">1mm ⇩</a>
<a href="/z-axis/move/down/micron/500" type="button" class="btn btn-warning btn-sm">0.5mm ⇩</a>
<a href="/z-axis/move/down/micron/100" type="button" class="btn btn-warning btn-sm">0.1mm ⇩</a>
<a href="/z-axis/move/down/pulse/100" type="button" class="btn btn-warning btn-sm side_left" translate>100 Pulse ⇩</a>
<a href="/z-axis/move/down/pulse/10" type="button" class="btn btn-warning btn-sm side_left" translate>10 Pulse ⇩</a>
<a href="/z-axis/move/down/pulse/1" type="button" class="btn btn-warning btn-sm side_left" translate>1 Pulse ⇩</a>
</div>
<div class="col-xs-6 left_link">
<a href="/z-axis/top" type="button" class="btn btn-primary btn-sm" translate>Top ⇧</a>
<a href="/z-axis/move/up/micron/200000" type="button" class="btn btn-success btn-sm">200mm ⇧</a>
<a href="/z-axis/move/up/micron/100000" type="button" class="btn btn-success btn-sm">100mm ⇧</a>
<a href="/z-axis/move/up/micron/50000" type="button" class="btn btn-success btn-sm">50mm ⇧</a>
<a href="/z-axis/move/up/micron/10000" type="button" class="btn btn-success btn-sm">10mm ⇧</a>
<a href="/z-axis/move/up/micron/1000" type="button" class="btn btn-success btn-sm">1mm ⇧</a>
<a href="/z-axis/move/up/micron/500" type="button" class="btn btn-success btn-sm">0.5mm ⇧</a>
<a href="/z-axis/move/up/micron/100" type="button" class="btn btn-success btn-sm">0.1mm ⇧</a>
<a href="/z-axis/move/up/pulse/100" type="button" class="btn btn-success btn-sm side_right" translate>100 Pulse ⇧</a>
<a href="/z-axis/move/up/pulse/10" type="button" class="btn btn-success btn-sm side_right" translate>10 Pulse ⇧</a>
<a href="/z-axis/move/up/pulse/1" type="button" class="btn btn-success btn-sm side_right" translate>1 Pulse ⇧</a>
</div>
</div>
{% if ZAxisPin %}
<br>
<legend translate>Move to layer</legend>
<form class="edit-page" method="POST">
<fieldset>
<div class="control-group">
<label class="control-label" for="appendedtext" translate>Plate</label>
<select name="ProfileID" class="form-control" required>
{% for profile in profiles %}
<option value="{{profile.ProfileID}}">{{profile.Title}}</option>
{% endfor %}
</select>
</div>
<br>
<div class="control-group">
<label class="control-label" translate>Layer</label>
<input id="appendedtext" name="LayerID" class="form-control" placeholder="Layer ID" type="text" required>
<br>
<br>
<div class="controls">
<button value="down" class="btn btn-danger" translate>Move to Layer</button>
</div>
</div>
</fieldset>
</form>
{% endif %}
</div>
</div>
{% endblock %}
|
layout: base
{% include header.html type="page" %}
<div class="container" role="main">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
{{ content }}
{% if page.comments %}
<div class="disqus-comments">
{% include disqus.html %}
</div>
{% include fb-comment.html %}
<div class="staticman-comments">
{% include staticman-comments.html %}
</div>
{% endif %}
</div>
</div>
</div>
|
require 'asciidoctor/extensions'
Asciidoctor::Extensions.register do
treeprocessor do
process do |doc|
doc
end
end
end
|
package com.artfulbits.utils;
import android.text.TextUtils;
import java.io.<API key>;
import java.util.logging.Logger;
/** Common string routine. */
public final class StringUtils {
/** Our own class Logger instance. */
private final static Logger _log = LogEx.getLogger(StringUtils.class);
/** Default strings encoding. */
public final static String UTF8 = "UTF-8";
/** Hidden constructor. */
private StringUtils() {
throw new AssertionError();
}
/**
* Convert string to utf 8 bytes.
*
* @param value the value to convert
* @return the bytes in UTF8 encoding.
*/
public static byte[] toUtf8Bytes(final String value) {
ValidUtils.isEmpty(value, "Expected not null value.");
// try to avoid NULL values, better to return empty array
byte[] buffer = new byte[]{};
if (!TextUtils.isEmpty(value)) {
try {
buffer = value.getBytes(StringUtils.UTF8);
} catch (final <API key> e) {
_log.severe(LogEx.dump(e));
}
}
return buffer;
}
}
|
#include <string.h>
#include "context.h"
void
makecontext(uctx *ucp, void (*func)(void), intptr_t arg)
{
long *sp;
memset(&ucp->uc_mcontext, 0, sizeof ucp->uc_mcontext);
ucp->uc_mcontext.mc_rdi = (long)arg;
sp = (long*)ucp->uc_stack.ss_sp+ucp->uc_stack.ss_size/sizeof(long);
sp -= 1;
sp = (void*)((uintptr_t)sp - (uintptr_t)sp%16); /* 16-align for OS X */
*--sp = 0; /* return address */
ucp->uc_mcontext.mc_rip = (long)func;
ucp->uc_mcontext.mc_rsp = (long)sp;
}
int
swapcontext(uctx *oucp, const uctx *ucp)
{
if(getcontext(oucp) == 0)
setcontext(ucp);
return 0;
}
|
package main
import (
"testing"
"github.com/k0kubun/pp"
_ "bitbucket.org/ikeikeikeike/antenna/conf/inits"
libm "bitbucket.org/ikeikeikeike/antenna/lib/models"
"bitbucket.org/ikeikeikeike/antenna/models"
"bitbucket.org/ikeikeikeike/antenna/models/character"
_ "bitbucket.org/ikeikeikeike/antenna/routers"
)
func TestQuery1(t *testing.T) {
models.Pictures().Filter("<API key>", "").Count()
for _, c := range character.CachedCharacters() {
if c.Id > 0 && len([]rune(c.Name)) > 2 && !libm.ReHK3.MatchString(c.Name) {
pp.Println(c.Name)
}
}
}
|
from django.conf import settings
from django.contrib.sites.shortcuts import get_current_site
from django.core.management import call_command
from django.db import models, connections, transaction
from django.urls import reverse
from django_tenants.clone import CloneSchema
from .postgresql_backend.base import _check_schema_name
from .signals import post_schema_sync, <API key>
from .utils import <API key>, <API key>
from .utils import schema_exists, <API key>, <API key>, <API key>
class TenantMixin(models.Model):
"""
All tenant models must inherit this class.
"""
auto_drop_schema = False
"""
USE THIS WITH CAUTION!
Set this flag to true on a parent class if you want the schema to be
automatically deleted if the tenant row gets deleted.
"""
auto_create_schema = True
"""
Set this flag to false on a parent class if you don't want the schema
to be automatically created upon save.
"""
schema_name = models.CharField(max_length=63, unique=True, db_index=True,
validators=[_check_schema_name])
domain_url = None
"""
Leave this as None. Stores the current domain url so it can be used in the logs
"""
domain_subfolder = None
"""
Leave this as None. Stores the subfolder in subfolder routing was used
"""
_previous_tenant = []
class Meta:
abstract = True
def __enter__(self):
"""
Syntax sugar which helps in celery tasks, cron jobs, and other scripts
Usage:
with Tenant.objects.get(schema_name='test') as tenant:
# run some code in tenant test
# run some code in previous tenant (public probably)
"""
connection = connections[<API key>()]
self._previous_tenant.append(connection.tenant)
self.activate()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
connection = connections[<API key>()]
connection.set_tenant(self._previous_tenant.pop())
def activate(self):
"""
Syntax sugar that helps at django shell with fast tenant changing
Usage:
Tenant.objects.get(schema_name='test').activate()
"""
connection = connections[<API key>()]
connection.set_tenant(self)
@classmethod
def deactivate(cls):
"""
Syntax sugar, return to public schema
Usage:
test_tenant.deactivate()
# or simpler
Tenant.deactivate()
"""
connection = connections[<API key>()]
connection.<API key>()
def save(self, verbosity=1, *args, **kwargs):
connection = connections[<API key>()]
is_new = self.pk is None
has_schema = hasattr(connection, 'schema_name')
if has_schema and is_new and connection.schema_name != <API key>():
raise Exception("Can't create tenant outside the public schema. "
"Current schema is %s." % connection.schema_name)
elif has_schema and not is_new and connection.schema_name not in (self.schema_name, <API key>()):
raise Exception("Can't update tenant outside it's own schema or "
"the public schema. Current schema is %s."
% connection.schema_name)
super().save(*args, **kwargs)
if has_schema and is_new and self.auto_create_schema:
try:
self.create_schema(check_if_exists=True, verbosity=verbosity)
post_schema_sync.send(sender=TenantMixin, tenant=self.serializable_fields())
except Exception:
# We failed creating the tenant, delete what we created and
# re-raise the exception
self.delete(force_drop=True)
raise
elif is_new:
# although we are not using the schema functions directly, the signal might be registered by a listener
<API key>.send(sender=TenantMixin, tenant=self.serializable_fields())
elif not is_new and self.auto_create_schema and not schema_exists(self.schema_name):
# Create schemas for existing models, deleting only the schema on failure
try:
self.create_schema(check_if_exists=True, verbosity=verbosity)
post_schema_sync.send(sender=TenantMixin, tenant=self.serializable_fields())
except Exception:
# We failed creating the schema, delete what we created and
# re-raise the exception
self._drop_schema()
raise
def serializable_fields(self):
""" in certain cases the user model isn't serializable so you may want to only send the id """
return self
def _drop_schema(self, force_drop=False):
""" Drops the schema"""
connection = connections[<API key>()]
has_schema = hasattr(connection, 'schema_name')
if has_schema and connection.schema_name not in (self.schema_name, <API key>()):
raise Exception("Can't delete tenant outside it's own schema or "
"the public schema. Current schema is %s."
% connection.schema_name)
if has_schema and schema_exists(self.schema_name) and (self.auto_drop_schema or force_drop):
self.pre_drop()
cursor = connection.cursor()
cursor.execute('DROP SCHEMA "%s" CASCADE' % self.schema_name)
def pre_drop(self):
"""
This is a routine which you could override to backup the tenant schema before dropping.
:return:
"""
def delete(self, force_drop=False, *args, **kwargs):
"""
Deletes this row. Drops the tenant's schema if the attribute
auto_drop_schema set to True.
"""
self._drop_schema(force_drop)
super().delete(*args, **kwargs)
def create_schema(self, check_if_exists=False, sync_schema=True,
verbosity=1):
"""
Creates the schema 'schema_name' for this tenant. Optionally checks if
the schema already exists before creating it. Returns true if the
schema was created, false otherwise.
"""
# safety check
connection = connections[<API key>()]
_check_schema_name(self.schema_name)
cursor = connection.cursor()
if check_if_exists and schema_exists(self.schema_name):
return False
fake_migrations = <API key>()
if sync_schema:
if fake_migrations:
# copy tables and data from provided model schema
base_schema = <API key>()
clone_schema = CloneSchema()
clone_schema.clone_schema(base_schema, self.schema_name)
call_command('migrate_schemas',
tenant=True,
fake=True,
schema_name=self.schema_name,
interactive=False,
verbosity=verbosity)
else:
# create the schema
cursor.execute('CREATE SCHEMA "%s"' % self.schema_name)
call_command('migrate_schemas',
tenant=True,
schema_name=self.schema_name,
interactive=False,
verbosity=verbosity)
connection.<API key>()
def get_primary_domain(self):
"""
Returns the primary domain of the tenant
"""
try:
domain = self.domains.get(is_primary=True)
return domain
except <API key>().DoesNotExist:
return None
def reverse(self, request, view_name):
"""
Returns the URL of this tenant.
"""
http_type = 'https:
domain = get_current_site(request).domain
url = ''.join((http_type, self.schema_name, '.', domain, reverse(view_name)))
return url
def get_tenant_type(self):
"""
Get the type of tenant. Will only work for multi type tenants
:return: str
"""
return getattr(self, settings.<API key>)
class DomainMixin(models.Model):
"""
All models that store the domains must inherit this class
"""
domain = models.CharField(max_length=253, unique=True, db_index=True)
tenant = models.ForeignKey(settings.TENANT_MODEL, db_index=True, related_name='domains',
on_delete=models.CASCADE)
# Set this to true if this is the primary domain
is_primary = models.BooleanField(default=True, db_index=True)
@transaction.atomic
def save(self, *args, **kwargs):
# Get all other primary domains with the same tenant
domain_list = self.__class__.objects.filter(tenant=self.tenant, is_primary=True).exclude(pk=self.pk)
# If we have no primary domain yet, set as primary domain by default
self.is_primary = self.is_primary or (not domain_list.exists())
if self.is_primary:
# Remove primary status of existing domains for tenant
domain_list.update(is_primary=False)
super().save(*args, **kwargs)
class Meta:
abstract = True
|
#ifndef <API key>
#define <API key>
#define HIP_SCOPED_MARKER(markerName, group)
#define HIP_BEGIN_MARKER(markerName, group)
#define HIP_END_MARKER()
#endif
|
package server
import (
"io"
"io/ioutil"
"log"
"net/http"
)
type Rest struct {
channels map[string]*Channel
}
func NewRestServer(server *Server) *Rest {
return &Rest{server.channels}
}
func (self *Rest) PostOnly(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
h(w, r)
return
}
http.Error(w, "post only", http.<API key>)
}
}
func (self *Rest) restHandler(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))
if err != nil {
panic(err)
}
if err := r.Body.Close(); err != nil {
panic(err)
}
channel := r.URL.Query().Get("channel")
//get the session id from header
session := r.Header.Get("session");
log.Printf("SessionID: %s", session)
msg := &Message{Channel: channel, Body: string(body), session: session}
if ch, ok := self.channels[channel]; ok {
ch.sendAll <- msg
}
log.Printf("[REST] body: %s, channel: %s", body, channel)
}
func (self *Rest) ListenRest() {
log.Println("Listening server(REST)...")
http.HandleFunc("/rest", self.PostOnly(self.restHandler))
}
|
#!/bin/sh
# CYBERWATCH SAS - 2017
# Security fix for DSA-2885-1
# Operating System: Debian 7 (Wheezy)
# Architecture: x86_64
# - <API key>:0.38-3+deb7u2
# Last versions recommanded by security team:
# - <API key>:0.38-3+deb7u3
# CVE List:
# - CVE-2014-2525
# More details:
sudo apt-get install --only-upgrade <API key>=0.38-3+deb7u3 -y
|
\author AMD Developer Tools Team
\file <API key>.h
#ifndef <API key>
#define <API key>
#pragma once
// Local:
#include <AMDTOSWrappers/Include/<API key>.h>
// Class Name: OS_API <API key>
// General Description:
// Aid class that enables "exception safe" locking of a synchronization object.
// Its constructor locks the synchronization object and destructor unlocks the
// synchronization object.
// This causes synchronization object unlocking in case of an exception.
// Example:
// void foo(<API key>& mySyncObj)
// <API key> syncObjLucker(mySyncObj);
// < doing something >
// In the above example, the synchronization object will be unlocked in the following scenarios:
// a. The thread exits the function: Exiting the function executes the syncObjLucker
// destructor, which unlocks the synchronization object.
// b. An exception is thrown while < doing something > is executed.
// If there is no exception handler in the function, the exception will be "thrown out"
// of the function, calling all the destructors of the function stack variables.
// Among these destructors is the syncObjLucker destructor, which will unlocks the
// synchronization object.
// The user can also call unlockSyncObj() manually to unlock the synchronization object
// before the <API key> destructor is called.
class OS_API <API key>
{
public:
<API key>(<API key>& syncObj);
~<API key>();
bool unlockSyncObj();
private:
// Disallow use of default constructor, copy constructor and assignment operator:
<API key>() = delete;
<API key>(const <API key>&) = delete;
<API key>& operator=(const <API key>&) = delete;
private:
// The synchronization object on which this class operates:
<API key>& _syncObj;
// Contains true iff the synchronization object was already unlocked by this class:
bool _wasSyncObjUnlocked;
};
#endif // <API key>
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>beta</title>
<!-- Bootstrap Core CSS -->
<link href="../vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!-- MetisMenu CSS -->
<link href="../vendor/metisMenu/metisMenu.min.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="../dist/css/sb-admin-2.css" rel="stylesheet">
<!-- Morris Charts CSS -->
<link href="../vendor/morrisjs/morris.css" rel="stylesheet">
<!-- Custom Fonts -->
<link href="../vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<!-- 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/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]
</head>
<body>
<div id="wrapper">
<!-- Navigation -->
<nav class="navbar navbar-default navbar-static-top" role="navigation" style="margin-bottom: 0">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<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="index.html">SB Admin v2.0</a>
</div>
<!-- /.navbar-header -->
<ul class="nav navbar-top-links navbar-right">
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="
<i class="fa fa-envelope fa-fw"></i> <i class="fa fa-caret-down"></i>
</a>
<ul class="dropdown-menu dropdown-messages">
<li>
<a href="
<div>
<strong>John Smith</strong>
<span class="pull-right text-muted">
<em>Yesterday</em>
</span>
</div>
<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque eleifend...</div>
</a>
</li>
<li class="divider"></li>
<li>
<a href="
<div>
<strong>John Smith</strong>
<span class="pull-right text-muted">
<em>Yesterday</em>
</span>
</div>
<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque eleifend...</div>
</a>
</li>
<li class="divider"></li>
<li>
<a href="
<div>
<strong>John Smith</strong>
<span class="pull-right text-muted">
<em>Yesterday</em>
</span>
</div>
<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque eleifend...</div>
</a>
</li>
<li class="divider"></li>
<li>
<a class="text-center" href="
<strong>Read All Messages</strong>
<i class="fa fa-angle-right"></i>
</a>
</li>
</ul>
<!-- /.dropdown-messages -->
</li>
<!-- /.dropdown -->
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="
<i class="fa fa-tasks fa-fw"></i> <i class="fa fa-caret-down"></i>
</a>
<ul class="dropdown-menu dropdown-tasks">
<li>
<a href="
<div>
<p>
<strong>Task 1</strong>
<span class="pull-right text-muted">40% Complete</span>
</p>
<div class="progress progress-striped active">
<div class="progress-bar <API key>" role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style="width: 40%">
<span class="sr-only">40% Complete (success)</span>
</div>
</div>
</div>
</a>
</li>
<li class="divider"></li>
<li>
<a href="
<div>
<p>
<strong>Task 2</strong>
<span class="pull-right text-muted">20% Complete</span>
</p>
<div class="progress progress-striped active">
<div class="progress-bar progress-bar-info" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100" style="width: 20%">
<span class="sr-only">20% Complete</span>
</div>
</div>
</div>
</a>
</li>
<li class="divider"></li>
<li>
<a href="
<div>
<p>
<strong>Task 3</strong>
<span class="pull-right text-muted">60% Complete</span>
</p>
<div class="progress progress-striped active">
<div class="progress-bar <API key>" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 60%">
<span class="sr-only">60% Complete (warning)</span>
</div>
</div>
</div>
</a>
</li>
<li class="divider"></li>
<li>
<a href="
<div>
<p>
<strong>Task 4</strong>
<span class="pull-right text-muted">80% Complete</span>
</p>
<div class="progress progress-striped active">
<div class="progress-bar progress-bar-danger" role="progressbar" aria-valuenow="80" aria-valuemin="0" aria-valuemax="100" style="width: 80%">
<span class="sr-only">80% Complete (danger)</span>
</div>
</div>
</div>
</a>
</li>
<li class="divider"></li>
<li>
<a class="text-center" href="
<strong>See All Tasks</strong>
<i class="fa fa-angle-right"></i>
</a>
</li>
</ul>
<!-- /.dropdown-tasks -->
</li>
<!-- /.dropdown -->
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="
<i class="fa fa-bell fa-fw"></i> <i class="fa fa-caret-down"></i>
</a>
<ul class="dropdown-menu dropdown-alerts">
<li>
<a href="
<div>
<i class="fa fa-comment fa-fw"></i> New Comment
<span class="pull-right text-muted small">4 minutes ago</span>
</div>
</a>
</li>
<li class="divider"></li>
<li>
<a href="
<div>
<i class="fa fa-twitter fa-fw"></i> 3 New Followers
<span class="pull-right text-muted small">12 minutes ago</span>
</div>
</a>
</li>
<li class="divider"></li>
<li>
<a href="
<div>
<i class="fa fa-envelope fa-fw"></i> Message Sent
<span class="pull-right text-muted small">4 minutes ago</span>
</div>
</a>
</li>
<li class="divider"></li>
<li>
<a href="
<div>
<i class="fa fa-tasks fa-fw"></i> New Task
<span class="pull-right text-muted small">4 minutes ago</span>
</div>
</a>
</li>
<li class="divider"></li>
<li>
<a href="
<div>
<i class="fa fa-upload fa-fw"></i> Server Rebooted
<span class="pull-right text-muted small">4 minutes ago</span>
</div>
</a>
</li>
<li class="divider"></li>
<li>
<a class="text-center" href="
<strong>See All Alerts</strong>
<i class="fa fa-angle-right"></i>
</a>
</li>
</ul>
<!-- /.dropdown-alerts -->
</li>
<!-- /.dropdown -->
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="
<i class="fa fa-user fa-fw"></i> <i class="fa fa-caret-down"></i>
</a>
<ul class="dropdown-menu dropdown-user">
<li><a href="#"><i class="fa fa-user fa-fw"></i> User Profile</a>
</li>
<li><a href="#"><i class="fa fa-gear fa-fw"></i> Settings</a>
</li>
<li class="divider"></li>
<li><a href="login.html"><i class="fa fa-sign-out fa-fw"></i> Logout</a>
</li>
</ul>
<!-- /.dropdown-user -->
</li>
<!-- /.dropdown -->
</ul>
<!-- /.navbar-top-links -->
<div class="navbar-default sidebar" role="navigation">
<div class="sidebar-nav navbar-collapse">
<ul class="nav" id="side-menu">
<li class="sidebar-search">
<div class="input-group custom-search-form">
<input type="text" class="form-control" placeholder="Search...">
<span class="input-group-btn">
<button class="btn btn-default" type="button">
<i class="fa fa-search"></i>
</button>
</span>
</div>
<!-- /input-group -->
</li>
<li>
<a href="index.html"><i class="fa fa-dashboard fa-fw"></i> Dashboard</a>
</li>
<li>
<a href="#"><i class="fa fa-bar-chart-o fa-fw"></i> Charts<span class="fa arrow"></span></a>
<ul class="nav nav-second-level">
<li>
<a href="flot.html">Flot Charts</a>
</li>
<li>
<a href="morris.html">Morris.js Charts</a>
</li>
</ul>
<!-- /.nav-second-level -->
</li>
<li>
<a href="tables.html"><i class="fa fa-table fa-fw"></i> Tables</a>
</li>
<li>
<a href="forms.html"><i class="fa fa-edit fa-fw"></i> Forms</a>
</li>
<li>
<a href="#"><i class="fa fa-wrench fa-fw"></i> UI Elements<span class="fa arrow"></span></a>
<ul class="nav nav-second-level">
<li>
<a href="panels-wells.html">Panels and Wells</a>
</li>
<li>
<a href="buttons.html">Buttons</a>
</li>
<li>
<a href="notifications.html">Notifications</a>
</li>
<li>
<a href="typography.html">Typography</a>
</li>
<li>
<a href="icons.html"> Icons</a>
</li>
<li>
<a href="grid.html">Grid</a>
</li>
</ul>
<!-- /.nav-second-level -->
</li>
<li>
<a href="#"><i class="fa fa-sitemap fa-fw"></i> Multi-Level Dropdown<span class="fa arrow"></span></a>
<ul class="nav nav-second-level">
<li>
<a href="#">Second Level Item</a>
</li>
<li>
<a href="#">Second Level Item</a>
</li>
<li>
<a href="#">Third Level <span class="fa arrow"></span></a>
<ul class="nav nav-third-level">
<li>
<a href="#">Third Level Item</a>
</li>
<li>
<a href="#">Third Level Item</a>
</li>
<li>
<a href="#">Third Level Item</a>
</li>
<li>
<a href="#">Third Level Item</a>
</li>
</ul>
<!-- /.nav-third-level -->
</li>
</ul>
<!-- /.nav-second-level -->
</li>
<li>
<a href="#"><i class="fa fa-files-o fa-fw"></i> Sample Pages<span class="fa arrow"></span></a>
<ul class="nav nav-second-level">
<li>
<a href="blank.html">Blank Page</a>
</li>
<li>
<a href="login.html">Login Page</a>
</li>
</ul>
<!-- /.nav-second-level -->
</li>
</ul>
</div>
<!-- /.sidebar-collapse -->
</div>
<!-- /.navbar-static-side -->
</nav>
<div id="page-wrapper">
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Flot</h1>
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-heading">
Line Chart Example
</div>
<!-- /.panel-heading -->
<div class="panel-body">
<div class="flot-chart">
<div class="flot-chart-content" id="flot-line-chart"></div>
</div>
</div>
<!-- /.panel-body -->
</div>
<!-- /.panel -->
</div>
<!-- /.col-lg-12 -->
<div class="col-lg-6">
<div class="panel panel-default">
<div class="panel-heading">
Pie Chart Example
</div>
<!-- /.panel-heading -->
<div class="panel-body">
<div class="flot-chart">
<div class="flot-chart-content" id="flot-pie-chart"></div>
</div>
</div>
<!-- /.panel-body -->
</div>
<!-- /.panel -->
</div>
<!-- /.col-lg-6 -->
<div class="col-lg-6">
<div class="panel panel-default">
<div class="panel-heading">
Multiple Axes Line Chart Example
</div>
<!-- /.panel-heading -->
<div class="panel-body">
<div class="flot-chart">
<div class="flot-chart-content" id="<API key>"></div>
</div>
</div>
<!-- /.panel-body -->
</div>
<!-- /.panel -->
</div>
<!-- /.col-lg-6 -->
<div class="col-lg-6">
<div class="panel panel-default">
<div class="panel-heading">
Moving Line Chart Example
</div>
<!-- /.panel-heading -->
<div class="panel-body">
<div class="flot-chart">
<div class="flot-chart-content" id="<API key>"></div>
</div>
</div>
<!-- /.panel-body -->
</div>
<!-- /.panel -->
</div>
<!-- /.col-lg-6 -->
<div class="col-lg-6">
<div class="panel panel-default">
<div class="panel-heading">
Bar Chart Example
</div>
<!-- /.panel-heading -->
<div class="panel-body">
<div class="flot-chart">
<div class="flot-chart-content" id="flot-bar-chart"></div>
</div>
</div>
<!-- /.panel-body -->
</div>
<!-- /.panel -->
</div>
<!-- /.col-lg-6 -->
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-heading">
Flot Charts Usage
</div>
<!-- /.panel-heading -->
<div class="panel-body">
<p>Flot is a pure JavaScript plotting library for jQuery, with a focus on simple usage, attractive looks, and interactive features. In SB Admin, we are using the most recent version of Flot along with a few plugins to enhance the user experience. The Flot plugins being used are the tooltip plugin for hoverable tooltips, and the resize plugin for fully responsive charts. The documentation for Flot Charts is available on their website, <a target="_blank" href="http:
<a target="_blank" class="btn btn-default btn-lg btn-block" href="http:
</div>
<!-- /.panel-body -->
</div>
<!-- /.panel -->
</div>
<!-- /.col-lg-6 -->
</div>
<!-- /.row -->
</div>
<!-- /#page-wrapper -->
</div>
<!-- /#wrapper -->
<!-- jQuery -->
<script src="../vendor/jquery/jquery.min.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="../vendor/bootstrap/js/bootstrap.min.js"></script>
<!-- Metis Menu Plugin JavaScript -->
<script src="../vendor/metisMenu/metisMenu.min.js"></script>
<!-- Flot Charts JavaScript -->
<script src="../vendor/flot/excanvas.min.js"></script>
<script src="../vendor/flot/jquery.flot.js"></script>
<script src="../vendor/flot/jquery.flot.pie.js"></script>
<script src="../vendor/flot/jquery.flot.resize.js"></script>
<script src="../vendor/flot/jquery.flot.time.js"></script>
<script src="../vendor/flot-tooltip/jquery.flot.tooltip.min.js"></script>
<script src="../data/flot-data.js"></script>
<!-- Custom Theme JavaScript -->
<script src="../dist/js/sb-admin-2.js"></script>
</body>
</html>
|
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class HistorialC extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->helper('date');
$this->load->model('HistorialM');
if (!$this->session->userdata("login")) {
redirect(base_url());
}
}
public function index(){
$data['regs'] = $this->HistorialM->lista();
$this->load->view('historialV', $data);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using RiotSharp.MatchEndpoint.Enums;
namespace RiotSharp.Misc
{
static class Util
{
public static DateTime BaseDateTime = new DateTime(1970, 1, 1);
public static DateTime <API key>(this long millis)
{
return BaseDateTime.AddMilliseconds(millis);
}
public static long ToLong(this DateTime dateTime)
{
var span = dateTime - BaseDateTime;
return (long)span.TotalMilliseconds;
}
public static string BuildIdsString(List<int> ids)
{
return string.Join(",", ids);
}
public static string BuildIdsString(List<long> ids)
{
return string.Join(",", ids);
}
public static string BuildNamesString(List<string> names)
{
return string.Join(",", names.Select(Uri.EscapeDataString));
}
public static string BuildQueuesString(List<string> queues)
{
return string.Join(",", queues);
}
public static string BuildSeasonString(List<Season> seasons)
{
return string.Join(",", seasons.Select(s => s.ToCustomString()));
}
}
}
|
'use strict';
describe('Controller: MainCtrl', function () {
// load the controller's module
beforeEach(module('pillzApp'));
var MainCtrl,
scope,
$httpBackend;
// Initialize the controller and a mock scope
beforeEach(inject(function (_$httpBackend_, $controller, $rootScope) {
$httpBackend = _$httpBackend_;
$httpBackend.expectGET('/api/awesomeThings')
.respond(['HTML5 Boilerplate', 'AngularJS', 'Karma', 'Express']);
scope = $rootScope.$new();
MainCtrl = $controller('MainCtrl', {
$scope: scope
});
}));
it('should attach a list of awesomeThings to the scope', function () {
expect(scope.awesomeThings).toBeUndefined();
$httpBackend.flush();
expect(scope.awesomeThings.length).toBe(4);
});
});
|
Confl
==
Load or reload configuration!
[
func main() {
watcher, err := confl.NewFileWatcher(&config.Config{}, "./default.yaml", yaml.Unmarshal)
if err != nil {
panic(err)
}
defer watcher.Close()
watcher.OnError(func(err error) {
fmt.Println("your error handler start")
fmt.Println(err)
})
// add hook for update events
// perhaps you need reload something that depends the configuration
watcher.AddHook(func(oc, nc interface{}) {
ocfg := oc.(config.Config)
ncfg := nc.(config.Config)
// use cfg
fmt.Printf("old config: %#v\n", ocfg)
fmt.Printf("new config: %#v\n", ncfg)
})
// get configuration from watcher
cfg := watcher.Config().(config.Config)
// use cfg
fmt.Printf("load config: %#v\n", cfg)
// start watch
// it is a blocking method choose run with `go` by situation
watcher.Watch()
}
More [example](./examples)
|
<?php
use Symfony\Component\Routing\Exception\<API key>;
use Symfony\Component\Routing\Exception\<API key>;
use Symfony\Component\Routing\RequestContext;
/**
* appDevUrlMatcher
*
* This class has been auto-generated
* by the Symfony Routing Component.
*/
class appDevUrlMatcher extends Symfony\Bundle\FrameworkBundle\Routing\<API key>
{
/**
* Constructor.
*/
public function __construct(RequestContext $context)
{
$this->context = $context;
}
public function match($pathinfo)
{
$allow = array();
$pathinfo = rawurldecode($pathinfo);
if (0 === strpos($pathinfo, '/_')) {
// _wdt
if (0 === strpos($pathinfo, '/_wdt') && preg_match('#^/_wdt/(?P<token>[^/]++)$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_wdt')), array ( '_controller' => 'web_profiler.controller.profiler:toolbarAction',));
}
if (0 === strpos($pathinfo, '/_profiler')) {
// _profiler_home
if (rtrim($pathinfo, '/') === '/_profiler') {
if (substr($pathinfo, -1) !== '/') {
return $this->redirect($pathinfo.'/', '_profiler_home');
}
return array ( '_controller' => 'web_profiler.controller.profiler:homeAction', '_route' => '_profiler_home',);
}
if (0 === strpos($pathinfo, '/_profiler/search')) {
// _profiler_search
if ($pathinfo === '/_profiler/search') {
return array ( '_controller' => 'web_profiler.controller.profiler:searchAction', '_route' => '_profiler_search',);
}
// <API key>
if ($pathinfo === '/_profiler/search_bar') {
return array ( '_controller' => 'web_profiler.controller.profiler:searchBarAction', '_route' => '<API key>',);
}
}
// _profiler_purge
if ($pathinfo === '/_profiler/purge') {
return array ( '_controller' => 'web_profiler.controller.profiler:purgeAction', '_route' => '_profiler_purge',);
}
if (0 === strpos($pathinfo, '/_profiler/i')) {
// _profiler_info
if (0 === strpos($pathinfo, '/_profiler/info') && preg_match('#^/_profiler/info/(?P<about>[^/]++)$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_info')), array ( '_controller' => 'web_profiler.controller.profiler:infoAction',));
}
// _profiler_import
if ($pathinfo === '/_profiler/import') {
return array ( '_controller' => 'web_profiler.controller.profiler:importAction', '_route' => '_profiler_import',);
}
}
// _profiler_export
if (0 === strpos($pathinfo, '/_profiler/export') && preg_match('#^/_profiler/export/(?P<token>[^/\\.]++)\\.txt$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_export')), array ( '_controller' => 'web_profiler.controller.profiler:exportAction',));
}
// _profiler_phpinfo
if ($pathinfo === '/_profiler/phpinfo') {
return array ( '_controller' => 'web_profiler.controller.profiler:phpinfoAction', '_route' => '_profiler_phpinfo',);
}
// <API key>
if (preg_match('#^/_profiler/(?P<token>[^/]++)/search/results$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '<API key>')), array ( '_controller' => 'web_profiler.controller.profiler:searchResultsAction',));
}
// _profiler
if (preg_match('#^/_profiler/(?P<token>[^/]++)$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler')), array ( '_controller' => 'web_profiler.controller.profiler:panelAction',));
}
// _profiler_router
if (preg_match('#^/_profiler/(?P<token>[^/]++)/router$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_router')), array ( '_controller' => 'web_profiler.controller.router:panelAction',));
}
// _profiler_exception
if (preg_match('#^/_profiler/(?P<token>[^/]++)/exception$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_exception')), array ( '_controller' => 'web_profiler.controller.exception:showAction',));
}
// <API key>
if (preg_match('#^/_profiler/(?P<token>[^/]++)/exception\\.css$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '<API key>')), array ( '_controller' => 'web_profiler.controller.exception:cssAction',));
}
}
if (0 === strpos($pathinfo, '/_configurator')) {
// _configurator_home
if (rtrim($pathinfo, '/') === '/_configurator') {
if (substr($pathinfo, -1) !== '/') {
return $this->redirect($pathinfo.'/', '_configurator_home');
}
return array ( '_controller' => 'Sensio\\Bundle\\DistributionBundle\\Controller\\<API key>::checkAction', '_route' => '_configurator_home',);
}
// _configurator_step
if (0 === strpos($pathinfo, '/_configurator/step') && preg_match('#^/_configurator/step/(?P<index>[^/]++)$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_configurator_step')), array ( '_controller' => 'Sensio\\Bundle\\DistributionBundle\\Controller\\<API key>::stepAction',));
}
// _configurator_final
if ($pathinfo === '/_configurator/final') {
return array ( '_controller' => 'Sensio\\Bundle\\DistributionBundle\\Controller\\<API key>::finalAction', '_route' => '_configurator_final',);
}
}
}
if (0 === strpos($pathinfo, '/collection')) {
// lien_collection
if (rtrim($pathinfo, '/') === '/collection') {
if (substr($pathinfo, -1) !== '/') {
return $this->redirect($pathinfo.'/', 'lien_collection');
}
return array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\<API key>::indexAction', '_route' => 'lien_collection',);
}
// <API key>
if (preg_match('#^/collection/(?P<id>[^/]++)/(?P<slug>[^/]++)(?:/(?P<page>[^/]++))?$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '<API key>')), array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\<API key>::showAction', 'page' => 1,));
}
// lien_collection_new
if ($pathinfo === '/collection/new') {
return array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\<API key>::newAction', '_route' => 'lien_collection_new',);
}
// <API key>
if ($pathinfo === '/collection/create') {
if ($this->context->getMethod() != 'POST') {
$allow[] = 'POST';
goto <API key>;
}
return array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\<API key>::createAction', '_route' => '<API key>',);
}
<API key>:
// <API key>
if (0 === strpos($pathinfo, '/collection/edit') && preg_match('#^/collection/edit/(?P<id>[^/]++)/?$#s', $pathinfo, $matches)) {
if (substr($pathinfo, -1) !== '/') {
return $this->redirect($pathinfo.'/', '<API key>');
}
return $this->mergeDefaults(array_replace($matches, array('_route' => '<API key>')), array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\<API key>::editAction',));
}
// <API key>
if (preg_match('#^/collection/(?P<id>[^/]++)/update$#s', $pathinfo, $matches)) {
if (!in_array($this->context->getMethod(), array('POST', 'PUT'))) {
$allow = array_merge($allow, array('POST', 'PUT'));
goto <API key>;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => '<API key>')), array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\<API key>::updateAction',));
}
<API key>:
// <API key>
if (preg_match('#^/collection/(?P<id>[^/]++)/delete$#s', $pathinfo, $matches)) {
if (!in_array($this->context->getMethod(), array('POST', 'DELETE'))) {
$allow = array_merge($allow, array('POST', 'DELETE'));
goto <API key>;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => '<API key>')), array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\<API key>::deleteAction',));
}
<API key>:
}
if (0 === strpos($pathinfo, '/avis')) {
// lien_avis
if (rtrim($pathinfo, '/') === '/avis') {
if (substr($pathinfo, -1) !== '/') {
return $this->redirect($pathinfo.'/', 'lien_avis');
}
return array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\<API key>::indexAction', '_route' => 'lien_avis',);
}
// lien_avis_show
if (preg_match('#^/avis/(?P<id>[^/]++)/show$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'lien_avis_show')), array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\<API key>::showAction',));
}
// lien_avis_new
if ($pathinfo === '/avis/new') {
return array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\<API key>::newAction', '_route' => 'lien_avis_new',);
}
// lien_avis_create
if ($pathinfo === '/avis/create') {
if ($this->context->getMethod() != 'POST') {
$allow[] = 'POST';
goto <API key>;
}
return array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\<API key>::createAction', '_route' => 'lien_avis_create',);
}
<API key>:
// lien_avis_edit
if (preg_match('#^/avis/(?P<id>[^/]++)/edit$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'lien_avis_edit')), array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\<API key>::editAction',));
}
// lien_avis_update
if (preg_match('#^/avis/(?P<id>[^/]++)/update$#s', $pathinfo, $matches)) {
if (!in_array($this->context->getMethod(), array('POST', 'PUT'))) {
$allow = array_merge($allow, array('POST', 'PUT'));
goto <API key>;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'lien_avis_update')), array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\<API key>::updateAction',));
}
<API key>:
// lien_avis_delete
if (preg_match('#^/avis/(?P<id>[^/]++)/delete$#s', $pathinfo, $matches)) {
if (!in_array($this->context->getMethod(), array('POST', 'DELETE'))) {
$allow = array_merge($allow, array('POST', 'DELETE'));
goto <API key>;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'lien_avis_delete')), array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\<API key>::deleteAction',));
}
<API key>:
}
if (0 === strpos($pathinfo, '/livre')) {
// lien_livre
if (rtrim($pathinfo, '/') === '/livre') {
if (substr($pathinfo, -1) !== '/') {
return $this->redirect($pathinfo.'/', 'lien_livre');
}
return array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\LivreController::indexAction', '_route' => 'lien_livre',);
}
// lien_livre_read
if (0 === strpos($pathinfo, '/livre/read') && preg_match('#^/livre/read/(?P<collection>[^/]++)/(?P<auteur>[^/]++)/(?P<id>\\d+)/(?P<titre>[^/]++)$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'lien_livre_read')), array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\LivreController::readAction',));
}
// lien_livre_show
if (preg_match('#^/livre/(?P<collection>[^/]++)/(?P<auteur>[^/]++)/(?P<id>\\d+)/(?P<titre>[^/]++)$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'lien_livre_show')), array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\LivreController::showAction',));
}
// lien_livre_all
if (0 === strpos($pathinfo, '/livre/liste') && preg_match('#^/livre/liste(?:/(?P<page>[^/]++))?$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'lien_livre_all')), array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\LivreController::allAction', 'page' => 1,));
}
// lien_livre_show_all
if (0 === strpos($pathinfo, '/livre/catalogue') && preg_match('#^/livre/catalogue(?:/(?P<page>[^/]++))?$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'lien_livre_show_all')), array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\LivreController::showAllAction', 'page' => 1,));
}
// lien_livre_find
if ($pathinfo === '/livre/recherche') {
if ($this->context->getMethod() != 'POST') {
$allow[] = 'POST';
goto not_lien_livre_find;
}
return array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\LivreController::findAction', '_route' => 'lien_livre_find',);
}
not_lien_livre_find:
// lien_livre_new
if ($pathinfo === '/livre/new') {
return array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\LivreController::newAction', '_route' => 'lien_livre_new',);
}
// lien_livre_create
if ($pathinfo === '/livre/create') {
if ($this->context->getMethod() != 'POST') {
$allow[] = 'POST';
goto <API key>;
}
return array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\LivreController::createAction', '_route' => 'lien_livre_create',);
}
<API key>:
// lien_livre_edit
if (preg_match('#^/livre/(?P<id>[^/]++)/edit$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'lien_livre_edit')), array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\LivreController::editAction',));
}
// lien_livre_update
if (preg_match('#^/livre/(?P<id>[^/]++)/update$#s', $pathinfo, $matches)) {
if (!in_array($this->context->getMethod(), array('POST', 'PUT'))) {
$allow = array_merge($allow, array('POST', 'PUT'));
goto <API key>;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'lien_livre_update')), array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\LivreController::updateAction',));
}
<API key>:
// lien_livre_delete
if (preg_match('#^/livre/(?P<id>[^/]++)/delete$#s', $pathinfo, $matches)) {
if (!in_array($this->context->getMethod(), array('POST', 'DELETE'))) {
$allow = array_merge($allow, array('POST', 'DELETE'));
goto <API key>;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'lien_livre_delete')), array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\LivreController::deleteAction',));
}
<API key>:
}
if (0 === strpos($pathinfo, '/user')) {
// lien_user
if (rtrim($pathinfo, '/') === '/user') {
if (substr($pathinfo, -1) !== '/') {
return $this->redirect($pathinfo.'/', 'lien_user');
}
return array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\UserController::indexAction', '_route' => 'lien_user',);
}
// lien_user_show
if (preg_match('#^/user/(?P<id>[^/]++)/show$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'lien_user_show')), array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\UserController::showAction',));
}
// lien_user_new
if ($pathinfo === '/user/new') {
return array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\UserController::newAction', '_route' => 'lien_user_new',);
}
// lien_user_create
if ($pathinfo === '/user/create') {
if ($this->context->getMethod() != 'POST') {
$allow[] = 'POST';
goto <API key>;
}
return array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\UserController::createAction', '_route' => 'lien_user_create',);
}
<API key>:
// lien_user_modif
if ($pathinfo === '/user/modif') {
if ($this->context->getMethod() != 'POST') {
$allow[] = 'POST';
goto not_lien_user_modif;
}
return array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\UserController::modifAction', '_route' => 'lien_user_modif',);
}
not_lien_user_modif:
// lien_user_edit
if (0 === strpos($pathinfo, '/user/edit') && preg_match('#^/user/edit/(?P<id>[^/]++)/?$#s', $pathinfo, $matches)) {
if (substr($pathinfo, -1) !== '/') {
return $this->redirect($pathinfo.'/', 'lien_user_edit');
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'lien_user_edit')), array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\UserController::editAction',));
}
// <API key>
if (preg_match('#^/user/(?P<id>[^/]++)/edit$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '<API key>')), array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\UserController::editAdminAction',));
}
// lien_user_update
if (preg_match('#^/user/(?P<id>[^/]++)/update$#s', $pathinfo, $matches)) {
if (!in_array($this->context->getMethod(), array('POST', 'PUT'))) {
$allow = array_merge($allow, array('POST', 'PUT'));
goto <API key>;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'lien_user_update')), array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\UserController::updateAction',));
}
<API key>:
// <API key>
if (preg_match('#^/user/(?P<id>[^/]++)/update$#s', $pathinfo, $matches)) {
if (!in_array($this->context->getMethod(), array('POST', 'PUT'))) {
$allow = array_merge($allow, array('POST', 'PUT'));
goto <API key>;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => '<API key>')), array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\UserController::updateAdminAction',));
}
<API key>:
// lien_user_delete
if (preg_match('#^/user/(?P<id>[^/]++)/delete$#s', $pathinfo, $matches)) {
if (!in_array($this->context->getMethod(), array('POST', 'DELETE'))) {
$allow = array_merge($allow, array('POST', 'DELETE'));
goto <API key>;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'lien_user_delete')), array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\UserController::deleteAction',));
}
<API key>:
if (0 === strpos($pathinfo, '/user/log')) {
// lien_user_login
if ($pathinfo === '/user/login') {
if ($this->context->getMethod() != 'POST') {
$allow[] = 'POST';
goto not_lien_user_login;
}
return array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\UserController::loginAction', '_route' => 'lien_user_login',);
}
not_lien_user_login:
// lien_user_logout
if ($pathinfo === '/user/logout') {
return array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\UserController::logoutAction', '_route' => 'lien_user_logout',);
}
}
}
// lsi_biblio_homepage
if (0 === strpos($pathinfo, '/hello') && preg_match('#^/hello/(?P<name>[^/]++)$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'lsi_biblio_homepage')), array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\DefaultController::indexAction',));
}
// _welcome
if (rtrim($pathinfo, '/') === '') {
if (substr($pathinfo, -1) !== '/') {
return $this->redirect($pathinfo.'/', '_welcome');
}
return array ( '_controller' => 'Acme\\DemoBundle\\Controller\\WelcomeController::indexAction', '_route' => '_welcome',);
}
if (0 === strpos($pathinfo, '/demo')) {
if (0 === strpos($pathinfo, '/demo/secured')) {
if (0 === strpos($pathinfo, '/demo/secured/log')) {
if (0 === strpos($pathinfo, '/demo/secured/login')) {
// _demo_login
if ($pathinfo === '/demo/secured/login') {
return array ( '_controller' => 'Acme\\DemoBundle\\Controller\\SecuredController::loginAction', '_route' => '_demo_login',);
}
// _security_check
if ($pathinfo === '/demo/secured/login_check') {
return array ( '_controller' => 'Acme\\DemoBundle\\Controller\\SecuredController::securityCheckAction', '_route' => '_security_check',);
}
}
// _demo_logout
if ($pathinfo === '/demo/secured/logout') {
return array ( '_controller' => 'Acme\\DemoBundle\\Controller\\SecuredController::logoutAction', '_route' => '_demo_logout',);
}
}
if (0 === strpos($pathinfo, '/demo/secured/hello')) {
// <API key>
if ($pathinfo === '/demo/secured/hello') {
return array ( 'name' => 'World', '_controller' => 'Acme\\DemoBundle\\Controller\\SecuredController::helloAction', '_route' => '<API key>',);
}
// _demo_secured_hello
if (preg_match('#^/demo/secured/hello/(?P<name>[^/]++)$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_demo_secured_hello')), array ( '_controller' => 'Acme\\DemoBundle\\Controller\\SecuredController::helloAction',));
}
// <API key>
if (0 === strpos($pathinfo, '/demo/secured/hello/admin') && preg_match('#^/demo/secured/hello/admin/(?P<name>[^/]++)$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '<API key>')), array ( '_controller' => 'Acme\\DemoBundle\\Controller\\SecuredController::helloadminAction',));
}
}
}
// _demo
if (rtrim($pathinfo, '/') === '/demo') {
if (substr($pathinfo, -1) !== '/') {
return $this->redirect($pathinfo.'/', '_demo');
}
return array ( '_controller' => 'Acme\\DemoBundle\\Controller\\DemoController::indexAction', '_route' => '_demo',);
}
// _demo_hello
if (0 === strpos($pathinfo, '/demo/hello') && preg_match('#^/demo/hello/(?P<name>[^/]++)$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_demo_hello')), array ( '_controller' => 'Acme\\DemoBundle\\Controller\\DemoController::helloAction',));
}
// _demo_contact
if ($pathinfo === '/demo/contact') {
return array ( '_controller' => 'Acme\\DemoBundle\\Controller\\DemoController::contactAction', '_route' => '_demo_contact',);
}
}
throw 0 < count($allow) ? new <API key>(array_unique($allow)) : new <API key>();
}
}
|
'use strict';
var assert = require('power-assert');
var resetStorage = require('./');
var dbName = 'test-item';
describe('#localStorage', function () {
beforeEach(function (done) {
localStorage.clear();
done();
});
it('should save value', function () {
var expected = { foo: 'bar', goo: 'nuu' };
localStorage.setItem('item', JSON.stringify(expected));
assert.deepEqual(expected, JSON.parse(localStorage.getItem('item')));
});
it('should clear value', function (done) {
var input = { foo: 'bar', goo: 'nuu' };
localStorage.setItem('item', JSON.stringify(input));
resetStorage
.localStorage()
.then(function () {
assert.equal(null, localStorage.getItem('item'));
done();
});
});
});
describe('#indexedDB', function () {
var db;
beforeEach(function (done) {
var req = indexedDB.deleteDatabase('test-item');
req.onsuccess = function() {
done();
};
});
it('should save value', function (done) {
if (!indexedDB) {
throw new Error('Your browser doesn\'t support a stable version of IndexedDB.');
}
var openRequest = indexedDB.open(dbName, 2);
var key = 'foo';
var value = 'bar';
var expected = {};
expected[key] = value;
openRequest.onerror = function(event) {
throw new Error(event.toString);
};
openRequest.onupgradeneeded = function(event) {
db = event.target.result;
var store = db.createObjectStore('mystore', { keyPath: 'mykey'});
store.createIndex('myvalueIndex', 'myvalue');
};
openRequest.onsuccess = function() {
db = openRequest.result;
var transaction = db.transaction(['mystore'], 'readwrite');
var store = transaction.objectStore('mystore');
var request = store.put({ mykey: key, myvalue: value });
request.onsuccess = function () {
var transaction = db.transaction(['mystore'], 'readwrite');
var store = transaction.objectStore('mystore');
var request = store.get(key);
request.onsuccess = function (event) {
assert.equal(value, event.target.result.myvalue);
db.close();
done();
};
request.onerror = function (event) {
db.close();
throw new Error(event.toString);
};
};
request.onerror = function(event) {
db.close();
throw new Error(event.toString);
};
};
});
it.skip('should clear value. Writing this test is too hard for me.', function (done) {
if (true) {// eslint-disable-line <API key>
throw new Error();
}
if (!indexedDB) {
throw new Error('Your browser doesn\'t support a stable version of IndexedDB.');
}
var openRequest = indexedDB.open(dbName, 2);
var key = 'foo';
var value = 'bar';
var expected = {};
expected[key] = value;
openRequest.onerror = function(event) {
throw new Error(event.toString);
};
openRequest.onupgradeneeded = function(event) {
db = event.target.result;
var store = db.createObjectStore('mystore', { keyPath: 'mykey'});
store.createIndex('myvalueIndex', 'myvalue');
};
openRequest.onsuccess = function() {
db = openRequest.result;
var transaction = db.transaction(['mystore'], 'readwrite');
var store = transaction.objectStore('mystore');
var request = store.put({ mykey: key, myvalue: value });
request.onsuccess = function () {
db.close();
var openRequest = indexedDB.open(dbName, 2);
openRequest.onerror = function(event) {
throw new Error(event.toString);
};
openRequest.onsuccess = function() {
var db = openRequest.result;
var transaction = db.transaction(['mystore'], 'readwrite');
var store = transaction.objectStore('mystore');
var request = store.get(key);
request.onsuccess = function (event) {
assert.equal(value, event.target.result.myvalue);
db.close();
done();
};
request.onerror = function (event) {
db.close();
throw new Error(event.toString);
};
};
};
request.onerror = function(event) {
db.close();
throw new Error(event.toString);
};
};
});
});
|
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.XPath;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using alby.core.threadpool ;
namespace alby.codegen.generator
{
public partial class <API key>
{
public Program p ;
public string fqview ;
public Exception exception ;
} // end class
public partial class <API key> : <API key>
{
protected <API key> _vgp ;
public <API key>( <API key> vgp )
{
_vgp = vgp ;
}
public override void Run()
{
Helper h = new Helper() ;
try
{
DoView( _vgp.p, _vgp.fqview ) ;
}
catch( Exception ex )
{
_vgp.exception = ex ;
h.Message( "[DoTable() EXCEPTION]\n{0}", ex ) ;
}
}
protected void DoView( Program p, string fqview )
{
Helper h = new Helper() ;
ColumnInfo ci = new ColumnInfo() ;
Tuple<string,string> schemaview = h.<API key>( fqview ) ;
string thedatabase = h.GetCsharpClassName( null, null, p._databaseName ) ;
string csharpnamespace = p._namespace + "." + p._viewSubDirectory;
string resourcenamespace = p._resourceNamespace + "." + p._viewSubDirectory;
string theclass = h.GetCsharpClassName( p.<API key>, schemaview.Item1, schemaview.Item2);
string csharpfile = p._directory + @"\" + p._viewSubDirectory + @"\" + theclass + ".cs" ;
string csharpfactoryfile = csharpfile.Replace(".cs", "Factory.cs");
string thefactoryclass = theclass + "Factory";
// config for this view, if any
string xpath = "/CodeGen/Views/View[@Class='" + theclass + "']" ;
XmlNode view = p._codegen.SelectSingleNode(xpath);
// select sql
string selectsql = "select * from {0} t ";
// do class
h.MessageVerbose( "[{0}]", csharpfile );
using ( StreamWriter sw = new StreamWriter( csharpfile, false, UTF8Encoding.UTF8 ) )
{
int tab = 0;
// header
h.WriteCodeGenHeader(sw);
h.WriteUsing(sw);
// namespace
using (NamespaceBlock nsb = new NamespaceBlock(sw, tab++, csharpnamespace))
{
using (ClassBlock cb = new ClassBlock(sw, tab++, theclass, "acr.RowBase"))
{
List< Tuple<string,string> > columns = ci.GetViewColumns( fqview ) ;
// properties and constructor
using (RowConstructorBlock conb = new RowConstructorBlock(sw, tab, theclass, columns, null, ""))
{}
} // end class
} // end namespace
} // eof
// do class factory
h.MessageVerbose( "[{0}]", csharpfactoryfile );
using (StreamWriter sw = new StreamWriter(csharpfactoryfile, false, UTF8Encoding.UTF8))
{
int tab = 0;
// header
h.WriteCodeGenHeader(sw);
h.WriteUsing(sw, p._namespace );
// namespace
using (NamespaceBlock nsb = new NamespaceBlock(sw, tab++, csharpnamespace))
{
using (ClassBlock cb = new ClassBlock(sw, tab++, thefactoryclass,
"acr.FactoryBase< " +
theclass + ", " +
"ns." + p.<API key> + "." + thedatabase + "<API key>, " +
"ns." + p.<API key> + "." + thedatabase + "Database >"
) )
{
// constructor
using (<API key> conb = new <API key>( sw, tab, fqview, selectsql, thefactoryclass))
{}
// default load all method
List<string> parameters = new List<string>();
Dictionary<string, string> parameterdictionary = new Dictionary<string, string>();
parameters = new List<string>() ;
parameters.Add("connˡ" );
parameters.Add("topNˡ" );
parameters.Add("orderByˡ" );
parameters.Add("tranˡ" );
parameterdictionary.Add("connˡ", "sds.SqlConnection");
parameterdictionary.Add("topNˡ", "int?");
parameterdictionary.Add("orderByˡ", "scg.List<acr.CodeGenOrderBy>");
parameterdictionary.Add("tranˡ", "sds.SqlTransaction");
// method
h.MessageVerbose("[{0}].[{1}].[{2}]", csharpnamespace, theclass, "Loadˡ");
using (<API key> mb = new <API key>(sw, tab, "Loadˡ", parameters, parameterdictionary, "", theclass, resourcenamespace))
{}
// load by where
parameters = new List<string>() ;
parameters.Add("connˡ" );
parameters.Add("whereˡ" );
parameters.Add("parametersˡ" );
parameters.Add("topNˡ" );
parameters.Add("orderByˡ" );
parameters.Add("tranˡ" );
parameterdictionary = new Dictionary<string, string>();
parameterdictionary.Add("connˡ", "sds.SqlConnection");
parameterdictionary.Add("whereˡ", "string");
parameterdictionary.Add("parametersˡ", "scg.List<sds.SqlParameter>");
parameterdictionary.Add("topNˡ", "int?");
parameterdictionary.Add("orderByˡ", "scg.List<acr.CodeGenOrderBy>");
parameterdictionary.Add("tranˡ", "sds.SqlTransaction");
h.MessageVerbose("[{0}].[{1}].[{2}]", csharpnamespace, theclass, "LoadByWhereˡ");
using (<API key> mb = new <API key>(sw, tab, "LoadByWhereˡ", parameters, parameterdictionary, "", theclass, resourcenamespace))
{}
// other methods
if ( view != null )
{
XmlNodeList xmlmethods = view.SelectNodes("Methods/Method");
foreach ( XmlNode xmlmethod in xmlmethods )
{
string themethod = xmlmethod.SelectSingleNode("@Name").InnerText;
// where resource
string whereresource = xmlmethod.SelectSingleNode("@Where").InnerText;
// parameters
parameters = new List<string>() ;
parameters.Add("connˡ" );
XmlNodeList xmlparameters = xmlmethod.SelectNodes("Parameters/Parameter");
foreach ( XmlNode xmlparameter in xmlparameters )
parameters.Add( xmlparameter.SelectSingleNode("@Name").InnerText );
parameters.Add("topNˡ" );
parameters.Add("orderByˡ" );
parameters.Add("tranˡ" );
parameterdictionary = new Dictionary<string, string>();
parameterdictionary.Add("connˡ", "sds.SqlConnection");
xmlparameters = xmlmethod.SelectNodes("Parameters/Parameter");
foreach ( XmlNode xmlparameter in xmlparameters )
parameterdictionary.Add( xmlparameter.SelectSingleNode("@Name").InnerText,
xmlparameter.SelectSingleNode("@Type").InnerText );
parameterdictionary.Add("topNˡ", "int?");
parameterdictionary.Add("orderByˡ", "scg.List<acr.CodeGenOrderBy>");
parameterdictionary.Add("tranˡ", "sds.SqlTransaction");
// method
h.MessageVerbose( "[{0}].[{1}].method [{2}]", csharpnamespace, theclass, themethod );
using (<API key> mb = new <API key>(sw, tab, themethod, parameters, parameterdictionary, whereresource, theclass, resourcenamespace))
{}
}
}
} // end class
} // end namespace
} // eof
} // end do view
} // end class
}
|
.progressbar-top {
margin-top: -24px;
margin-bottom: 24px;
width: 70%;
margin-left: -24px;
position: absolute;
}
.check-icon {
color: #21C9A1;
}
.overdue-text {
color: #ce2424;
font-weight: bold;
}
.alert-icon {
color: #ce2424;
}
.offset-top-mat-icon {
margin-top: 17px;
}
.pointer {
cursor: pointer;
}
.member-initials {
background-color: lightgrey;
height: 24px;
min-width: 25px;
font-size: 12px;
line-height: 24px;
text-align: center;
padding: 2px;
border-radius: 4px;
margin-right: 2px;
}
.text-area {
resize: none;
}
.margin {
margin-right: 5px;
}
|
#if defined(HAVE_CONFIG_H)
#include <config/bitcoin-config.h>
#endif
#include <chainparams.h>
#include <chainparamsbase.h>
#include <logging.h>
#include <util/system.h>
#include <util/translation.h>
#include <util/url.h>
#include <wallet/wallettool.h>
#include <functional>
const std::function<std::string(const char*)> G_TRANSLATION_FUN = nullptr;
UrlDecodeFn* const URL_DECODE = nullptr;
static void SetupWalletToolArgs(ArgsManager& argsman)
{
SetupHelpOptions(argsman);
<API key>(argsman);
argsman.AddArg("-datadir=<dir>", "Specify data directory", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
argsman.AddArg("-wallet=<wallet-name>", "Specify wallet name", ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::OPTIONS);
argsman.AddArg("-debug=<category>", "Output debugging information (default: 0).", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
argsman.AddArg("-printtoconsole", "Send trace/debug info to console (default: 1 when no -debug is true, 0 otherwise).", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
argsman.AddArg("info", "Get wallet info", ArgsManager::ALLOW_ANY, OptionsCategory::COMMANDS);
argsman.AddArg("create", "Create new wallet file", ArgsManager::ALLOW_ANY, OptionsCategory::COMMANDS);
argsman.AddArg("salvage", "Attempt to recover private keys from a corrupt wallet. Warning: 'salvage' is experimental.", ArgsManager::ALLOW_ANY, OptionsCategory::COMMANDS);
}
static bool WalletAppInit(int argc, char* argv[])
{
SetupWalletToolArgs(gArgs);
std::string error_message;
if (!gArgs.ParseParameters(argc, argv, error_message)) {
tfm::format(std::cerr, "Error parsing command line arguments: %s\n", error_message);
return false;
}
if (argc < 2 || HelpRequested(gArgs)) {
std::string usage = strprintf("%s elements-wallet version", PACKAGE_NAME) + " " + FormatFullVersion() + "\n\n" +
"elements-wallet is an offline tool for creating and interacting with " PACKAGE_NAME " wallet files.\n" +
"By default elements-wallet will act on wallets in the default mainnet wallet directory in the datadir.\n" +
"To change the target wallet, use the -datadir, -wallet and -testnet/-regtest arguments.\n\n" +
"Usage:\n" +
" elements-wallet [options] <command>\n\n" +
gArgs.GetHelpMessage();
tfm::format(std::cout, "%s", usage);
return false;
}
// check for printtoconsole, allow -debug
LogInstance().m_print_to_console = gArgs.GetBoolArg("-printtoconsole", gArgs.GetBoolArg("-debug", false));
if (!CheckDataDirOption()) {
tfm::format(std::cerr, "Error: Specified data directory \"%s\" does not exist.\n", gArgs.GetArg("-datadir", ""));
return false;
}
// Check for chain settings (Params() calls are only valid after this clause)
SelectParams(gArgs.GetChainName());
return true;
}
int main(int argc, char* argv[])
{
#ifdef WIN32
util::WinCmdLineArgs winArgs;
std::tie(argc, argv) = winArgs.get();
#endif
SetupEnvironment();
RandomInit();
try {
if (!WalletAppInit(argc, argv)) return EXIT_FAILURE;
} catch (const std::exception& e) {
<API key>(&e, "WalletAppInit()");
return EXIT_FAILURE;
} catch (...) {
<API key>(nullptr, "WalletAppInit()");
return EXIT_FAILURE;
}
std::string method {};
for(int i = 1; i < argc; ++i) {
if (!IsSwitchChar(argv[i][0])) {
if (!method.empty()) {
tfm::format(std::cerr, "Error: two methods provided (%s and %s). Only one method should be provided.\n", method, argv[i]);
return EXIT_FAILURE;
}
method = argv[i];
}
}
if (method.empty()) {
tfm::format(std::cerr, "No method provided. Run `elements-wallet -help` for valid methods.\n");
return EXIT_FAILURE;
}
// A name must be provided when creating a file
if (method == "create" && !gArgs.IsArgSet("-wallet")) {
tfm::format(std::cerr, "Wallet name must be provided when creating a new wallet.\n");
return EXIT_FAILURE;
}
std::string name = gArgs.GetArg("-wallet", "");
ECCVerifyHandle globalVerifyHandle;
ECC_Start();
if (!WalletTool::<API key>(method, name))
return EXIT_FAILURE;
ECC_Stop();
return EXIT_SUCCESS;
}
|
<?php
namespace App\Common\Models\Order\Mysql;
use App\Common\Models\Base\Mysql\Base;
class OrderCommon extends Base
{
/**
* -
* This model is mapped to the table iorder_common
*/
public function getSource()
{
return 'iorder_common';
}
public function reorganize(array $data)
{
$data = parent::reorganize($data);
// $data['is_smtp'] = $this->changeToBoolean($data['is_smtp']);
// $data['access_token_expire'] = $this->changeToValidDate($data['access_token_expire']);
return $data;
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Treorisoft.Net.Utilities
{
<summary>
Provides properties and instance methods for sending files over a <see cref="Winsock"/> objects.
</summary>
[Serializable]
public class FileData : ISerializable
{
<summary>
Initializes a new instance of the <see cref="FileData"/> class.
</summary>
<param name="info">A <see cref="FileInfo"/> object that contains data about the file.</param>
public FileData(FileInfo info)
{
Guid = Guid.NewGuid();
FileName = info.Name;
FileSize = info.Length;
Info = info;
}
<summary>
Initializes a new instance of the <see cref="FileData"/> class with serialized data.
</summary>
<param name="info">The object that holds the serialized object data.</param>
<param name="context">The contextual information about the source or destination.</param>
protected FileData(SerializationInfo info, StreamingContext context)
{
Guid = (Guid)info.GetValue("guid", typeof(Guid));
FileName = info.GetString("filename");
FileSize = info.GetInt64("filesize");
}
<summary>
Implements the <see cref="ISerializable"/> interface and returns the data needed to serialize the <see cref="FileData"/> object.
</summary>
<param name="info">A SerializationInfo object containing information required to serialize the FileData object.</param>
<param name="context">A StreamingContext object containing the source and destination of the serialized stream associated with the FileData object.</param>
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("guid", Guid);
info.AddValue("filename", FileName);
info.AddValue("filesize", FileSize);
}
<summary>
Gets a <see cref="Guid"/> identifier for the file.
</summary>
public Guid Guid { get; private set; }
<summary>
Gets the name of the file.
</summary>
public string FileName { get; private set; }
<summary>
Gets the size, in bytes, of the file.
</summary>
public long FileSize { get; private set; }
<summary>
Gets the <see cref="FileInfo"/> of the file being transmitted.
</summary>
<remarks>
During sending this contains the details of the actual file being transmitted.
During receiving this contains the details of a temporary file, that upon arrival can be moved to another location.
</remarks>
public FileInfo Info { get; internal set; }
#region Sending/Receiving Helpers
<summary>
Field backing the SyncRoot property.
</summary>
internal object _syncRoot = null;
<summary>
Field backing the MetaSize property.
</summary>
internal static int _fileDataMetaSize = -1;
<summary>
Gets an object that can be used to synchronize access to the file being read/written.
</summary>
private object SyncRoot
{
get
{
if (_syncRoot == null)
Interlocked.CompareExchange(ref _syncRoot, new object(), null);
return _syncRoot;
}
}
<summary>
Gets a value the estimates the size of an empty <see cref="FileDataPart"/> object.
</summary>
internal static int MetaSize
{
get
{
if (_fileDataMetaSize < 0)
_fileDataMetaSize = EstimatePartSize(0) + 1;
return _fileDataMetaSize;
}
}
<summary>
Gets an estimate of a <see cref="FileDataPart"/> object of the specified data size.
</summary>
<param name="size">The size of the data that should be used in the size estimate.</param>
<returns>The estimated size, in bytes, of a serialized <see cref="FileDataPart"/>.</returns>
internal static int EstimatePartSize(int size)
{
return EstimatePartSize(Guid.Empty, long.MaxValue, size);
}
<summary>
Gets an estimate of a <see cref="FileDataPart"/>.
</summary>
<param name="guid">The <see cref="Guid"/> that should be used in the size estimate.</param>
<param name="start">The start position that should be used in the size estimate.</param>
<param name="size">The size of the data that should be used in the size estimate.</param>
<returns>The estimated size, in bytes, of a serialized <see cref="FileDataPart"/>.</returns>
internal static int EstimatePartSize(Guid guid, long start, int size)
{
var part = new FileDataPart(guid, start, new byte[size]);
var bytes = ObjectPacker.Pack(part);
return bytes.Length + PacketHeader.HeaderSize(bytes.Length);
}
#endregion
#region Sending
<summary>
Gets the total number of bytes sent.
</summary>
internal long SentBytes { get; set; } = 0;
<summary>
Gets a boolean value indicating whether if the file has been completely sent or not.
</summary>
internal bool SendCompleted { get { return (SentBytes == FileSize); } }
<summary>
Gets the next <see cref="FileDataPart"/> that will be sent over the network.
</summary>
<param name="bufferSize">The size of the buffer and amount of data to return.</param>
<returns>The bufferSize is adjusted by an estimate of how large the metadata would be, so that the size of the serialized <see cref="FileDataPart"/> should be the same as the bufferSize.</returns>
internal FileDataPart GetNextPart(int bufferSize)
{
if (SendCompleted) return null;
if (Info == null) throw new <API key>("File information not found.");
if (!Info.Exists) throw new <API key>(Info.FullName);
bufferSize -= MetaSize;
byte[] buffer = new byte[bufferSize];
lock (SyncRoot)
{
using (FileStream fs = new FileStream(Info.FullName, FileMode.Open, FileAccess.Read))
{
fs.Seek(SentBytes, SeekOrigin.Begin);
int readSize = fs.Read(buffer, 0, bufferSize);
byte[] sizedBuffer = ArrayMethods.Shrink(ref buffer, readSize);
var part = new FileDataPart(Guid, SentBytes, sizedBuffer);
SentBytes += readSize;
return part;
}
}
}
<summary>
Gets the total size of all the parts of the file at the given buffer size.
</summary>
<param name="bufferSize">The size of the buffer and amount of data to estimate with.</param>
<returns>
This routine is used by <see cref="SendProgress"/> to help determine the total number of bytes to send, and therefore also the percent completed.
The bufferSize is adjusted by an estimate of how large the metadata would be, so that the size of the serialized <see cref="FileDataPart"/> should be the same as the bufferSize.
</returns>
internal long GetTotalPartSize(int bufferSize)
{
long sum = 0;
foreach (int size in GetPartSizes(bufferSize))
sum += size;
return sum;
}
<summary>
Gets the sizes of all the parts of the file at the given buffer size.
</summary>
<param name="bufferSize">The size of the buffer and amount of data to estimate with.</param>
<returns>
Returns an IEnumerable containing the sizes of all the different parts of the file - including the <see cref="FileData"/> header.
</returns>
internal IEnumerable<int> GetPartSizes(int bufferSize)
{
if (Info == null) throw new <API key>("File information not found.");
if (!Info.Exists) throw new <API key>(Info.FullName);
var bytes = ObjectPacker.Pack(this);
yield return bytes.Length + PacketHeader.HeaderSize(bytes.Length);
bufferSize -= MetaSize;
long fileSize = Info.Length;
long start = 0;
while (fileSize > 0)
{
if (fileSize > bufferSize)
{
yield return EstimatePartSize(Guid, start, bufferSize);
fileSize -= bufferSize;
start += bufferSize;
}
else
{
yield return EstimatePartSize(Guid, start, (int)fileSize);
fileSize = 0;
}
}
}
#endregion
#region Receiving
<summary>
Gets the total number of received bytes.
</summary>
public long ReceivedBytes { get; private set; } = 0;
<summary>
Gets a boolean value indicating if the file has been completely received or not.
</summary>
public bool ReceiveCompleted { get { return (ReceivedBytes == FileSize); } }
<summary>
Gets the size of the last received <see cref="FileDataPart"/>.
</summary>
<remarks>This is used to help setup the <see cref="<API key>"/> that is raised.</remarks>
internal int LastReceivedSize { get; set; }
<summary>
Receives the <see cref="FileDataPart"/> into the specified file.
</summary>
<param name="fileName">The fully qualified name of the file, or the relative file name. Do not end the path with the directory separator character.</param>
<param name="part">The <see cref="FileDataPart"/> to be received.</param>
internal void ReceivePart(string fileName, FileDataPart part)
{
ReceivePart(new FileInfo(fileName), part);
}
<summary>
Receives the <see cref="FileDataPart"/> into the specified file.
</summary>
<param name="file">A <see cref="FileInfo"/> object containing the fully qualified name of the file to receiving the data to.</param>
<param name="part">The <see cref="FileDataPart"/> to be received.</param>
internal void ReceivePart(FileInfo file, FileDataPart part)
{
if (ReceiveCompleted)
throw new <API key>("Receive operation for this file has already been completed.");
lock (SyncRoot)
{
using (FileStream fs = new FileStream(file.FullName, FileMode.OpenOrCreate, FileAccess.Write))
{
fs.Seek(part.Start, SeekOrigin.Begin);
fs.Write(part.Data, 0, part.Data.Length);
}
LastReceivedSize = part.Data.Length;
ReceivedBytes += part.Data.Length;
}
}
#endregion
}
}
|
package main
import "fmt"
func main() {
fmt.Println("go" + "lang")
fmt.Println("1+1 =", 1+1)
fmt.Println("7.0/3.0 =", 7.0/3.0)
fmt.Println(true && false)
fmt.Println(true || false)
fmt.Println(!true)
}
|
import React from 'react'
import DocumentTitle from '<API key>'
import ReactHeight from 'react-height'
import Header from './header/header'
import Content from './content/content'
import Footer from './footer/footer'
import { APP_NAME } from '../constants'
class Layout extends React.Component {
render() {
const hfStyle = {
flex: 'none'
}
const contentStyle = {
flex: 1
}
const containerStyle = {
display: 'flex',
minHeight: window.innerHeight,
flexDirection: 'column'
}
return (
<div style={containerStyle}>
<DocumentTitle title={APP_NAME}/>
<Header style={hfStyle}/>
<Content style={contentStyle}/>
<Footer style={hfStyle}/>
</div>
)
}
}
export default Layout
|
import Graph from 'graphology-types';
export default function mergePath(graph: Graph, nodes: Array<unknown>): void;
|
var i18n = require('i18n');
var _ = require('lodash');
exports.register = function (plugin, options, next) {
i18n.configure(options);
plugin.ext('onPreResponse', function (request, extNext) {
// If is an error message
if(request.response.isBoom) {
i18n.setLocale(getLocale(request, options));
request.response.output.payload.message = i18n.__(request.response.output.payload.message);
return extNext(request.response);
}
extNext();
});
next();
};
var getLocale = function(request, options) {
i18n.init(request.raw.req);
if(_.contains(_.keys(i18n.getCatalog()), request.raw.req.language)) {
return request.raw.req.language;
} else {
return options.defaultLocale;
}
};
|
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="utf-8">
<title>Henge: b_ine</title>
<link rel="stylesheet" href="/vendor/bootstrap-3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="/css/site.css">
</head>
<body>
<div id="staticBody">
<header>
<h1><img src="/imgs/logo.svg" alt="henge"></h1>
</header>
<h2>#436 b_ine</h2>
<ul id="words">
<li>baseline</li>
<li>beeline</li>
<li>benedictine</li>
<li>benzine</li>
<li>bloodline</li>
<li>borderline</li>
<li>bovine</li>
<li>bowline</li>
<li>brigantine</li>
<li>brine</li>
<li>byline</li>
<li>byzantine</li>
</ul>
</div>
<div id="CircleApp" data-floor="37" data-floor-pos="3"></div>
<script type="text/javascript" src="/CircleApp.bundle.js"></script>
<script>
(function(i,s,o,g,r,a,m){i['<API key>']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.<API key>(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https:
ga('create', 'UA-631498-5', 'auto');
ga('send', 'pageview');
</script>
</body>
</html>
|
from nintendo import dauth, switch
from anynet import http
import pytest
CHALLENGE_REQUEST = \
"POST /v6/challenge HTTP/1.1\r\n" \
"Host: 127.0.0.1:12345\r\n" \
"User-Agent: libcurl (nnDauth; <API key>; SDK 12.3.0.0)\r\n" \
"Accept: */*\r\n" \
"<API key>: FA\r\n" \
"Content-Length: 17\r\n" \
"Content-Type: application/<API key>\r\n\r\n" \
"key_generation=11"
TOKEN_REQUEST = \
"POST /v6/device_auth_token HTTP/1.1\r\n" \
"Host: 127.0.0.1:12345\r\n" \
"User-Agent: libcurl (nnDauth; <API key>; SDK 12.3.0.0)\r\n" \
"Accept: */*\r\n" \
"<API key>: FA\r\n" \
"Content-Length: 211\r\n" \
"Content-Type: application/<API key>\r\n\r\n" \
"challenge=<API key>=&" \
"client_id=8f849b5d34778d8e&ist=false&key_generation=11&" \
"system_version=CusHY#000c0000#<API key>=&" \
"mac=<API key>"
@pytest.mark.anyio
async def test_dauth():
async def handler(client, request):
if request.path == "/v6/challenge":
assert request.encode().decode() == CHALLENGE_REQUEST
response = http.HTTPResponse(200)
response.json = {
"challenge": "<API key>=",
"data": "<API key>=="
}
return response
else:
assert request.encode().decode() == TOKEN_REQUEST
response = http.HTTPResponse(200)
response.json = {
"device_auth_token": "device token"
}
return response
async with http.serve(handler, "127.0.0.1", 12345):
keys = switch.KeySet()
keys["<API key>"] = bytes.fromhex("<API key>")
keys["master_key_0a"] = bytes.fromhex("<API key>")
client = dauth.DAuthClient(keys)
client.set_url("127.0.0.1:12345")
client.set_system_version(1200)
client.set_context(None)
response = await client.device_token(client.BAAS)
token = response["device_auth_token"]
assert token == "device token"
|
import expect from 'expect';
import createStore from './createStore';
describe('createStore()', () => {
let store;
beforeEach(() => {
store = createStore();
});
it('should write data and return its key when write() is called', () => {
const hash = store.write({ hello: 'world' });
expect(hash).toBe(store.keys()[0]);
});
it('should return data when read() is called with a valid key', () => {
const hash = store.write({ hello: 'world' });
expect(store.read(hash)).toEqual({ hello: 'world' });
});
it('should throw an error when read() is called with an invalid key', () => {
store.write({ hello: 'world' });
expect(() => store.read('wrong')).toThrow(/Entry wrong not found/);
});
it('should return all keys when keys() is called', () => {
const hash1 = store.write({ hello: 'world' });
const hash2 = store.write({ hello2: 'world2' });
expect(store.keys()).toEqual([
hash1,
hash2,
]);
});
it('should return all store content when toJSON() is called', () => {
const hash1 = store.write({ hello: 'world' });
const hash2 = store.write({ hello2: 'world2' });
expect(store.toJSON()).toEqual({
[hash1]: {
hello: 'world',
},
[hash2]: {
hello2: 'world2',
},
});
});
it('should init the store if a snapshot is given', () => {
const localStore = createStore({
ae3: {
hello: 'world',
},
});
expect(localStore.read('ae3')).toEqual({
hello: 'world',
});
});
it('should write data with the given hash if provided', () => {
const hash = store.write({ hello: 'world' }, 'forcedHash');
expect(hash).toBe('forcedHash');
expect(store.keys()[0]).toBe('forcedHash');
expect(store.read('forcedHash')).toEqual({ hello: 'world' });
});
it('should notify any subscriber when something is written into the store', () => {
const subscriber1 = expect.createSpy();
store.subscribe(subscriber1);
const subscriber2 = expect.createSpy();
store.subscribe(subscriber2);
const hash = store.write({ hello: 'world' });
expect(subscriber1).<API key>(hash);
expect(subscriber2).<API key>(hash);
store.unsubscribe(subscriber1);
const hash2 = store.write({ hello: 'earth' });
expect(subscriber1.calls.length).toBe(1);
expect(subscriber2).<API key>(hash2);
expect(subscriber2.calls.length).toBe(2);
});
});
|
package com.jxtech.distributed.zookeeper.pool;
import java.util.<API key>;
import org.apache.commons.pool.ObjectPool;
import org.apache.commons.pool.<API key>;
import org.apache.commons.pool.impl.StackObjectPool;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.jxtech.distributed.Configuration;
/**
* ZK
*
* @author wmzsoft@gmail.com
*/
public class <API key> {
private static final Logger LOG = LoggerFactory.getLogger(<API key>.class);
protected static <API key> instance;
private ObjectPool pool;
private <API key>() {
init();
}
/**
*
*
* @return
*/
public static <API key> getInstance() {
if (instance == null) {
instance = new <API key>();
}
return instance;
}
/**
* zookeeper
*
* @param config
*/
private void init() {
if (pool != null) {
LOG.debug("pool is already init");
return;
}
Configuration config = Configuration.getInstance();
if (!config.isDeploy()) {
LOG.info("Can't init , deploy = false.");
return;
}
<API key> factory = new <API key>(config);
int maxIdle = config.getMaxIdle();
int initIdleCapacity = config.getInitIdleCapacity();
pool = new StackObjectPool(factory, maxIdle, initIdleCapacity);
for (int i = 0; i < initIdleCapacity; i++) {
try {
pool.addObject();
} catch (<API key> | <API key> ex) {
LOG.error(ex.getMessage(), ex);
} catch (Exception ex) {
LOG.error(ex.getMessage(), ex);
}
}
}
/**
* ZK
*
* @return
*/
public ZooKeeper borrowObject() {
if (pool != null) {
try {
return (ZooKeeper) pool.borrowObject();
} catch (<API key> | <API key> ex) {
LOG.error(ex.getMessage(), ex);
} catch (Exception e) {
LOG.error(e.getMessage(), e);
}
}
return null;
}
/**
* ZK
*
* @param zk
*/
public void returnObject(ZooKeeper zk) {
if (pool != null && zk != null) {
try {
pool.returnObject(zk);
} catch (Exception ex) {
LOG.error(ex.getMessage(), ex);
}
}
}
public void close() {
if (pool != null) {
try {
pool.close();
LOG.info("ZK");
} catch (Exception ex) {
LOG.error(ex.getMessage(), ex);
}
}
}
}
|
#include "paymentserver.h"
#include "Testcoinunits.h"
#include "guiutil.h"
#include "optionsmodel.h"
#include "base58.h"
#include "chainparams.h"
#include "ui_interface.h"
#include "util.h"
#include "wallet.h"
#include <cstdlib>
#include <openssl/x509.h>
#include <openssl/x509_vfy.h>
#include <QApplication>
#include <QByteArray>
#include <QDataStream>
#include <QDateTime>
#include <QDebug>
#include <QFile>
#include <QFileOpenEvent>
#include <QHash>
#include <QList>
#include <QLocalServer>
#include <QLocalSocket>
#include <<API key>>
#include <QNetworkProxy>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QSslCertificate>
#include <QSslError>
#include <QSslSocket>
#include <QStringList>
#include <QTextDocument>
#if QT_VERSION < 0x050000
#include <QUrl>
#else
#include <QUrlQuery>
#endif
using namespace std;
const int <API key> = 1000; // milliseconds
const QString Testcoin_IPC_PREFIX("Testcoin:");
// BIP70 payment protocol messages
const char* <API key> = "PaymentACK";
const char* <API key> = "PaymentRequest";
// BIP71 payment protocol media types
const char* <API key> = "application/Testcoin-payment";
const char* <API key> = "application/Testcoin-paymentack";
const char* <API key> = "application/<API key>";
// BIP70 max payment request size in bytes (DoS protection)
const qint64 <API key> = 50000;
X509_STORE* PaymentServer::certStore = NULL;
void PaymentServer::freeCertStore()
{
if (PaymentServer::certStore != NULL)
{
X509_STORE_free(PaymentServer::certStore);
PaymentServer::certStore = NULL;
}
}
// Create a name that is unique for:
// testnet / non-testnet
// data directory
static QString ipcServerName()
{
QString name("TestcoinQt");
// Append a simple hash of the datadir
// Note that GetDataDir(true) returns a different path
// for -testnet versus main net
QString ddir(QString::fromStdString(GetDataDir(true).string()));
name.append(QString::number(qHash(ddir)));
return name;
}
// We store payment URIs and requests received before
// the main GUI window is up and ready to ask the user
// to send payment.
static QList<QString> <API key>;
static void <API key>(const QSslCertificate& cert)
{
qDebug() << "<API key> : Payment server found an invalid certificate: " << cert.subjectInfo(QSslCertificate::CommonName);
}
// Load OpenSSL's list of root certificate authorities
void PaymentServer::LoadRootCAs(X509_STORE* _store)
{
if (PaymentServer::certStore == NULL)
atexit(PaymentServer::freeCertStore);
else
freeCertStore();
// Unit tests mostly use this, to pass in fake root CAs:
if (_store)
{
PaymentServer::certStore = _store;
return;
}
// Normal execution, use either -rootcertificates or system certs:
PaymentServer::certStore = X509_STORE_new();
// Note: use "-system-" default here so that users can pass -rootcertificates=""
// and get 'I don't like X.509 certificates, don't trust anybody' behavior:
QString certFile = QString::fromStdString(GetArg("-rootcertificates", "-system-"));
if (certFile.isEmpty())
return; // Empty store
QList<QSslCertificate> certList;
if (certFile != "-system-")
{
certList = QSslCertificate::fromPath(certFile);
// Use those certificates when fetching payment requests, too:
QSslSocket::<API key>(certList);
}
else
certList = QSslSocket::<API key> ();
int nRootCerts = 0;
const QDateTime currentTime = QDateTime::currentDateTime();
foreach (const QSslCertificate& cert, certList)
{
if (currentTime < cert.effectiveDate() || currentTime > cert.expiryDate()) {
<API key>(cert);
continue;
}
#if QT_VERSION >= 0x050000
if (cert.isBlacklisted()) {
<API key>(cert);
continue;
}
#endif
QByteArray certData = cert.toDer();
const unsigned char *data = (const unsigned char *)certData.data();
X509* x509 = d2i_X509(0, &data, certData.size());
if (x509 && X509_STORE_add_cert(PaymentServer::certStore, x509))
{
// Note: X509_STORE_free will free the X509* objects when
// the PaymentServer is destroyed
++nRootCerts;
}
else
{
<API key>(cert);
continue;
}
}
qWarning() << "PaymentServer::LoadRootCAs : Loaded " << nRootCerts << " root certificates";
// Project for another day:
// Fetch certificate revocation lists, and add them to certStore.
// Issues to consider:
// performance (start a thread to fetch in background?)
// privacy (fetch through tor/proxy so IP address isn't revealed)
// would it be easier to just use a compiled-in blacklist?
// or use Qt's blacklist?
// "certificate stapling" with server-side caching is more efficient
}
// Sending to the server is done synchronously, at startup.
// If the server isn't already running, startup continues,
// and the items in savedPaymentRequest will be handled
// when uiReady() is called.
// Warning: ipcSendCommandLine() is called early in init,
// so don't use "emit message()", but "QMessageBox::"!
void PaymentServer::ipcParseCommandLine(int argc, char* argv[])
{
for (int i = 1; i < argc; i++)
{
QString arg(argv[i]);
if (arg.startsWith("-"))
continue;
// If the Testcoin: URI contains a payment request, we are not able to detect the
// network as that would require fetching and parsing the payment request.
// That means clicking such an URI which contains a testnet payment request
// will start a mainnet instance and throw a "wrong network" error.
if (arg.startsWith(Testcoin_IPC_PREFIX, Qt::CaseInsensitive)) // Testcoin: URI
{
<API key>.append(arg);
SendCoinsRecipient r;
if (GUIUtil::parseTestcoinURI(arg, &r) && !r.address.isEmpty())
{
CTestcoinAddress address(r.address.toStdString());
if (address.IsValid(Params(CBaseChainParams::MAIN)))
{
SelectParams(CBaseChainParams::MAIN);
}
else if (address.IsValid(Params(CBaseChainParams::TESTNET)))
{
SelectParams(CBaseChainParams::TESTNET);
}
}
}
else if (QFile::exists(arg)) // Filename
{
<API key>.append(arg);
PaymentRequestPlus request;
if (<API key>(arg, request))
{
if (request.getDetails().network() == "main")
{
SelectParams(CBaseChainParams::MAIN);
}
else if (request.getDetails().network() == "test")
{
SelectParams(CBaseChainParams::TESTNET);
}
}
}
else
{
// Printing to debug.log is about the best we can do here, the
// GUI hasn't started yet so we can't pop up a message box.
qWarning() << "PaymentServer::ipcSendCommandLine : Payment request file does not exist: " << arg;
}
}
}
// Sending to the server is done synchronously, at startup.
// If the server isn't already running, startup continues,
// and the items in savedPaymentRequest will be handled
// when uiReady() is called.
bool PaymentServer::ipcSendCommandLine()
{
bool fResult = false;
foreach (const QString& r, <API key>)
{
QLocalSocket* socket = new QLocalSocket();
socket->connectToServer(ipcServerName(), QIODevice::WriteOnly);
if (!socket->waitForConnected(<API key>))
{
delete socket;
socket = NULL;
return false;
}
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_0);
out << r;
out.device()->seek(0);
socket->write(block);
socket->flush();
socket->waitForBytesWritten(<API key>);
socket-><API key>();
delete socket;
socket = NULL;
fResult = true;
}
return fResult;
}
PaymentServer::PaymentServer(QObject* parent, bool startLocalServer) :
QObject(parent),
saveURIs(true),
uriServer(0),
netManager(0),
optionsModel(0)
{
// Verify that the version of the library that we linked against is
// compatible with the version of the headers we compiled against.
<API key>;
// Install global event filter to catch QFileOpenEvents
// on Mac: sent when you click Testcoin: links
// other OSes: helpful when dealing with payment request files (in the future)
if (parent)
parent->installEventFilter(this);
QString name = ipcServerName();
// Clean up old socket leftover from a crash:
QLocalServer::removeServer(name);
if (startLocalServer)
{
uriServer = new QLocalServer(this);
if (!uriServer->listen(name)) {
// constructor is called early in init, so don't use "emit message()" here
QMessageBox::critical(0, tr("Payment request error"),
tr("Cannot start Testcoin: click-to-pay handler"));
}
else {
connect(uriServer, SIGNAL(newConnection()), this, SLOT(handleURIConnection()));
connect(this, SIGNAL(receivedPaymentACK(QString)), this, SLOT(handlePaymentACK(QString)));
}
}
}
PaymentServer::~PaymentServer()
{
google::protobuf::<API key>();
}
// OSX-specific way of handling Testcoin: URIs and
// PaymentRequest mime types
bool PaymentServer::eventFilter(QObject *object, QEvent *event)
{
// clicking on Testcoin: URIs creates FileOpen events on the Mac
if (event->type() == QEvent::FileOpen)
{
QFileOpenEvent *fileEvent = static_cast<QFileOpenEvent*>(event);
if (!fileEvent->file().isEmpty())
handleURIOrFile(fileEvent->file());
else if (!fileEvent->url().isEmpty())
handleURIOrFile(fileEvent->url().toString());
return true;
}
return QObject::eventFilter(object, event);
}
void PaymentServer::initNetManager()
{
if (!optionsModel)
return;
if (netManager != NULL)
delete netManager;
// netManager is used to fetch paymentrequests given in Testcoin: URIs
netManager = new <API key>(this);
QNetworkProxy proxy;
// Query active SOCKS5 proxy
if (optionsModel->getProxySettings(proxy)) {
netManager->setProxy(proxy);
qDebug() << "PaymentServer::initNetManager : Using SOCKS5 proxy" << proxy.hostName() << ":" << proxy.port();
}
else
qDebug() << "PaymentServer::initNetManager : No active proxy server found.";
connect(netManager, SIGNAL(finished(QNetworkReply*)),
this, SLOT(netRequestFinished(QNetworkReply*)));
connect(netManager, SIGNAL(sslErrors(QNetworkReply*, const QList<QSslError> &)),
this, SLOT(reportSslErrors(QNetworkReply*, const QList<QSslError> &)));
}
void PaymentServer::uiReady()
{
initNetManager();
saveURIs = false;
foreach (const QString& s, <API key>)
{
handleURIOrFile(s);
}
<API key>.clear();
}
void PaymentServer::handleURIOrFile(const QString& s)
{
if (saveURIs)
{
<API key>.append(s);
return;
}
if (s.startsWith(Testcoin_IPC_PREFIX, Qt::CaseInsensitive)) // Testcoin: URI
{
#if QT_VERSION < 0x050000
QUrl uri(s);
#else
QUrlQuery uri((QUrl(s)));
#endif
if (uri.hasQueryItem("r")) // payment request URI
{
QByteArray temp;
temp.append(uri.queryItemValue("r"));
QString decoded = QUrl::fromPercentEncoding(temp);
QUrl fetchUrl(decoded, QUrl::StrictMode);
if (fetchUrl.isValid())
{
qDebug() << "PaymentServer::handleURIOrFile : fetchRequest(" << fetchUrl << ")";
fetchRequest(fetchUrl);
}
else
{
qWarning() << "PaymentServer::handleURIOrFile : Invalid URL: " << fetchUrl;
emit message(tr("URI handling"),
tr("Payment request fetch URL is invalid: %1").arg(fetchUrl.toString()),
CClientUIInterface::ICON_WARNING);
}
return;
}
else // normal URI
{
SendCoinsRecipient recipient;
if (GUIUtil::parseTestcoinURI(s, &recipient))
{
CTestcoinAddress address(recipient.address.toStdString());
if (!address.IsValid()) {
emit message(tr("URI handling"), tr("Invalid payment address %1").arg(recipient.address),
CClientUIInterface::MSG_ERROR);
}
else
emit <API key>(recipient);
}
else
emit message(tr("URI handling"),
tr("URI cannot be parsed! This can be caused by an invalid Testcoin address or malformed URI parameters."),
CClientUIInterface::ICON_WARNING);
return;
}
}
if (QFile::exists(s)) // payment request file
{
PaymentRequestPlus request;
SendCoinsRecipient recipient;
if (!<API key>(s, request))
{
emit message(tr("Payment request file handling"),
tr("Payment request file cannot be read! This can be caused by an invalid payment request file."),
CClientUIInterface::ICON_WARNING);
}
else if (<API key>(request, recipient))
emit <API key>(recipient);
return;
}
}
void PaymentServer::handleURIConnection()
{
QLocalSocket *clientConnection = uriServer-><API key>();
while (clientConnection->bytesAvailable() < (int)sizeof(quint32))
clientConnection->waitForReadyRead();
connect(clientConnection, SIGNAL(disconnected()),
clientConnection, SLOT(deleteLater()));
QDataStream in(clientConnection);
in.setVersion(QDataStream::Qt_4_0);
if (clientConnection->bytesAvailable() < (int)sizeof(quint16)) {
return;
}
QString msg;
in >> msg;
handleURIOrFile(msg);
}
// Warning: <API key>() is used in ipcSendCommandLine()
// so don't use "emit message()", but "QMessageBox::"!
bool PaymentServer::<API key>(const QString& filename, PaymentRequestPlus& request)
{
QFile f(filename);
if (!f.open(QIODevice::ReadOnly)) {
qWarning() << QString("PaymentServer::%1: Failed to open %2").arg(__func__).arg(filename);
return false;
}
// BIP70 DoS protection
if (f.size() > <API key>) {
qWarning() << QString("PaymentServer::%1: Payment request %2 is too large (%3 bytes, allowed %4 bytes).")
.arg(__func__)
.arg(filename)
.arg(f.size())
.arg(<API key>);
return false;
}
QByteArray data = f.readAll();
return request.parse(data);
}
bool PaymentServer::<API key>(PaymentRequestPlus& request, SendCoinsRecipient& recipient)
{
if (!optionsModel)
return false;
if (request.IsInitialized()) {
const payments::PaymentDetails& details = request.getDetails();
// Payment request network matches client network?
if (details.network() != Params().NetworkIDString())
{
emit message(tr("Payment request rejected"), tr("Payment request network doesn't match client network."),
CClientUIInterface::MSG_ERROR);
return false;
}
// Expired payment request?
if (details.has_expires() && (int64_t)details.expires() < GetTime())
{
emit message(tr("Payment request rejected"), tr("Payment request has expired."),
CClientUIInterface::MSG_ERROR);
return false;
}
}
else {
emit message(tr("Payment request error"), tr("Payment request is not initialized."),
CClientUIInterface::MSG_ERROR);
return false;
}
recipient.paymentRequest = request;
recipient.message = GUIUtil::HtmlEscape(request.getDetails().memo());
request.getMerchant(PaymentServer::certStore, recipient.<API key>);
QList<std::pair<CScript, CAmount> > sendingTos = request.getPayTo();
QStringList addresses;
foreach(const PAIRTYPE(CScript, CAmount)& sendingTo, sendingTos) {
// Extract and check destination addresses
CTxDestination dest;
if (ExtractDestination(sendingTo.first, dest)) {
// Append destination address
addresses.append(QString::fromStdString(CTestcoinAddress(dest).ToString()));
}
else if (!recipient.<API key>.isEmpty()) {
// Insecure payments to custom Testcoin addresses are not supported
// (there is no good way to tell the user where they are paying in a way
// they'd have a chance of understanding).
emit message(tr("Payment request rejected"),
tr("Unverified payment requests to custom payment scripts are unsupported."),
CClientUIInterface::MSG_ERROR);
return false;
}
// Extract and check amounts
CTxOut txOut(sendingTo.second, sendingTo.first);
if (txOut.IsDust(::minRelayTxFee)) {
emit message(tr("Payment request error"), tr("Requested payment amount of %1 is too small (considered dust).")
.arg(TestcoinUnits::formatWithUnit(optionsModel->getDisplayUnit(), sendingTo.second)),
CClientUIInterface::MSG_ERROR);
return false;
}
recipient.amount += sendingTo.second;
}
// Store addresses and format them to fit nicely into the GUI
recipient.address = addresses.join("<br />");
if (!recipient.<API key>.isEmpty()) {
qDebug() << "PaymentServer::<API key> : Secure payment request from " << recipient.<API key>;
}
else {
qDebug() << "PaymentServer::<API key> : Insecure payment request to " << addresses.join(", ");
}
return true;
}
void PaymentServer::fetchRequest(const QUrl& url)
{
QNetworkRequest netRequest;
netRequest.setAttribute(QNetworkRequest::User, <API key>);
netRequest.setUrl(url);
netRequest.setRawHeader("User-Agent", CLIENT_NAME.c_str());
netRequest.setRawHeader("Accept", <API key>);
netManager->get(netRequest);
}
void PaymentServer::fetchPaymentACK(CWallet* wallet, SendCoinsRecipient recipient, QByteArray transaction)
{
const payments::PaymentDetails& details = recipient.paymentRequest.getDetails();
if (!details.has_payment_url())
return;
QNetworkRequest netRequest;
netRequest.setAttribute(QNetworkRequest::User, <API key>);
netRequest.setUrl(QString::fromStdString(details.payment_url()));
netRequest.setHeader(QNetworkRequest::ContentTypeHeader, <API key>);
netRequest.setRawHeader("User-Agent", CLIENT_NAME.c_str());
netRequest.setRawHeader("Accept", <API key>);
payments::Payment payment;
payment.set_merchant_data(details.merchant_data());
payment.add_transactions(transaction.data(), transaction.size());
// Create a new refund address, or re-use:
QString account = tr("Refund from %1").arg(recipient.<API key>);
std::string strAccount = account.toStdString();
set<CTxDestination> refundAddresses = wallet->GetAccountAddresses(strAccount);
if (!refundAddresses.empty()) {
CScript s = <API key>(*refundAddresses.begin());
payments::Output* refund_to = payment.add_refund_to();
refund_to->set_script(&s[0], s.size());
}
else {
CPubKey newKey;
if (wallet->GetKeyFromPool(newKey)) {
CKeyID keyID = newKey.GetID();
wallet->SetAddressBook(keyID, strAccount, "refund");
CScript s = <API key>(keyID);
payments::Output* refund_to = payment.add_refund_to();
refund_to->set_script(&s[0], s.size());
}
else {
// This should never happen, because sending coins should have
// just unlocked the wallet and refilled the keypool.
qWarning() << "PaymentServer::fetchPaymentACK : Error getting refund key, refund_to not set";
}
}
int length = payment.ByteSize();
netRequest.setHeader(QNetworkRequest::ContentLengthHeader, length);
QByteArray serData(length, '\0');
if (payment.SerializeToArray(serData.data(), length)) {
netManager->post(netRequest, serData);
}
else {
// This should never happen, either.
qWarning() << "PaymentServer::fetchPaymentACK : Error serializing payment message";
}
}
void PaymentServer::netRequestFinished(QNetworkReply* reply)
{
reply->deleteLater();
// BIP70 DoS protection
if (reply->size() > <API key>) {
QString msg = tr("Payment request %1 is too large (%2 bytes, allowed %3 bytes).")
.arg(reply->request().url().toString())
.arg(reply->size())
.arg(<API key>);
qWarning() << QString("PaymentServer::%1:").arg(__func__) << msg;
emit message(tr("Payment request DoS protection"), msg, CClientUIInterface::MSG_ERROR);
return;
}
if (reply->error() != QNetworkReply::NoError) {
QString msg = tr("Error communicating with %1: %2")
.arg(reply->request().url().toString())
.arg(reply->errorString());
qWarning() << "PaymentServer::netRequestFinished: " << msg;
emit message(tr("Payment request error"), msg, CClientUIInterface::MSG_ERROR);
return;
}
QByteArray data = reply->readAll();
QString requestType = reply->request().attribute(QNetworkRequest::User).toString();
if (requestType == <API key>)
{
PaymentRequestPlus request;
SendCoinsRecipient recipient;
if (!request.parse(data))
{
qWarning() << "PaymentServer::netRequestFinished : Error parsing payment request";
emit message(tr("Payment request error"),
tr("Payment request cannot be parsed!"),
CClientUIInterface::MSG_ERROR);
}
else if (<API key>(request, recipient))
emit <API key>(recipient);
return;
}
else if (requestType == <API key>)
{
payments::PaymentACK paymentACK;
if (!paymentACK.ParseFromArray(data.data(), data.size()))
{
QString msg = tr("Bad response from server %1")
.arg(reply->request().url().toString());
qWarning() << "PaymentServer::netRequestFinished : " << msg;
emit message(tr("Payment request error"), msg, CClientUIInterface::MSG_ERROR);
}
else
{
emit receivedPaymentACK(GUIUtil::HtmlEscape(paymentACK.memo()));
}
}
}
void PaymentServer::reportSslErrors(QNetworkReply* reply, const QList<QSslError> &errs)
{
Q_UNUSED(reply);
QString errString;
foreach (const QSslError& err, errs) {
qWarning() << "PaymentServer::reportSslErrors : " << err;
errString += err.errorString() + "\n";
}
emit message(tr("Network request error"), errString, CClientUIInterface::MSG_ERROR);
}
void PaymentServer::setOptionsModel(OptionsModel *optionsModel)
{
this->optionsModel = optionsModel;
}
void PaymentServer::handlePaymentACK(const QString& paymentACKMsg)
{
// currently we don't futher process or store the paymentACK message
emit message(tr("Payment acknowledged"), paymentACKMsg, CClientUIInterface::ICON_INFORMATION | CClientUIInterface::MODAL);
}
|
<div class="page-actions">
<!-- AUDIO CONTAINER (conditional) -->
<?php if ($page->episode_file()->isNotEmpty()) { ?>
<div class="audio-holder" itemprop="audio">
<audio preload="none" controls>
<source src="/podcasts/<?php echo $page->episode_file() ?>" type="audio/mpeg" />
</audio>
</div>
<?php } ?>
<!-- DOWNLOAD FILE -->
<?php if ($page->episode_file() != ""): ?>
<a itemprop="audio" class="action download" href="<?= $site->url(); ?>/podcasts/<?php echo $page->episode_file() ?>" download title="Download episode">
<svg viewBox="0 0 100 100">
<path d="M81.2 49.4c0 7.7-6.3 13.9-13.9 13.9h-5.6v-6.1h5.6c4.4 0 7.9-3.6 7.9-7.9 0-5.4-3.6-8.2-7.5-8.2-.2-9-6.1-12.9-11.9-12.9-7.6 0-10.8 5.8-11.5 8-3.1-4.5-11.5-1.1-9.8 4.9-5.3-.9-9.4 3-9.4 8.2 0 4.4 3.6 7.9 8.1 7.9h7.7v6.1h-7.7C25.3 63.3 19 57 19 49.4c0-6.3 4.2-11.7 10-13.4 1.6-5.6 7.5-8.9 13.1-7.4 3.4-4 8.3-6.3 13.6-6.3 8.6 0 16 6.2 17.5 14.5 4.9 2.3 8 7.1 8 12.6zM62.3 68.8h-5.1V57.3H45.1v11.5H40L51.1 80l11.2-11.2z"/>
</svg>
<span class="label go-right">Download this episode</span>
</a>
<?php endif; ?>
<!-- READ DOCUMENT -->
<?php if ($page->document_link() != ""): ?>
<a itemprop="citation" class="action read" href="<?php echo $page->document_link() ?>" title="Read <?php echo $page->provider() ?>'s document" target="_blank">
<svg viewBox="0 0 100 100">
<path d="M65.3 57H44.2v-4.6h21l.1 4.6zm0-10H44.2v-4.6h21l.1 4.6zm0-10H44.2v-4.6h21l.1 4.6zM29.1 75.3V24.4h42.8v33.4c0 9.7-11.9 5.8-11.9 5.8s3.6 11.7-5.4 11.7H29.1zM78 58.4V18.3H23v63.1h31.7c10.4 0 23.3-13.6 23.3-23zM37.8 32c-1.5 0-2.7 1.2-2.7 2.7 0 1.5 1.2 2.7 2.7 2.7s2.7-1.2 2.7-2.7c-.1-1.5-1.3-2.7-2.7-2.7zm0 10.1c-1.5 0-2.7 1.2-2.7 2.7 0 1.5 1.2 2.7 2.7 2.7s2.7-1.2 2.7-2.7c-.1-1.5-1.3-2.7-2.7-2.7zm0 9.9c-1.5 0-2.7 1.2-2.7 2.7 0 1.5 1.2 2.7 2.7 2.7s2.7-1.2 2.7-2.7c-.1-1.5-1.3-2.7-2.7-2.7z"/>
</svg>
<span class="label go-right">Read <?php echo $page->provider() ?>'s document</span>
</a>
<?php endif ?>
<!-- Contribute To The F Plus -->
<a class="social contribute" href="/contribute/" title="Contribute To The Podcast">
<svg viewBox="0 0 100 100">
<path d="M50.6 28.3l10.2-3.6L50 20.9l-10.7 3.7M32 36v-1.2l2.3-.7 9.5-3.4L32.7 27l-11.8 4.1v8.2L32 43.6M67.5 27l-9.7 3.6 8.9 2.9 3 1v7.6l9.4-4.1v-6.9M62.1 36.9L51 33.1l-11.4 4.2v9.2l10.4 4 12.1-5.2"/>
<path d="M60.9 47.4L50 52.2l-9.2-3.6v24.9l9.2 5.6L60.9 72M33.2 45.6l-10.9-4.2v21L33.2 69M68.5 44v23.1l9.2-6V39.9" />
</svg>
<span class="label">Contribute to the Podcast</span>
</a>
<!-- TWEET THIS -->
<a class="social twitter" href="https://twitter.com/intent/tweet?text=<?php echo rawurlencode($page->title()); ?>%0A&url=<?php echo rawurlencode($page->url()); ?>&via=TheFPlus" target="_blank" title="Tweet this">
<svg viewBox="0 0 100 100">
<path d="M80.2 30.5c-2.3 1-4.8 1.8-7.4 2 2.6-1.6 4.7-4.1 5.7-7.1-2.5 1.5-5.2 2.6-8.2 3.2-2.3-2.5-5.7-4.1-9.5-4.1-7.1 0-13 5.8-13 13 0 1 .1 2 .3 2.9-10.8-.6-20.3-5.7-26.7-13.6-1.2 1.9-1.8 4.1-1.8 6.6 0 4.5 2.3 8.5 5.8 10.8-2 0-4.1-.7-5.8-1.6v.1c0 6.3 4.5 11.5 10.4 12.7-1.2.3-2.2.4-3.4.4-.9 0-1.6 0-2.5-.3 1.6 5.1 6.4 8.9 12.1 9-4.5 3.5-10.1 5.5-16 5.5-1 0-2 0-3.1-.1 5.7 3.7 12.6 5.8 20 5.8C61 75.7 74 55.9 74 38.8V37c2.3-1.6 4.5-4 6.2-6.5z"/>
</svg>
<span class="label">Tweet this episode</span>
</a>
<!-- FACEBOOK SHARE -->
<a class="social facebook" href="https:
<svg viewBox="0 0 100 100">
<path d="M76.8 18.3H21.9c-1.9 0-3.4 1.5-3.4 3.4v54.9c0 1.9 1.5 3.4 3.4 3.4h29.5V56.1h-8v-9.3h8V40c0-7.9 4.9-12.3 12-12.3 3.4 0 6.3.3 7.2.4v8.3h-4.9c-3.9 0-4.6 1.8-4.6 4.5v6h9.2L69 56.3h-7.9v23.9h15.7c1.9 0 3.4-1.5 3.4-3.4v-55c0-1.9-1.5-3.5-3.4-3.5z"/>
</svg>
<span class="label">Share on Facebook</span>
</a>
<!-- REDDIT SHARE -->
<a class="social reddit" href="https://reddit.com/submit/?<?php echo rawurlencode ($page->url()); ?>" target="_blank" title="Share on Reddit">
<svg viewBox="0 0 100 100">
<path d="M82.7 47.1c0-4.7-3.8-8.5-8.5-8.5-2.7 0-5.3 1.4-6.9 3.5-4.7-2.9-10.6-4.7-17.2-4.9.2-3.2 1.1-8.7 4.3-10.5 2-1.2 4.9-.7 8.6 1.4.4 4.3 4 7.6 8.4 7.6 4.7 0 8.5-3.8 8.5-8.5s-3.8-8.5-8.5-8.5c-3.9 0-7.2 2.7-8.2 6.3-4.1-2-7.5-2.3-10.2-.7-4.7 2.7-5.5 9.9-5.7 12.9-6.6.2-12.6 2-17.3 4.9-1.6-2.2-4.1-3.5-6.9-3.5-4.7 0-8.5 3.8-8.5 8.5 0 3.7 2.4 6.9 5.8 8.1-.1.6-.1 1.2-.1 1.9C20.3 68.1 33 77 48.7 77S77 68 77 57c0-.6-.1-1.3-.1-1.9 3.4-1.1 5.8-4.3 5.8-8zM21 52.4c-2.2-.8-3.7-2.9-3.7-5.3 0-3.1 2.5-5.7 5.7-5.7 1.8 0 3.5.9 4.5 2.3-3.1 2.4-5.4 5.4-6.5 8.7zm10.6.4c0-3.1 2.5-5.7 5.7-5.7 3.1 0 5.7 2.5 5.7 5.7s-2.5 5.7-5.7 5.7-5.7-2.6-5.7-5.7zm27.8 13.6c-3 1.7-6.8 2.7-10.8 2.7-3.9 0-7.8-1-10.8-2.7-.7-.4-.9-1.3-.5-1.9.4-.7 1.3-.9 1.9-.5 5.2 3 13.5 3 18.7 0 .7-.4 1.5-.2 1.9.5.5.7.2 1.5-.4 1.9zm.6-8c-3.1 0-5.7-2.5-5.7-5.7S56.8 47 60 47c3.1 0 5.7 2.5 5.7 5.7s-2.6 5.7-5.7 5.7zm16.2-6c-1.1-3.3-3.4-6.2-6.5-8.7 1.1-1.4 2.7-2.3 4.5-2.3 3.1 0 5.7 2.5 5.7 5.7 0 2.4-1.6 4.4-3.7 5.3z" />
</svg>
<span class="label">Share on Reddit</span>
</a>
<!-- TUMBLR SHARE -->
<a class="social tumblr" href="http:
<svg viewBox="0 0 100 100">
<path d="M57.3 81.4c6.5 0 13-2.3 15.1-5.1l.4-.6-4-12c0-.1-.1-.2-.3-.2h-9c-.1 0-.2-.1-.3-.2-.1-.4-.2-.9-.2-1.5V47.2c0-.2.1-.3.3-.3H70c.2 0 .3-.1.3-.3v-15c0-.2-.1-.3-.3-.3H59.4c-.2 0-.3-.1-.3-.3V16.5c0-.2-.1-.3-.3-.3H40.2c-1.3 0-2.9 1-3.1 2.8-.9 7.5-4.4 12.1-10.9 14.2l-.7.2c-.1 0-.2.1-.2.3v12.9c0 .2.1.3.3.3H32.3v15.9c0 12.7 8.8 18.6 25 18.6zm12.4-6.1c-2 2-6.2 3.4-10.2 3.5h-.4c-13.2 0-16.7-10.1-16.7-16V44.6c0-.2-.1-.3-.3-.3h-6.4c-.2 0-.3-.1-.3-.3v-8.3c0-.1.1-.2.2-.3 6.8-2.6 10.6-7.9 11.6-16.1.1-.5.4-.5.4-.5h8.5c.2 0 .3.1.3.3v14.6c0 .2.1.3.3.3h10.6c.2 0 .3.1.3.3V44c0 .2-.1.3-.3.3H56.7c-.2 0-.3.1-.3.3v17.3c.1 3.9 2 5.9 5.6 5.9 1.5 0 3.2-.3 4.7-.9.1-.1.3 0 .4.2l2.7 8s0 .1-.1.2z" />
</svg>
<span class="label">Post to Tumblr</span>
</a>
<!-- Save To Pocket -->
<?php if ($page->episode_file()->isEmpty()) { ?>
<a class="social pocket" href="https://getpocket.com/edit?url=<?=rawurlencode ($page->url()); ?>">
<svg xmlns="http:
<path d="M67.1 47.8L53.2 61.2c-.8.8-1.8 1.1-2.8 1.1-1 0-2-.4-2.8-1.1l-14-13.4c-1.6-1.5-1.7-4.1-.1-5.7 1.6-1.6 4.1-1.7 5.7-.1l11.1 10.7L61.4 42c1.6-1.6 4.2-1.5 5.7.1 1.7 1.6 1.7 4.1 0 5.7zm12.5-18.6c-.7-2.1-2.8-3.5-5-3.5H26.1c-2.2 0-4.2 1.4-5 3.5-.2.6-.3 1.3-.3 1.9V49l.2 3.6c.9 8.1 5 15.1 11.5 20.1.1.1.2.2.4.3l.1.1c3.5 2.5 7.4 4.3 11.6 5.1 1.9.4 3.9.6 5.9.6 1.8 0 3.7-.2 5.4-.5.2-.1.4-.1.7-.1.1 0 .1 0 .2-.1 4-.9 7.8-2.6 11.1-5l.1-.1.3-.3c6.5-4.9 10.7-12 11.5-20.1L80 49V31c-.1-.6-.2-1.2-.4-1.8z" />
</svg>
<span class="label">Save to Pocket</span>
</a>
<?php } ?>
<!-- GitHub Repo -->
<?php if ($page->github_repo()->isNotEmpty()) { ?>
<a class="social github" href="<?= $page->github_repo(); ?>" title="Fork on GitHub">
<svg xmlns="http:
<path d="M50 15.3c-19 0-34.3 15.4-34.3 34.3 0 15.2 9.8 28 23.5 32.6 1.7.3 2.3-.7 2.3-1.7v-5.8c-9.5 2.1-11.6-4.6-11.6-4.6-1.6-4-3.8-5-3.8-5-3.1-2.1.2-2.1.2-2.1 3.4.2 5.3 3.5 5.3 3.5 3.1 5.2 8 3.7 10 2.9.3-2.2 1.2-3.7 2.2-4.6-7.6-.9-15.6-3.8-15.6-17 0-3.7 1.3-6.8 3.5-9.2-.4-.9-1.5-4.4.3-9.1 0 0 2.9-.9 9.4 3.5 2.7-.8 5.7-1.1 8.6-1.2 2.9 0 5.9.4 8.6 1.2 6.6-4.4 9.4-3.5 9.4-3.5 1.9 4.7.7 8.2.3 9.1 2.2 2.4 3.5 5.5 3.5 9.2 0 13.2-8 16.1-15.7 16.9 1.2 1.1 2.3 3.2 2.3 6.4v9.4c0 .9.6 2 2.4 1.7 13.6-4.5 23.5-17.4 23.5-32.6C84.3 30.7 69 15.3 50 15.3z"/>
</svg>
<span class="label">Fork on GitHub</span>
</a>
<?php } ?>
</div>
|
When /(.*) should receive: (.*) email/ do |email, preference_list|
u = User.find_by(email:email)
print(u)
preference_list.split(",").each do |p|
if p[1,p.length-2] == "internal"
expect(u.internal).to be(false)
end
end
end
When /I should see correct flash message "([^"]*)"$/ do |message|
expect(page).to have_css('flashNotice',text: message)
end
#New tests for iter 2-1
Then /I should receive an email/ do
pending
end
Then /I should see title "([^"]*)"$/ do |title|
pending
end
Then /I should see content "([^"]*)"$/ do |content|
pending
end
Then /the database should( not)? have email with title "([^"]*)" and content "([^"]*)"$/ do |title, content|
pending
end
#New Tests for iter 2-2
Then /I should see a MailRecord object with attribute "([^"]*)" and description "([^"]*)"$/ do |attr, desc|
MailRecord.where.not(attr, nil).find_by(description: desc)
end
|
#!/usr/bin/env python3
# Test addressindex generation and fetching
import binascii
from test_framework.messages import COIN, COutPoint, CTransaction, CTxIn, CTxOut
from test_framework.test_framework import <API key>
from test_framework.test_node import ErrorMatch
from test_framework.script import CScript, OP_CHECKSIG, OP_DUP, OP_EQUAL, OP_EQUALVERIFY, OP_HASH160
from test_framework.util import assert_equal, connect_nodes
class AddressIndexTest(<API key>):
def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 4
def <API key>(self):
self.skip_if_no_wallet()
def setup_network(self):
self.add_nodes(self.num_nodes)
# Nodes 0/1 are "wallet" nodes
self.start_node(0, [])
self.start_node(1, ["-addressindex"])
# Nodes 2/3 are used for testing
self.start_node(2, ["-addressindex"])
self.start_node(3, ["-addressindex"])
connect_nodes(self.nodes[0], 1)
connect_nodes(self.nodes[0], 2)
connect_nodes(self.nodes[0], 3)
self.sync_all()
def run_test(self):
self.log.info("Test that settings can't be changed without -reindex...")
self.stop_node(1)
self.nodes[1].<API key>(["-addressindex=0"], "You need to rebuild the database using -reindex to change -addressindex", match=ErrorMatch.PARTIAL_REGEX)
self.start_node(1, ["-addressindex=0", "-reindex"])
connect_nodes(self.nodes[0], 1)
self.sync_all()
self.stop_node(1)
self.nodes[1].<API key>(["-addressindex"], "You need to rebuild the database using -reindex to change -addressindex", match=ErrorMatch.PARTIAL_REGEX)
self.start_node(1, ["-addressindex", "-reindex"])
connect_nodes(self.nodes[0], 1)
self.sync_all()
self.log.info("Mining blocks...")
mining_address = self.nodes[0].getnewaddress()
self.nodes[0].generatetoaddress(105, mining_address)
self.sync_all()
chain_height = self.nodes[1].getblockcount()
assert_equal(chain_height, 105)
assert_equal(self.nodes[1].getbalance(), 0)
assert_equal(self.nodes[2].getbalance(), 0)
# Check that balances are correct
balance0 = self.nodes[1].getaddressbalance("<API key>")
balance_mining = self.nodes[1].getaddressbalance(mining_address)
assert_equal(balance0["balance"], 0)
assert_equal(balance_mining["balance"], 105 * 500 * COIN)
assert_equal(balance_mining["balance_immature"], 100 * 500 * COIN)
assert_equal(balance_mining["balance_spendable"], 5 * 500 * COIN)
# Check p2pkh and p2sh address indexes
self.log.info("Testing p2pkh and p2sh address index...")
txid0 = self.nodes[0].sendtoaddress("<API key>", 10)
self.nodes[0].generate(1)
txidb0 = self.nodes[0].sendtoaddress("<API key>", 10)
self.nodes[0].generate(1)
txid1 = self.nodes[0].sendtoaddress("<API key>", 15)
self.nodes[0].generate(1)
txidb1 = self.nodes[0].sendtoaddress("<API key>", 15)
self.nodes[0].generate(1)
txid2 = self.nodes[0].sendtoaddress("<API key>", 20)
self.nodes[0].generate(1)
txidb2 = self.nodes[0].sendtoaddress("<API key>", 20)
self.nodes[0].generate(1)
self.sync_all()
txids = self.nodes[1].getaddresstxids("<API key>")
assert_equal(len(txids), 3)
assert_equal(txids[0], txid0)
assert_equal(txids[1], txid1)
assert_equal(txids[2], txid2)
txidsb = self.nodes[1].getaddresstxids("<API key>")
assert_equal(len(txidsb), 3)
assert_equal(txidsb[0], txidb0)
assert_equal(txidsb[1], txidb1)
assert_equal(txidsb[2], txidb2)
# Check that limiting by height works
self.log.info("Testing querying txids by range of block heights..")
height_txids = self.nodes[1].getaddresstxids({
"addresses": ["<API key>"],
"start": 105,
"end": 110
})
assert_equal(len(height_txids), 2)
assert_equal(height_txids[0], txidb0)
assert_equal(height_txids[1], txidb1)
# Check that multiple addresses works
multitxids = self.nodes[1].getaddresstxids({"addresses": ["<API key>", "<API key>"]})
assert_equal(len(multitxids), 6)
assert_equal(multitxids[0], txid0)
assert_equal(multitxids[1], txidb0)
assert_equal(multitxids[2], txid1)
assert_equal(multitxids[3], txidb1)
assert_equal(multitxids[4], txid2)
assert_equal(multitxids[5], txidb2)
# Check that balances are correct
balance0 = self.nodes[1].getaddressbalance("<API key>")
assert_equal(balance0["balance"], 45 * 100000000)
# Check that outputs with the same address will only return one txid
self.log.info("Testing for txid uniqueness...")
addressHash = binascii.unhexlify("<API key>")
scriptPubKey = CScript([OP_HASH160, addressHash, OP_EQUAL])
unspent = self.nodes[0].listunspent()
tx = CTransaction()
tx.vin = [CTxIn(COutPoint(int(unspent[0]["txid"], 16), unspent[0]["vout"]))]
tx.vout = [CTxOut(10 * COIN, scriptPubKey), CTxOut(11 * COIN, scriptPubKey)]
tx.rehash()
signed_tx = self.nodes[0].<API key>(tx.serialize().hex())
sent_txid = self.nodes[0].sendrawtransaction(signed_tx["hex"], 0)
self.nodes[0].generate(1)
self.sync_all()
txidsmany = self.nodes[1].getaddresstxids("<API key>")
assert_equal(len(txidsmany), 4)
assert_equal(txidsmany[3], sent_txid)
# Check that balances are correct
self.log.info("Testing balances...")
balance0 = self.nodes[1].getaddressbalance("<API key>")
assert_equal(balance0["balance"], (45 + 21) * 100000000)
# Check that balances are correct after spending
self.log.info("Testing balances after spending...")
privkey2 = "<API key>"
address2 = "<API key>"
addressHash2 = binascii.unhexlify("<API key>")
scriptPubKey2 = CScript([OP_DUP, OP_HASH160, addressHash2, OP_EQUALVERIFY, OP_CHECKSIG])
self.nodes[0].importprivkey(privkey2)
unspent = self.nodes[0].listunspent()
tx = CTransaction()
tx_fee_sat = 1000
tx.vin = [CTxIn(COutPoint(int(unspent[0]["txid"], 16), unspent[0]["vout"]))]
amount = int(unspent[0]["amount"] * 100000000) - tx_fee_sat
tx.vout = [CTxOut(amount, scriptPubKey2)]
tx.rehash()
signed_tx = self.nodes[0].<API key>(tx.serialize().hex())
spending_txid = self.nodes[0].sendrawtransaction(signed_tx["hex"], 0)
self.nodes[0].generate(1)
self.sync_all()
balance1 = self.nodes[1].getaddressbalance(address2)
assert_equal(balance1["balance"], amount)
tx = CTransaction()
tx.vin = [CTxIn(COutPoint(int(spending_txid, 16), 0))]
send_amount = 1 * 100000000 + 12840
change_amount = amount - send_amount - 10000
tx.vout = [CTxOut(change_amount, scriptPubKey2), CTxOut(send_amount, scriptPubKey)]
tx.rehash()
signed_tx = self.nodes[0].<API key>(tx.serialize().hex())
sent_txid = self.nodes[0].sendrawtransaction(signed_tx["hex"], 0)
self.nodes[0].generate(1)
self.sync_all()
balance2 = self.nodes[1].getaddressbalance(address2)
assert_equal(balance2["balance"], change_amount)
# Check that deltas are returned correctly
deltas = self.nodes[1].getaddressdeltas({"addresses": [address2], "start": 0, "end": 200})
balance3 = 0
for delta in deltas:
balance3 += delta["satoshis"]
assert_equal(balance3, change_amount)
assert_equal(deltas[0]["address"], address2)
assert_equal(deltas[0]["blockindex"], 1)
# Check that entire range will be queried
deltasAll = self.nodes[1].getaddressdeltas({"addresses": [address2]})
assert_equal(len(deltasAll), len(deltas))
# Check that deltas can be returned from range of block heights
deltas = self.nodes[1].getaddressdeltas({"addresses": [address2], "start": 113, "end": 113})
assert_equal(len(deltas), 1)
# Check that unspent outputs can be queried
self.log.info("Testing utxos...")
utxos = self.nodes[1].getaddressutxos({"addresses": [address2]})
assert_equal(len(utxos), 1)
assert_equal(utxos[0]["satoshis"], change_amount)
# Check that indexes will be updated with a reorg
self.log.info("Testing reorg...")
best_hash = self.nodes[0].getbestblockhash()
self.nodes[0].invalidateblock(best_hash)
self.nodes[1].invalidateblock(best_hash)
self.nodes[2].invalidateblock(best_hash)
self.nodes[3].invalidateblock(best_hash)
# Allow some time for the reorg to start
self.bump_mocktime(2)
self.sync_all()
balance4 = self.nodes[1].getaddressbalance(address2)
assert_equal(balance4, balance1)
utxos2 = self.nodes[1].getaddressutxos({"addresses": [address2]})
assert_equal(len(utxos2), 1)
assert_equal(utxos2[0]["satoshis"], amount)
# Check sorting of utxos
self.nodes[2].generate(150)
self.nodes[2].sendtoaddress(address2, 50)
self.nodes[2].generate(1)
self.nodes[2].sendtoaddress(address2, 50)
self.nodes[2].generate(1)
self.sync_all()
utxos3 = self.nodes[1].getaddressutxos({"addresses": [address2]})
assert_equal(len(utxos3), 3)
assert_equal(utxos3[0]["height"], 114)
assert_equal(utxos3[1]["height"], 264)
assert_equal(utxos3[2]["height"], 265)
# Check mempool indexing
self.log.info("Testing mempool indexing...")
privKey3 = "<API key>"
address3 = "<API key>"
addressHash3 = binascii.unhexlify("<API key>")
scriptPubKey3 = CScript([OP_DUP, OP_HASH160, addressHash3, OP_EQUALVERIFY, OP_CHECKSIG])
# address4 = "<API key>"
scriptPubKey4 = CScript([OP_HASH160, addressHash3, OP_EQUAL])
unspent = self.nodes[2].listunspent()
tx = CTransaction()
tx.vin = [CTxIn(COutPoint(int(unspent[0]["txid"], 16), unspent[0]["vout"]))]
amount = int(unspent[0]["amount"] * 100000000) - tx_fee_sat
tx.vout = [CTxOut(amount, scriptPubKey3)]
tx.rehash()
signed_tx = self.nodes[2].<API key>(tx.serialize().hex())
memtxid1 = self.nodes[2].sendrawtransaction(signed_tx["hex"], 0)
self.bump_mocktime(2)
tx2 = CTransaction()
tx2.vin = [CTxIn(COutPoint(int(unspent[1]["txid"], 16), unspent[1]["vout"]))]
amount = int(unspent[1]["amount"] * 100000000) - tx_fee_sat
tx2.vout = [
CTxOut(int(amount / 4), scriptPubKey3),
CTxOut(int(amount / 4), scriptPubKey3),
CTxOut(int(amount / 4), scriptPubKey4),
CTxOut(int(amount / 4), scriptPubKey4)
]
tx2.rehash()
signed_tx2 = self.nodes[2].<API key>(tx2.serialize().hex())
memtxid2 = self.nodes[2].sendrawtransaction(signed_tx2["hex"], 0)
self.bump_mocktime(2)
mempool = self.nodes[2].getaddressmempool({"addresses": [address3]})
assert_equal(len(mempool), 3)
assert_equal(mempool[0]["txid"], memtxid1)
assert_equal(mempool[0]["address"], address3)
assert_equal(mempool[0]["index"], 0)
assert_equal(mempool[1]["txid"], memtxid2)
assert_equal(mempool[1]["index"], 0)
assert_equal(mempool[2]["txid"], memtxid2)
assert_equal(mempool[2]["index"], 1)
self.nodes[2].generate(1)
self.sync_all()
mempool2 = self.nodes[2].getaddressmempool({"addresses": [address3]})
assert_equal(len(mempool2), 0)
tx = CTransaction()
tx.vin = [
CTxIn(COutPoint(int(memtxid2, 16), 0)),
CTxIn(COutPoint(int(memtxid2, 16), 1))
]
tx.vout = [CTxOut(int(amount / 2 - 10000), scriptPubKey2)]
tx.rehash()
self.nodes[2].importprivkey(privKey3)
signed_tx3 = self.nodes[2].<API key>(tx.serialize().hex())
self.nodes[2].sendrawtransaction(signed_tx3["hex"], 0)
self.bump_mocktime(2)
mempool3 = self.nodes[2].getaddressmempool({"addresses": [address3]})
assert_equal(len(mempool3), 2)
assert_equal(mempool3[0]["prevtxid"], memtxid2)
assert_equal(mempool3[0]["prevout"], 0)
assert_equal(mempool3[1]["prevtxid"], memtxid2)
assert_equal(mempool3[1]["prevout"], 1)
# sending and receiving to the same address
privkey1 = "<API key>"
address1 = "<API key>"
address1hash = binascii.unhexlify("<API key>")
address1script = CScript([OP_DUP, OP_HASH160, address1hash, OP_EQUALVERIFY, OP_CHECKSIG])
self.nodes[0].sendtoaddress(address1, 10)
self.nodes[0].generate(1)
self.sync_all()
utxos = self.nodes[1].getaddressutxos({"addresses": [address1]})
assert_equal(len(utxos), 1)
tx = CTransaction()
tx.vin = [
CTxIn(COutPoint(int(utxos[0]["txid"], 16), utxos[0]["outputIndex"]))
]
amount = int(utxos[0]["satoshis"] - 10000)
tx.vout = [CTxOut(amount, address1script)]
tx.rehash()
self.nodes[0].importprivkey(privkey1)
signed_tx = self.nodes[0].<API key>(tx.serialize().hex())
self.nodes[0].sendrawtransaction(signed_tx["hex"], 0)
self.sync_all()
mempool_deltas = self.nodes[2].getaddressmempool({"addresses": [address1]})
assert_equal(len(mempool_deltas), 2)
self.log.info("Passed")
if __name__ == '__main__':
AddressIndexTest().main()
|
import xml.etree.ElementTree as ET
import numpy as np
import openmc
import pytest
from tests.unit_tests import assert_unbounded
def test_basic():
c1 = openmc.Cell()
c2 = openmc.Cell()
c3 = openmc.Cell()
u = openmc.Universe(name='cool', cells=(c1, c2, c3))
assert u.name == 'cool'
cells = set(u.cells.values())
assert not (cells ^ {c1, c2, c3})
# Test __repr__
repr(u)
with pytest.raises(TypeError):
u.add_cell(openmc.Material())
with pytest.raises(TypeError):
u.add_cells(c1)
u.remove_cell(c3)
cells = set(u.cells.values())
assert not (cells ^ {c1, c2})
u.clear_cells()
assert not set(u.cells)
def test_bounding_box():
cyl1 = openmc.ZCylinder(r=1.0)
cyl2 = openmc.ZCylinder(r=2.0)
c1 = openmc.Cell(region=-cyl1)
c2 = openmc.Cell(region=+cyl1 & -cyl2)
u = openmc.Universe(cells=[c1, c2])
ll, ur = u.bounding_box
assert ll == pytest.approx((-2., -2., -np.inf))
assert ur == pytest.approx((2., 2., np.inf))
u = openmc.Universe()
assert_unbounded(u)
def test_plot(run_in_tmpdir, sphere_model):
m = sphere_model.materials[0]
univ = sphere_model.geometry.root_universe
colors = {m: 'limegreen'}
for basis in ('xy', 'yz', 'xz'):
univ.plot(
basis=basis,
pixels=(10, 10),
color_by='material',
colors=colors,
)
def test_get_nuclides(uo2):
c = openmc.Cell(fill=uo2)
univ = openmc.Universe(cells=[c])
nucs = univ.get_nuclides()
assert nucs == ['U235', 'O16']
def test_cells():
cells = [openmc.Cell() for i in range(5)]
cells2 = [openmc.Cell() for i in range(3)]
cells[0].fill = openmc.Universe(cells=cells2)
u = openmc.Universe(cells=cells)
assert not (set(u.cells.values()) ^ set(cells))
all_cells = set(u.get_all_cells().values())
assert not (all_cells ^ set(cells + cells2))
def <API key>(cell_with_lattice):
cells, mats, univ, lattice = cell_with_lattice
test_mats = set(univ.get_all_materials().values())
assert not (test_mats ^ set(mats))
def <API key>():
c1 = openmc.Cell()
u1 = openmc.Universe(cells=[c1])
c2 = openmc.Cell()
u2 = openmc.Universe(cells=[c2])
c3 = openmc.Cell(fill=u1)
c4 = openmc.Cell(fill=u2)
u3 = openmc.Universe(cells=[c3, c4])
univs = set(u3.get_all_universes().values())
assert not (univs ^ {u1, u2})
def test_create_xml(cell_with_lattice):
cells = [openmc.Cell() for i in range(5)]
u = openmc.Universe(cells=cells)
geom = ET.Element('geom')
u.<API key>(geom)
cell_elems = geom.findall('cell')
assert len(cell_elems) == len(cells)
assert all(c.get('universe') == str(u.id) for c in cell_elems)
assert not (set(c.get('id') for c in cell_elems) ^
set(str(c.id) for c in cells))
|
// Name: wx/gtk/slider.h
// Purpose:
// Id: $Id: slider.h,v 1.20 2005/08/02 22:57:57 MW Exp $
// Licence: wxWindows licence
#ifndef __GTKSLIDERH__
#define __GTKSLIDERH__
#if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
#pragma interface
#endif
// wxSlider
class WXDLLIMPEXP_CORE wxSlider : public wxSliderBase
{
public:
wxSlider() { }
wxSlider(wxWindow *parent,
wxWindowID id,
int value, int minValue, int maxValue,
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxDefaultSize,
long style = wxSL_HORIZONTAL,
const wxValidator& validator = wxDefaultValidator,
const wxString& name = wxSliderNameStr)
{
Create( parent, id, value, minValue, maxValue,
pos, size, style, validator, name );
}
bool Create(wxWindow *parent,
wxWindowID id,
int value, int minValue, int maxValue,
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxDefaultSize,
long style = wxSL_HORIZONTAL,
const wxValidator& validator = wxDefaultValidator,
const wxString& name = wxSliderNameStr);
// implement the base class pure virtuals
virtual int GetValue() const;
virtual void SetValue(int value);
virtual void SetRange(int minValue, int maxValue);
virtual int GetMin() const;
virtual int GetMax() const;
virtual void SetLineSize(int lineSize);
virtual void SetPageSize(int pageSize);
virtual int GetLineSize() const;
virtual int GetPageSize() const;
virtual void SetThumbLength(int lenPixels);
virtual int GetThumbLength() const;
static wxVisualAttributes
<API key>(wxWindowVariant variant = <API key>);
// implementation
bool IsOwnGtkWindow( GdkWindow *window );
void GtkDisableEvents();
void GtkEnableEvents();
GtkAdjustment *m_adjust;
float m_oldPos;
private:
<API key>(wxSlider)
};
#endif // __GTKSLIDERH__
|
<?php
namespace Braintree\Error;
/**
*
* Validation Error codes and messages
*
* ErrorCodes class provides constants for validation errors.
* The constants should be used to check for a specific validation
* error in a <API key>.
* The error messages returned from the server may change;
* but the codes will remain the same.
*
* @package Braintree
* @subpackage Errors
* @category Validation
*/
class Codes
{
const <API key> = '81801';
const <API key> = '91821';
const <API key> = '81802';
const <API key> = '91814';
const <API key> = '91816';
const <API key> = '91817';
const <API key> = '91803';
const <API key> = '91823';
const <API key> = '81804';
const <API key> = '91819';
const <API key> = '81805';
const <API key> = '91815';
const <API key> = '91820';
const <API key> = '81806';
const <API key> = '91824';
const <API key> = '81807';
const <API key> = '81813';
const <API key> = '91826';
const <API key> = '81808';
const <API key> = '81809';
const <API key> = '91825';
const <API key> = '81810';
const <API key> = '81827';
const <API key> = '91822';
const <API key> = '81811';
const <API key> = '81812';
const <API key> = '91818';
const <API key> = '83501';
const <API key> = '83502';
const <API key> = '93503';
const <API key> = '93504';
const <API key> = '93505';
const <API key> = '93506';
const <API key> = '83518';
const <API key> = '93507';
const <API key> = '93508';
const <API key> = '93509';
const <API key> = '93510';
const <API key> = '93511';
const <API key> = '83512';
const APPLE_PAY_DISABLED = '93513';
const <API key> = '93514';
const <API key> = '93515';
const <API key> = '93516';
const <API key> = '93517';
const <API key> = '93519';
const <API key> = '83520';
const <API key> = '93521';
const <API key> = '93522';
const <API key> = '93204';
const <API key> = '93202';
const <API key> = '93205';
const <API key> = '93206';
const <API key> = '93201';
const <API key> = '93207';
const <API key> = '93203';
const CLIENT_<API key> = '92804';
const CLIENT_<API key> = '92803';
const CLIENT_<API key> = '92801';
const CLIENT_<API key> = '92805';
const CLIENT_<API key> = '92806';
const CLIENT_<API key> = '92802';
const CLIENT_<API key> = '92807';
const <API key> = '91701';
const <API key> = '91744';
const <API key> = '91702';
const <API key> = '91735';
const <API key> = '81723';
const <API key> = '81703';
const <API key> = '81718';
const <API key> = '91705';
const <API key> = '91704';
const <API key> = '81707';
const <API key> = '81706';
const <API key> = '81736';
const <API key> = '81724';
const <API key> = '91708';
const <API key> = '81710';
const <API key> = '81709';
const <API key> = '81711';
const <API key> = '81712';
const <API key> = '81713';
const <API key> = '91745';
const <API key> = '91727';
const <API key> = '81716';
const <API key> = '81715';
const <API key> = '81750';
const <API key> = '81714';
const <API key> = '81716';
const <API key> = '81717';
const <API key> = '91723';
const <API key> = '91729';
const <API key> = '91739';
const <API key> = '91740';
const <API key> = '91752';
const <API key> = '91741';
const <API key> = '91728';
const <API key> = '91743';
const <API key> = '91742';
const <API key> = '91755';
const <API key> = '81725';
const <API key> = '91738';
const <API key> = '91734';
const <API key> = '91731';
const <API key> = '91733';
const <API key> = '91732';
const <API key> = '81737';
const CREDIT_CARD_<API key> = '91718';
const <API key> = '91718';
const <API key> = '91719';
const <API key> = '91721';
const <API key> = '91722';
const <API key> = '91720';
const <API key> = '91726';
const <API key> = '91730';
const <API key> = '81601';
const <API key> = '91602';
const <API key> = '81603';
const <API key> = '81604';
const <API key> = '81604';
const <API key> = '81606';
const <API key> = '81605';
const <API key> = '81607';
const <API key> = '81608';
const <API key> = '91610'; //Deprecated
const <API key> = '91610';
const <API key> = '91609';
const <API key> = '91611';
const <API key> = '91613';
const <API key> = '91612';
const <API key> = '81613';
const <API key> = '81614';
const <API key> = '91617';
const <API key> = '81616';
const <API key> = '81616';
const <API key> = '81615';
const <API key> = '92201';
const <API key> = '92202';
const <API key> = '92204';
const <API key> = '92203';
const <API key> = '92205';
const <API key> = '92206';
const <API key> = '95701';
const <API key> = '95702';
const <API key> = '95703';
const <API key> = '95704';
const <API key> = '95705';
const <API key> = '95706';
const <API key> = '95707';
const <API key> = '95708';
const <API key> = '95709';
const <API key> = '95710';
const <API key> = '95711';
const <API key> = '95712';
const <API key> = '95713';
const <API key> = '95713';
const <API key> = '95713';
const <API key> = '95720';
const <API key> = '95721';
const <API key> = '95722';
const <API key> = '95723';
const <API key> = '95724';
const <API key> = '95725';
const <API key> = '95726';
const <API key> = '84901';
const <API key> = '84902';
const <API key> = '84903';
const <API key> = '84904';
const FAILED_<API key> = '95603';
const FAILED_<API key> = '95602';
const FINAL_<API key> = '95601';
const <API key> = '93401';
const <API key> = '93402';
const <API key> = '93403';
const <API key> = '93404';
const <API key> = '93405';
const <API key> = '93406';
const <API key> = '93407';
const <API key> = '93408';
const <API key> = '93409';
const <API key> = '93410';
const <API key> = '93411';
const <API key> = '93412';
const <API key> = '93413';
const <API key> = '95801';
const <API key> = '95803';
const <API key> = '95804';
const <API key> = '95805';
const <API key> = '95806'; // Deprecated as the amount may be zero. Use <API key>.
const <API key> = '95806';
const <API key> = '95807';
const <API key> = '95808';
const <API key> = '95822';
const <API key> = '95823';
const <API key> = '95809';
const <API key> = '95810';
const <API key> = '95811';
const <API key> = '95812';
const <API key> = '95813';
const <API key> = '95814';
const <API key> = '95815';
const <API key> = '95816';
const <API key> = '95817';
const <API key> = '95818';
const <API key> = '95819';
const <API key> = '95820';
const <API key> = '95821';
const <API key> = '95824';
const <API key> = '95825';
const <API key> = '95826'; // Deprecated as the amount may be zero. Use <API key>.
const <API key> = '95826';
const <API key> = '95827';
const <API key> = '95828';
const <API key> = '95829';
const <API key> = '83603';
const <API key> = '93607';
const <API key> = '93606';
const <API key> = '93605';
const <API key> = '93604';
const <API key> = '93609';
const <API key> = '93608';
const <API key> = '93611';
const <API key> = '93610';
const <API key> = '93614';
const <API key> = '93602';
const <API key> = '83601';
const <API key> = '93612';
const <API key> = '93613';
const <API key> = '93615';
const <API key> = '93616';
const <API key> = '93617';
const <API key> = '93618';
const <API key> = '93619';
const <API key> = '93620';
const <API key> = '93621';
const <API key> = '82603';
const <API key> = '82604';
const <API key> = '82605';
const <API key> = '82602';
const <API key> = '82607';
const <API key> = '82606';
const <API key> = '82608';
const <API key> = '82610';
const <API key> = '82674';
const <API key> = '82626';
const <API key> = '82622';
const <API key> = '82621';
const <API key> = '82623';
const <API key> = '82624';
const <API key> = '82625';
const <API key> = '82675';
const <API key> = '82676';
const <API key> = '82614';
const <API key> = '82631';
const <API key> = '82633';
const <API key> = '82612';
const <API key> = '82626'; // Keep for backwards compatibility
const <API key> = '82622'; // Keep for backwards compatibility
const <API key> = '82621'; // Keep for backwards compatibility
const <API key> = '82623'; // Keep for backwards compatibility
const <API key> = '82624'; // Keep for backwards compatibility
const <API key> = '82625'; // Keep for backwards compatibility
const <API key> = '82616';
const <API key> = '82627';
const <API key> = '82609';
const <API key> = '82628';
const <API key> = '82611';
const <API key> = '82636';
const <API key> = '82635';
const <API key> = '82613';
const <API key> = '82615';
const <API key> = '82632';
const <API key> = '82634';
const <API key> = '82663';
const <API key> = '82664';
const <API key> = '82665';
const <API key> = '82670';
const <API key> = '82673';
const <API key> = '82618';
const <API key> = '82630';
const <API key> = '82619';
const <API key> = '82620';
const <API key> = '82629';
const <API key> = '82617';
const <API key> = '82646';
const <API key> = '82647';
const <API key> = '82648';
const <API key> = '82669';
const <API key> = '82672';
const <API key> = '82677';
const <API key> = '82684';
const <API key> = '82685';
const <API key> = '82686';
const <API key> = '82637';
const <API key> = '82638';
const <API key> = '82639';
const <API key> = '82642';
const <API key> = '82643';
const <API key> = '82644';
const <API key> = '82645';
const <API key> = '82656';
const <API key> = '82666';
const <API key> = '82667';
const <API key> = '82657';
const <API key> = '82658';
const <API key> = '82659';
const <API key> = '82660';
const <API key> = '82661';
const <API key> = '82662';
const <API key> = '82668';
const <API key> = '82640';
const <API key> = '82641';
const <API key> = '82649';
const <API key> = '82671';
const <API key> = '82678';
const <API key> = '82679';
const <API key> = '82680';
const <API key> = '82681';
const <API key> = '82682';
const <API key> = '82683';
const OAUTH_INVALID_GRANT = '93801';
const O<API key> = '93802';
const OAUTH_INVALID_SCOPE = '93803';
const O<API key> = '93804';
const O<API key> = '93805';
const <API key> = '93106';
const <API key> = '93105';
const <API key> = '93104';
const <API key> = '93102';
const <API key> = '93103';
const <API key> = '93107';
const <API key> = '93108';
const <API key> = '93109';
const <API key> = '93101';
const <API key> = '93117';
const <API key> = '93121';
const <API key> = '92911';
const <API key><API key> = '82903';
const <API key> = '92912';
const <API key> = '92914';
const <API key> = '82902';
const <API key> = '82901';
const <API key> = '82905';
const <API key> = '92913';
const <API key> = '92915';
const <API key> = '92907';
const <API key> = '92909';
const <API key> = '92908';
const <API key> = '82904';
const <API key> = '92910';
const <API key> = '92906';
const <API key> = '93003';
const <API key> = '93002';
const <API key> = '93001';
const <API key> = '83301';
const <API key> = '83306';
const <API key> = '83302';
const <API key> = '83307';
const <API key> = '83308';
const <API key> = '93311';
const <API key> = '93312';
const <API key> = '83305';
const <API key> = '83310';
const <API key> = '83303';
const <API key> = '83309';
const <API key> = '93304';
const <API key> = '93313';
const <API key> = '82302';
const <API key> = '82301';
const <API key> = '82303';
const <API key> = '91918';
const <API key> = '91914';
const <API key> = '91913';
const <API key> = '91911';
const <API key> = '81901';
const <API key> = '81910';
const <API key> = '91920';
const <API key> = '91916';
const <API key> = '91919';
const <API key> = '91915';
const <API key> = '81902';
const <API key> = '91908';
const <API key> = '91917';
const <API key> = '91921';
const <API key> = '91901';
const <API key> = '91923';
const <API key> = '91912';
const <API key> = '91909';
const <API key> = '91907';
const <API key> = '91906';
const <API key> = '91924';
const <API key> = '91925';
const <API key> = '91926';
const <API key> = '91927';
const <API key><API key> = '91902';
const <API key> = '91903';
const <API key><API key> = '91905';
const <API key> = '91922';
const <API key> = '91904';
const <API key> = '81903';
const <API key> = '81904';
const <API key> = '81923';
const <API key> = '81905';
const SUBSCRIPTION_<API key> = '81906';
const <API key> = '81907';
const <API key> = '81908';
const <API key> = '81909';
const <API key> = '91930';
const <API key> = '91929';
const <API key><API key> = '91928';
const <API key> = '92003';
const <API key> = '92002';
const <API key> = '92023';
const <API key> = '92022';
const <API key> = '92015';
const <API key> = '92020';
const <API key> = '92011';
const <API key> = '92012';
const <API key> = '92021';
const <API key> = '92025';
const <API key> = '92016';
const <API key> = '92018';
const <API key> = '92013';
const <API key> = '92014';
const <API key> = '92024';
const <API key> = '92017';
const <API key> = '92005';
const <API key> = '92019';
const <API key> = '92004';
const <API key> = '92001';
const <API key> = '92010';
const <API key> = '81501';
const <API key> = '91585';
const <API key> = '915144';
const <API key> = '81503';
const <API key> = '81503';
const <API key> = '81502';
const <API key> = '81528';
const <API key> = '81531';
const <API key> = '91530';
const <API key> = '91504';
const <API key> = '91562';
const <API key> = '91543';
const <API key> = '915137';
const <API key> = '91573';
const <API key> = '91540';
const <API key> = '91542';
const <API key> = '91541';
const <API key> = '91560';
const <API key> = '91563';
const <API key> = '91505';
const <API key> = '91574';
const <API key> = '91506';
const <API key> = '91559';
const <API key> = '91538';
const <API key> = '91561';
const <API key> = '91575';
const <API key> = '915103';
const <API key> = '91507';
const <API key> = '915129';
const <API key> = '91550';
const <API key> = '91508';
const <API key> = '81509';
const <API key> = '91511';
const <API key> = '91510';
const <API key> = '91526';
const <API key> = '81527';
const <API key> = '91512';
const <API key> = '815141';
const <API key> = '915150';
const <API key> = '915158';
const <API key> = '915157';
const <API key> = '915159';
const <API key> = '915160';
const <API key> = '915161';
const <API key> = '915162';
const <API key> = '915163';
const <API key> = '915164';
const <API key> = '915165';
const <API key> = '915166';
const <API key> = '915167';
const <API key> = '91584';
const <API key> = '915143';
const <API key> = '91558';
const <API key> = '91547';
const <API key> = '91513';
const <API key> = '91514';
const <API key> = '91513'; //Deprecated
const <API key> = '91580';
const <API key> = '91544';
const <API key> = '91582';
const <API key> = '91572';
const <API key> = '91525';
const <API key> = '91503';
const <API key> = '91502';
const <API key> = '91501';
const <API key> = '91577';
const <API key> = '915101';
const <API key> = '91515';
const <API key> = '91549';
const <API key> = '91516';
const <API key> = '91527';
const <API key> = '91567';
const <API key> = '91564';
const <API key> = '91569';
const <API key> = '91566';
const <API key> = '91565';
const <API key><API key> = '91517';
const <API key> = '91518';
const <API key> = '91576';
const <API key> = '91579';
const <API key> = '91583';
const <API key><API key> = '91519';
const <API key><API key> = '81520';
const <API key> = '915104';
const <API key> = '91546';
const <API key> = '915102';
const <API key> = '915107';
const <API key> = '915108';
const <API key> = '915130';
const <API key> = '91545';
const <API key> = '91548';
const <API key> = '91537';
const <API key> = '91521';
const <API key> = '91554';
const <API key> = '91555';
const <API key> = '91556';
const <API key> = '91557';
const <API key> = '91552';
const <API key> = '91578';
const <API key> = '91551';
const <API key> = '91522';
const <API key> = '91581';
const <API key> = '91529';
const <API key> = '91528';
const <API key> = '91531';
const <API key> = '91553';
const <API key> = '81534';
const <API key> = '81535';
const <API key> = '81536';
const <API key><API key> = '81571';
const <API key> = '91568';
const <API key> = '91570';
const <API key> = '915113';
const <API key> = '915116';
const <API key> = '915115';
const <API key> = '915114';
const <API key> = '915131';
const <API key> = '91523';
const <API key> = '91524';
const <API key> = '91539';
const <API key> = '915171';
const <API key> = '915172';
const <API key> = '915133';
const <API key> = '96101';
const <API key> = '96102';
const <API key> = '96103';
const <API key> = '96104';
const <API key> = '96105';
const <API key> = '96106';
const <API key> = '94201';
const <API key> = '94202';
const <API key> = '94207';
const <API key> = '94203';
const <API key> = '94204';
const <API key> = '94205';
const <API key> = '94206';
const <API key> = '94208';
}
class_alias('Braintree\Error\Codes', '<API key>');
|
var xml = require('xmlbuilder');
var fs = require('fs');
/**
* Function is used to create plis file which is required for downloading ios app.
* @param {string} name app name
* @param {string} path path to application
* @param {string} title title for alert
* @param {Function} callback function which will be called when plist file is created
*/
function creatPlist(name, path, title, callback){
var d = xml.create('plist', {'version':'1.0'})
.ele('dict')
.ele('key','items').up()
.ele('array')
.ele('dict')
.ele('key','assets').up()
.ele('array')
.ele('dict')
.ele('key','kind').up()
.ele('string','software-package').up()
.ele('key','url').up()
.ele('string',path).up()
.up()
.up()
.ele('key','metadata').up()
.ele('dict')
.ele('key','bundle-identifier').up()
.ele('string', name).up()
.ele('key', 'kind').up()
.ele('string','software').up()
.ele('key','title').up()
.ele('string', title)
.up()
.up()
.up()
.up()
.up()
.end({ pretty: true});
//generate unique file path:) use this for now.
var filePath = './processing/file' + new Date().getMilliseconds() + '.plist';
fs.writeFile(filePath, d, function(err){
callback(err,filePath);
});
console.log(xml);
}
exports.creatPlist = creatPlist;
|
<h2><span class="pref">options.data.</span>rows</h2>
<p>Specifies a custom row definition for this item. This allows you to render multiple rows for a single item.</p>
<p>This is useful when you want to have a data item be represented with multiple rows. This is especially useful when you toggle the visibility of the second row via a button (ie. expand/collapse details).</p>
<h5>Type and Default</h5>
<blockquote>
<p><code class="pill green">(object)</code>: Default <code class="pill">undefined</code>.</p>
</blockquote>
<h5>Example</h5>
<pre><code class="language-javascript">rows: {
0: {
height: 20,
formatter: function () {
return "Secondary Row";
}
}
}</code></pre>
<h5>Demo</h5>
<div id="demo-grid"></div>
|
<?php
/**
* Model_Post actions test
*
* @group anonymous
* @group invalid
*/
class PostTest extends <API key>
{
private static $_empty_db = FALSE;
protected function setUp()
{
Kohana::$config->load('database')->default = Kohana::$config->load('database')->test;
Database::$default = 'test';
if (!self::$_empty_db)
$this->prepare_db();
Auth::instance()->login('unittest', '12345');
}
/* QUESTION TEST METHODS */
/*
* Add 10 anonymous questions with ids 1..10
*/
public function <API key>()
{
for ($i = 1; $i < 11; $i++)
$this->addQuestionGuest($i);
}
/**
* @depends <API key>
*/
/*
* Add 10 user questions with ids 10..20
*/
public function testAddQuestionUser()
{
for ($i = 1; $i < 11; $i++)
$this->addQuestionUser($i);
}
/**
* @depends testAddQuestionUser
*/
/*
* error on purpose => id:3 and id:5, update id:13, id:14
*/
public function <API key>()
{
$this->updateUserQuestion(3, FALSE);
$this->updateUserQuestion(5, FALSE);
$this->updateUserQuestion(13);
$this->updateUserQuestion(14);
}
/**
* @depends <API key>
*/
/*
* error on purpose => id:2, delete id:18, id:19
*/
public function <API key>()
{
$this->deleteUserQuestion(2, FALSE);
$this->deleteUserQuestion(18);
$this->deleteUserQuestion(19);
}
/* ANSWER TEST METHODS */
/**
* @depends <API key>
*/
/*
* Add 4 anonymous Answers with ids 21 (parent:1), 22(P:2), 23(P:3), 24(P:1), 25(P:12)
*/
public function testAddAnswerGuest()
{
for ($i = 0; $i < 4; $i++)
$this->addAnswerGuest(($i % 3) + 1);
$this->addAnswerGuest(12);
}
/**
* @depends testAddAnswerGuest
*/
/*
* Add 4 user Answers with ids 26 (P:1), 27(P:4), 28(P:9), 29(P:16)
*/
public function testAddAnswerUser()
{
for ($i = 1; $i < 5; $i++)
$this->addAnswerUser($i * $i);
}
/**
* @depends testAddAnswerUser
*/
/*
* error on purpose => id:21(P:2), id:22(P:1) , update id:25(P:1), id:27(P:9)
*/
public function <API key>()
{
$this->updateUserAnswer(21, 2, FALSE);
$this->updateUserAnswer(22, 1, FALSE);
$this->updateUserAnswer(26, 1);
$this->updateUserAnswer(28, 9);
}
/**
* @depends <API key>
*/
/*
* error on purpose => id:24(P:2), delete id:26(P:4), id:28 (P:16)
*/
public function <API key>()
{
$this->deleteUserAnswer(24, 2, FALSE);
$this->deleteUserAnswer(27, 4);
$this->deleteUserAnswer(29, 16);
}
/**
* @depends <API key>
*/
/*
* error on purpose => id:8, id:13, vote id:1, id:8
*/
public function testVoteQuestion()
{
Auth::instance()->logout(TRUE, TRUE);
Auth::instance()->login('admin', '12345');
$this->voteQuestion(1, 1);
$this->voteQuestion(13, 0);
$this->voteQuestion(8, 1);
$this->voteQuestion(8, 1, FALSE); // error
}
/**
* @depends testVoteQuestion
*/
/*
* error on purpose => id:23, vote id:22, id:23
*/
public function testVoteAnswer()
{
Auth::instance()->logout(TRUE, TRUE);
Auth::instance()->login('admin', '12345');
$this->voteAnswer(22, 0);
$this->voteAnswer(23, 1);
$this->voteAnswer(23, 1, FALSE); // error
}
/**
* @depends testVoteAnswer
*/
public function testAcceptAnswer()
{
Auth::instance()->logout(TRUE, TRUE);
Auth::instance()->login('unittest', '12345');
$this->acceptAnswer(25);
$this->acceptAnswer(24, FALSE); // error: already accepted another answer
}
/**
* @depends testAcceptAnswer
*/
/*
* Add 3 user comments with ids 30 (P:11), 31(P:21), 32(P:26)
*/
public function testAddCommentUser()
{
$this->addCommentUser(11);
$this->addCommentUser(21);
$this->addCommentUser(26);
}
/**
* @depends testAcceptAnswer
*/
/*
* delete id:29(P:10), id:30 (P:11) => error
*/
public function <API key>()
{
$this->deleteCommentUser(30, 11);
$this->deleteCommentUser(31, 11, FALSE);
}
/* PRIVATE METHODS */
private function addQuestionGuest($index)
{
$_POST = array();
$_POST['title'] = "TEST - Question Add $index - guest";
$_POST['content'] = "TEST - Question Add $index Content - guest";
$_POST['tags'] = 't-' . $index . ',a-' . $index . ',b-' . $index;
$question = new Model_Question;
$result_add = $question->insert($_POST);
$this->assertSame(URL::title($_POST['title']), $question->slug);
$this->assertSame(TRUE, $result_add);
}
private function addQuestionUser($index)
{
$user = Auth::instance()->get_user();
$reputation_value = (int) Model_Setting::instance()->get(Model_Reputation::QUESTION_ADD);
$_POST = array();
$_POST['title'] = "TEST - Question Add $index - user";
$_POST['content'] = "TEST - Question Add $index Content - user";
$_POST['user_id'] = $user->id;
$_POST['tags'] = 't-' . $index . ',a-' . $index . ',b-' . $index;
$old_rep = $user->reputation;
$old_question_count = $user->question_count;
$question = new Model_Question;
$result_add = $question->insert($_POST);
$this->assertSame(URL::title($_POST['title']), $question->slug);
$this->assertSame(TRUE, $result_add);
$this->assertSame($user->reputation, $old_rep + $reputation_value);
$this->assertSame($user->question_count, $old_question_count + 1);
}
private function updateUserQuestion($id, $raise_error = TRUE)
{
$user = Auth::instance()->get_user();
$reputation_value = (int) Model_Setting::instance()->get(Model_Reputation::QUESTION_ADD);
$old_rep = $user->reputation;
$old_question_count = $user->question_count;
try {
$post = Model_Question::<API key>($id, $user);
}
catch (Exception $ex) {
if ($raise_error)
$this->assertEquals('<API key>', $ex->getMessage()); // Raise error
return;
}
$_POST = array();
$_POST['title'] = "TEST - Question EDITED $id - user";
$_POST['content'] = "TEST - Question EDITED $id Content - user";
$_POST['user_id'] = $user->id;
$_POST['tags'] = 'updated-tag';
try {
$result_edit = $post->edit($_POST, '');
}
catch (Exception $ex) {
$this->assertEquals('edit', $ex->getMessage()); // Raise error
}
$this->assertSame($user->reputation, $old_rep);
$this->assertSame($user->question_count, $old_question_count);
}
private function deleteUserQuestion($id, $raise_error = TRUE)
{
$user = Auth::instance()->get_user();
$reputation_value = (int) Model_Setting::instance()->get(Model_Reputation::QUESTION_ADD);
$old_rep = $user->reputation;
$old_question_count = $user->question_count;
try {
$post = Model_Question::<API key>($id, $user)->delete();
}
catch (Exception $ex) {
if ($raise_error)
$this->assertEquals('delete', $ex->getMessage()); // Raise error
return;
}
$this->assertSame($user->reputation, $old_rep - $reputation_value);
$this->assertSame($user->question_count, $old_question_count - 1);
}
private function addAnswerGuest($parent_id)
{
$_POST = array();
$_POST['content'] = "TEST - Answer For $parent_id th question Content - guest";
if (($question = Model_Question::get($parent_id)) === NULL)
throw new Kohana_Exception('Question could not be retrieved, ID:' . $parent_id);
$answer = new Model_Answer;
$result_add = $answer->insert($_POST, $parent_id);
$this->assertSame(TRUE, $result_add);
if (($question_updated = Model_Question::get($parent_id)) === NULL)
throw new Kohana_Exception('Question could not be retrieved, ID:' . $parent_id);
$this->assertSame($question->answer_count + 1, (int) $question_updated->answer_count);
}
private function addAnswerUser($parent_id)
{
$user = Auth::instance()->get_user();
$reputation_value = (int) Model_Setting::instance()->get(Model_Reputation::ANSWER_ADD);
$_POST = array();
$_POST['content'] = "TEST - Answer For $parent_id th question Content - user";
$_POST['user_id'] = $user->id;
if (($question = Model_Question::get($parent_id)) === NULL)
throw new Kohana_Exception('Question could not be retrieved, ID: ' . $parent_id);
$old_rep = $user->reputation;
$old_answer_count = $user->answer_count;
$answer = new Model_Answer;
$result_add = $answer->insert($_POST, $parent_id);
$this->assertSame(TRUE, $result_add);
$this->assertSame($user->reputation, $old_rep + $reputation_value);
$this->assertSame($user->answer_count, $old_answer_count + 1);
if (($question_updated = Model_Question::get($parent_id)) === NULL)
throw new Kohana_Exception('Post could not be retrieved, ID:' . $parent_id);
$this->assertSame($question->answer_count + 1, (int) $question_updated->answer_count);
}
private function updateUserAnswer($id, $parent_id, $raise_error = TRUE)
{
$user = Auth::instance()->get_user();
$old_rep = $user->reputation;
$old_answer_count = $user->answer_count;
try {
$post = Model_Answer::<API key>($id, $user);
if ($parent_id != $post->parent_post_id)
throw new Kohana_Exception(sprintf('Given parent id and post parent id are not equal. given: %d, expected: %d'
, $parent_id, $post->parent_post_id));
}
catch (Exception $ex) {
if ($raise_error)
$this->assertEquals('<API key>', $ex->getMessage()); // Raise error
return;
}
$_POST = array();
$_POST['content'] = "TEST - Answer EDITED $id, parent_id: $parent_id Content - user";
$_POST['user_id'] = $user->id;
try {
$question_slug = $post->edit($_POST);
}
catch (Exception $ex) {
$this->assertEquals('edit', $ex->getMessage()); // Raise error
}
$this->assertNotEquals($question_slug, '');
$this->assertSame($user->reputation, $old_rep);
$this->assertSame($user->answer_count, $old_answer_count);
}
private function deleteUserAnswer($id, $parent_id, $raise_error = TRUE)
{
$user = Auth::instance()->get_user();
$reputation_value = (int) Model_Setting::instance()->get(Model_Reputation::ANSWER_ADD);
$old_rep = $user->reputation;
$old_answer_count = $user->answer_count;
try {
$post = Model_Answer::<API key>($id, $user);
if ($parent_id != $post->parent_post_id)
throw new Kohana_Exception(sprintf('Given parent id and post parent id are not equal. given: %d, expected: %d'
, $parent_id, $post->parent_post_id));
}
catch (Exception $ex) {
if ($raise_error)
$this->assertEquals('<API key>', $ex->getMessage()); // Raise error
return;
}
try {
$post->delete();
}
catch (Exception $ex) {
$this->assertEquals('delete', $ex->getMessage()); // Raise error
}
$this->assertSame($user->reputation, $old_rep - $reputation_value);
$this->assertSame($user->answer_count, $old_answer_count - 1);
}
private function voteQuestion($post_id, $vote_type, $raise_error = TRUE)
{
$user = Auth::instance()->get_user();
if ($vote_type === 1)
{
$reputation_value = (int) Model_Setting::instance()->get(Model_Reputation::QUESTION_VOTE_UP);
$<API key> = (int) Model_Setting::instance()->get(Model_Reputation::<API key>);
}
else
{
$reputation_value = (int) Model_Setting::instance()->get(Model_Reputation::QUESTION_VOTE_DOWN);
$<API key> = (int) Model_Setting::instance()->get(Model_Reputation::<API key>);
}
$old_rep = $user->reputation;
if (($post = Model_Question::get($post_id)) === NULL)
{
if ($raise_error)
$this->assertEquals('voteQuestion', "post not found, ID: $post_id"); // Raise error
return;
}
if ($post->user_id === $user->id)
{
if ($raise_error)
$this->assertEquals('voteQuestion', 'You cannot vote on your own posts.'); // Raise error
return;
}
$post_type = Helper_PostType::QUESTION;
if ($post->user_id != 0)
{
if (($owner_user = Model_User::get($post->user_id)) === NULL)
{
$this->assertEquals('voteQuestion', 'Owner user couldnt be fetched. ID:' . $post->user_id); // Raise error
return;
}
$old_rep_owner = $owner_user->reputation;
}
try {
$result = $post->vote($vote_type);
}
catch (Exception $ex) {
$this->assertEquals('vote', $ex->getMessage()); // Raise error
}
if ($result !== 1)
{
if ($raise_error)
$this->assertEquals('voteQuestion', 'You already voted.'); // Raise error
return;
}
$this->assertSame($user->reputation, $old_rep + $reputation_value);
if ($post->user_id != 0)
{
$owner_user = Model_User::get($post->user_id);
$this->assertSame((int) $owner_user->reputation, $old_rep_owner + $<API key>);
}
}
private function voteAnswer($post_id, $vote_type, $raise_error = TRUE)
{
$user = Auth::instance()->get_user();
if ($vote_type === 1)
{
$reputation_value = (int) Model_Setting::instance()->get(Model_Reputation::ANSWER_VOTE_UP);
$<API key> = (int) Model_Setting::instance()->get(Model_Reputation::OWN_ANSWER_VOTED_UP);
}
else
{
$reputation_value = (int) Model_Setting::instance()->get(Model_Reputation::ANSWER_VOTE_DOWN);
$<API key> = (int) Model_Setting::instance()->get(Model_Reputation::<API key>);
}
$old_rep = $user->reputation;
if (($post = Model_Answer::get($post_id)) === NULL)
{
if ($raise_error)
$this->assertEquals('voteAnswer', "post not found, ID: $post_id"); // Raise error
return;
}
if ($post->user_id === $user->id)
{
if ($raise_error)
$this->assertEquals('voteAnswer', 'You cannot vote on your own posts.'); // Raise error
return;
}
$post_type = Helper_PostType::ANSWER;
if ($post->user_id != 0)
{
if (($owner_user = Model_User::get($post->user_id)) === NULL)
{
$this->assertEquals('voteAnswer', 'Owner user couldnt be fetched.'); // Raise error
return;
}
$old_rep_owner = $owner_user->reputation;
}
try {
$result = $post->vote($vote_type);
}
catch (Exception $ex) {
$this->assertEquals('vote', $ex->getMessage()); // Raise error
}
if ($result !== 1)
{
if ($raise_error)
$this->assertEquals('voteAnswer', 'You already voted.'); // Raise error
return;
}
$this->assertSame($user->reputation, $old_rep + $reputation_value);
if ($post->user_id != 0)
{
$owner_user = Model_User::get($post->user_id);
$this->assertSame($owner_user->reputation, $old_rep_owner + $<API key>);
}
}
private function acceptAnswer($post_id, $raise_error = TRUE)
{
$user = Auth::instance()->get_user();
$reputation_value = (int) Model_Setting::instance()->get(Model_Reputation::ACCEPTED_ANSWER);
$<API key> = (int) Model_Setting::instance()->get(Model_Reputation::OWN_ACCEPTED_ANSWER);
$old_rep = $user->reputation;
if (($post = Model_Answer::get($post_id)) === NULL)
{
if ($raise_error)
$this->assertEquals('acceptAnswer', "post not found, ID: $post_id"); // Raise error
return;
}
if ($post->user_id === $user->id)
{
if ($raise_error)
$this->assertEquals('voteAnswer', 'You cannot accept your own posts.'); // Raise error
return;
}
if ($post->user_id != 0)
{
if (($owner_user = Model_User::get($post->user_id)) === NULL)
{
$this->assertEquals('acceptAnswer', 'Owner user couldnt be fetched.'); // Raise error
return;
}
$old_rep_owner = $owner_user->reputation;
}
try {
$result = $post->accept_post();
}
catch (Exception $ex) {
$this->assertEquals('accept_post', $ex->getMessage()); // Raise error
}
if ($result < 1)
{
if ($result === -2 && $raise_error)
$this->assertEquals('voteAnswer', 'Already Accepted An Answer'); // Raise error
elseif ($result === -1 && $raise_error)
$this->assertEquals('voteAnswer', 'Error occured'); // Raise error
return;
}
$this->assertSame($user->reputation, $old_rep + $reputation_value);
if ($post->user_id != 0)
{
$owner_user = Model_User::get($post->user_id);
$this->assertSame($owner_user->reputation, $old_rep_owner + $<API key>);
}
}
private function addCommentUser($parent_id, $raise_error = TRUE)
{
$user = Auth::instance()->get_user();
$reputation_value = (int) Model_Setting::instance()->get(Model_Reputation::COMMENT_ADD);
$old_rep = $user->reputation;
$_POST = array();
$_POST['content'] = "TEST - Comment For $parent_id th post Content - user";
if (($question = Model_Post::get($parent_id)) === NULL && $raise_error)
throw new Kohana_Exception('Post could not be retrieved, ID:' . $parent_id);
try {
$comment = new Model_Comment;
$add_comment_result = $comment->insert($_POST, $parent_id);
}
catch (Exception $ex) {
if ($raise_error)
$this->assertEquals('add_comment', $ex->getMessage()); // Raise error
return;
}
$this->assertSame(TRUE, $add_comment_result > 0);
$this->assertSame($user->reputation, $old_rep + $reputation_value);
if (($question_updated = Model_Post::get($parent_id)) === NULL && $raise_error)
throw new Kohana_Exception('Post could not be retrieved, ID:' . $parent_id);
$this->assertSame($question->comment_count + 1, (int) $question_updated->comment_count);
}
private function deleteCommentUser($comment_id, $parent_id, $raise_error = TRUE)
{
$user = Auth::instance()->get_user();
$reputation_value = (int) Model_Setting::instance()->get(Model_Reputation::COMMENT_ADD);
$old_rep = $user->reputation;
try {
$comment = Model_Comment::<API key>($comment_id, $user);
if ($comment->parent_post_id != $parent_id && $raise_error)
{
$this->assertEquals('delete', 'Parents not matched!'); // Raise error
return;
}
$comment->delete();
}
catch (Exception $ex) {
if ($raise_error)
$this->assertEquals('delete', $ex->getMessage()); // Raise error
return;
}
$this->assertSame($user->reputation, $old_rep - $reputation_value);
}
private function prepare_db()
{
$this-><API key>();
self::$_empty_db = TRUE;
$this-><API key>();
}
private function <API key>()
{
$current_db = DB::select(array(DB::Expr('DATABASE()'), 'database'))->execute()->current();
$test_db = Kohana::$config->load('database')->test;
if ($current_db['database'] !== $test_db['connection']['database'])
{
throw new Kohana_Exception('CURRENT DB IS NOT A TEST DB!!!!!');
}
}
private function <API key>()
{
$this-><API key>('/var/www/qamini/application/db_changes/<API key>.sql');
$this->prepare_tables('/var/www/qamini/application/db_changes/<API key>.sql');
}
private function <API key>($file_name)
{
$this-><API key>($file_name);
}
private function prepare_tables($file_name)
{
$this-><API key>($file_name);
}
private function <API key>($file_name)
{
$sql = '';
$sql = file_get_contents($file_name);
$query_arr = explode(';', $sql);
foreach ($query_arr as $q)
{
if ($q === '') continue;
DB::query(NULL, $q)->execute();
}
}
}
|
package math;
import util.IReplicable;
public class Vector3 implements IReplicable<Vector3> {
private static final float MIN_TOLERANCE = (float) 1E-9;
public float x;
public float y;
public float z;
public static Vector3 of(float x, float y, float z) {
Vector3 vector = new Vector3();
vector.x = x;
vector.y = y;
vector.z = z;
return vector;
}
public static Vector3 getUnitX() {
Vector3 vector = new Vector3();
vector.x = 1;
return vector;
}
public static Vector3 getUnitY() {
Vector3 vector = new Vector3();
vector.y = 1;
return vector;
}
public static Vector3 getUnitZ() {
Vector3 vector = new Vector3();
vector.z = 1;
return vector;
}
public static Vector3 getUnit() {
Vector3 vector = new Vector3();
vector.x = 1;
vector.y = 1;
vector.z = 1;
return vector;
}
public boolean isUnitX() {
return (x == 1) && (y == 0) && (z == 0);
}
public boolean isUnitY() {
return (x == 0) && (y == 1) && (z == 0);
}
public boolean isUnitZ() {
return (x == 0) && (y == 0) && (z == 1);
}
public boolean isUnit() {
return (x == 1) && (y == 1) && (z == 1);
}
public float lengthSquared() {
return (x * x) + (y * y) + (z * z);
}
public float length() {
return (float) Math.sqrt(lengthSquared());
}
public float inverseLength() {
return 1f / length();
}
public static Vector3 add(Vector3 a, Vector3 b) {
Vector3 result = new Vector3();
add(result, a, b);
return result;
}
public static void add(Vector3 result, Vector3 a, Vector3 b) {
result.x = a.x + b.x;
result.y = a.y + b.y;
result.z = a.z + b.z;
}
public static Vector3 subtract(Vector3 a, Vector3 b) {
Vector3 result = new Vector3();
subtract(result, a, b);
return result;
}
public static void subtract(Vector3 result, Vector3 a, Vector3 b) {
result.x = a.x - b.x;
result.y = a.y - b.y;
result.z = a.z - b.z;
}
public static Vector3 multiply(Vector3 a, float scalar) {
Vector3 result = new Vector3();
multiply(result, a, scalar);
return result;
}
public static void multiply(Vector3 result, Vector3 a, float scalar) {
result.x = a.x * scalar;
result.y = a.y * scalar;
result.z = a.z * scalar;
}
public static Vector3 divide(Vector3 a, float scalar) {
Vector3 result = new Vector3();
divide(result, a, scalar);
return result;
}
public static void divide(Vector3 result, Vector3 a, float scalar) {
float multiplier = (scalar <= MIN_TOLERANCE)
? 0
: 1f / scalar;
multiply(result, a, multiplier);
}
public static float dot(Vector3 a, Vector3 b) {
return (a.x * b.x) + (a.y * b.y) + (a.z * b.z);
}
public static Vector3 cross(Vector3 a, Vector3 b) {
Vector3 result = new Vector3();
cross(result, a, b);
return result;
}
public static void cross(Vector3 result, Vector3 a, Vector3 b) {
float x = (a.y * b.z) - (a.z * b.y);
float y = (a.z * b.x) - (a.x * b.z);
float z = (a.x * b.y) - (a.y * b.x);
result.x = x;
result.y = y;
result.z = z;
}
public static Vector3 negate(Vector3 a) {
Vector3 result = new Vector3();
negate(result, a);
return result;
}
public static void negate(Vector3 result, Vector3 a) {
result.x = -a.x;
result.y = -a.y;
result.z = -a.z;
}
public static Vector3 normalise(Vector3 a) {
Vector3 result = new Vector3();
normalise(result, a);
return result;
}
public static void normalise(Vector3 result, Vector3 a) {
float sumSq = (a.x * a.x) + (a.y * a.y) + (a.z * a.z);
if (sumSq <= MIN_TOLERANCE) {
result.x = 0;
result.y = 1;
result.z = 0;
} else {
double sum = Math.sqrt(sumSq);
multiply(result, a, (float) (1.0 / sum));
}
}
@Override
public Vector3 createBlank() {
return new Vector3();
}
@Override
public void copyFrom(Vector3 master) {
this.x = master.x;
this.y = master.y;
this.z = master.z;
}
}
|
using Phaxio.Examples.ReceiveCallback.Models;
using System.Collections.Generic;
using System.Runtime.Caching;
using System.Web.Mvc;
namespace Phaxio.Examples.ReceiveCallback.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
ObjectCache cache = MemoryCache.Default;
var faxList = cache["Callbacks"] as List<FaxReceipt>;
return View(faxList);
}
}
}
|
<!DOCTYPE html>
<html>
<head>
<title>MathNotes</title>
<link rel="stylesheet" href="css/main.css"/>
<link rel="shortcut icon" href="img/pi.png"/>
<script type="text/javascript" async
src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=AM_CHTML">
</script>
</head>
<body>
<ul id="navbar"><li><a href="index.html"><button>Home</button></a></li><li><a href="notes.html"><button>Notes</button></a></li><li><a href="about.html"><button>About</button></a></li><li><a href="contact.html"><button>Contact</button></a></li>
</ul>
<p class = "entry">[5/10/17] Book Notes: 5.2 Proving Trig Identities</p>
<p>Prove: `(x^2-1) / (x-1) - (x^2-1)/(x+1) = 2`</p><br>
<p>`((x-1)(x+1))/(x-1) - ((x+1)(x-1))/((x+1)) =`</p><br>
<p>`(x+1) - (x-1) =`</p><br>
<p>`x+1 - x + 1 =`</p><br>
<p>`2`</p><br>
<hr>
<p>Prove: `tanTheta + cotTheta = secThetacscTheta`</p><br>
<p>`tanTheta + 1 / tanTheta =`</p><br>
<p>`sinTheta / cosTheta + cosTheta / sinTheta =`</p><br>
<p>`(sin^2Theta + cos^2Theta) /(sinThetacosTheta) =`</p><br>
<p>`1 / (sinThetacosTheta) =`</p><br>
<p>`secThetacscTheta`</p><br>
<hr>
<p>Prove: `cosTheta/(1-sinTheta) = (1 + sinTheta)/cosTheta`</p><br>
<p>`((1+sinTheta)(cosTheta))/((1+sinTheta)(1-sinTheta)) =`</p><br>
<p>`((1+sinTheta)(cosTheta))/(1-sin^2Theta) =`</p><br>
<p>`(1+sinTheta)/cosTheta`</p><br>
</body>
</html>
|
{-|
Module : TestUtils.Validate
Description : The Validate type class
Copyright : (c) Andrew Burnett 2014-2015
Maintainer : andyburnett88@gmail.com
Stability : experimental
Portability : Unknown
'Validate' provides a definition for validating a data structure. For example,
we may cache information about the size of a list as it is created. Validate
would check that this is correct
-}
module TestUtils.Validate (
Validate(..)
) where
{-|
The 'Validate' class provides a validate method for types, to make
sure that they have been defined correctly.
-}
class Validate a where
-- | validate should return a 'Bool' which defines whether a data structure
-- | is valid
validate :: a -> Bool
|
'use strict';
define([],
function($) {
var Util = class {
static charToLineCh(string, char) {
var stringUpToChar = string.substr(0, char);
var lines = stringUpToChar.split("\n");
return {
line: lines.length - 1,
ch: lines[lines.length - 1].length
};
}
};
return Util;
});
|
package org.usfirst.frc.team5518.robot.subsystems;
import org.usfirst.frc.team5518.robot.RobotMap;
import org.usfirst.frc.team5518.robot.commands.ArcadeDriveJoystick;
import edu.wpi.first.wpilibj.GenericHID;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.RobotDrive;
import edu.wpi.first.wpilibj.SpeedController;
import edu.wpi.first.wpilibj.Talon;
import edu.wpi.first.wpilibj.command.Subsystem;
public class DrivingSys extends Subsystem {
private RobotDrive robotDrive;
public DrivingSys() {
super();
robotDrive = new RobotDrive(RobotMap.FRONT_LEFT_MOTOR, RobotMap.REAR_LEFT_MOTOR,
RobotMap.FRONT_RIGHT_MOTOR, RobotMap.REAR_RIGHT_MOTOR);
}
public void initDefaultCommand() {
// Set the default command for a subsystem here.
setDefaultCommand(new ArcadeDriveJoystick());
}
public void drive(GenericHID moveStick, final int moveAxis,
GenericHID rotateStick, final int rotateAxis) {
robotDrive.arcadeDrive(moveStick, moveAxis, rotateStick, rotateAxis);
}
public void drive(double moveValue, double rotateValue) {
robotDrive.arcadeDrive(moveValue, rotateValue);
}
public void log() {
}
}
|
<?php
session_start();
if (isset($_SESSION['username'])) {
$username = $_SESSION['username'];
}
$veza = new PDO('mysql:host=' . getenv('MYSQL_SERVICE_HOST') . ';port=3306;dbname=developer_blog', 'admin', 'user');
$veza->exec("set names utf8");
if (isset($_POST['update'])) {
$title = $_POST['title'];
$paragraph = $_POST['paragraph'];
try {
$problem_id = $_GET['id'];
$upit = $veza->prepare("UPDATE part SET title = '$title', text = '$paragraph' WHERE id=?");
$upit->bindValue(1, $problem_id, PDO::PARAM_INT);
$upit->execute();
} catch (Exception $e) {
}
header("location: problems.php");
exit();
}
?>
<!doctype HTML>
<html class="no-js" lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>Developer Blog</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="apple-touch-icon" href="apple-touch-icon.png">
<!-- Place favicon.ico in the root directory -->
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/grid.css">
</head>
<body>
<nav class="nav">
<ul class="nav-list">
<li class="nav-item"><a id="problems" href="problems.php">Problems</a></li>
<li class="nav-item"><a id="tasks" href="tasks.php">Tasks</a></li>
<li class="nav-item"><a id="articles" href="articles.php">Articles</a></li>
<li class="nav-item"><a id="ideas" href="ideas.php">Ideas</a></li>
<?php
if (isset($_SESSION['username'])) {
echo '<li class="nav-item right"><a id="login" href="logout.php">Log Out</a></li>';
echo '<li class="nav-item right"><a id="profile" href="javascript:loadPartialProfile()">Profile</a></li>';
}
else {
echo '<li class="nav-item right"><a id="login" href="login.php">Log In</a></li>';
}
?>
</ul>
</nav>
<!--Content
<div class="content" id="content">
<?php
if (isset($_GET['id'])) {
$problem_id = $_GET['id'];
$title = "";
$paragraph = "";
$upit = $veza->prepare("SELECT * FROM part WHERE id=?");
$upit->bindValue(1, $problem_id, PDO::PARAM_INT);
$upit->execute();
foreach($upit as $childrens) {
if ($childrens['id'] == $problem_id) {
$title = $childrens['title'];
$paragraph = $childrens['text'];
}
}
echo '<form action="shareProblem.php?id=' . $_GET['id'] . '" method="POST">
<div class="row creatingForms">
<h1>Share problem</h1>
<h2>Title</h2>
<input type="text" name="title" id="title" value="' . $title . '">
<h2>Paragraph</h2>
<textarea name="paragraph" id="paragraph" >' . $paragraph . '</textarea>
<div class="centerAlign">
<button type="Submit" name="update" value="problem">Submit Problem</button>
</div>
</div>
</form>';
}
else
echo '<form action="index.php" method="POST">
<div class="row creatingForms">
<h1>Share problem</h1>
<h2>Title</h2>
<input type="text" name="title" id="title">
<h2>Paragraph</h2>
<textarea name="paragraph" id="paragraph"></textarea>
<div class="centerAlign">
<button type="Submit" name="file" value="problem">Submit Problem</button>
</div>
</div>
</form>';
?>
</div>
<script src="js/validations/loginValidation.js"></script>
<script src="js/validations/signupValidation.js"></script>
<script src="js/dropdownmenu.js"></script>
<script src="js/ajax.js"></script>
</body>
</html>
|
#if !NOT_UNITY3D
namespace Zenject
{
public class <API key> : <API key>
{
public <API key>(
BindInfo bindInfo,
<API key> gameObjectInfo)
: base(bindInfo, gameObjectInfo)
{
}
public <API key> WithGameObjectName(string gameObjectName)
{
GameObjectInfo.Name = gameObjectName;
return this;
}
}
}
#endif
|
<?php
namespace Hautelook\ExactTargetBundle\Services;
use ET_Subscriber;
use Hautelook\ExactTargetBundle\Model\Subscriber as <API key>;
class SubscriberService extends AbstractService
{
public function __construct($appSignature, $clientId, $clientSecret, $defaultWsdl)
{
parent::__construct($appSignature, $clientId, $clientSecret, $defaultWsdl);
$this->service = new ET_Subscriber();
$this->service->authStub = $this->client;
$this->properties = new <API key>();
}
}
|
function initBtnStartAlgo(){
$('#btn_startDispatch').bind('click', function(event) {
event.preventDefault();
initAlgo();
createResultPanel("div_resultPanel");
doRound();
printRound("resultRegion");
printResultPersonal("resultPersonal");
<API key>();
});
}
// html
function initAlgo(){
// Fixed: 2014, Dec, 11
var not_here_student = 0;
students = new Array();
avgScore = 0.0;
for(x in regionDatas){
regionDatas[x].queue = new Array();
regionDatas[x].resultArray = new Array();
}
for(var i=1;i<=TOTAL_STUDENT;i++){
var student = new Student();
student.id = i;
student.score = $('#score'+i).val();
student.home = $('#wishList'+i+'_0').val();
student.wish1 = $('#wishList'+i+'_1').val();
student.result = NO_REGION_RESULT;
student.homeFirst = $('#homeFirst'+i).is(':checked');
// Add to lists
students[i-1] = student;
if($('
students[i-1].result = "NA"; // NO_REGION_RESULT
not_here_student++;
continue;
}
// parserInt() used to cause lost of digits. Fixed: 2014, Oct 29
avgScore += parseFloat(student.score);
}
avgScore = avgScore/(<API key>);
var size = Math.pow(10, 2);
avgScore = Math.round(avgScore * size) / size;
}
// Round1Round2Round3() nav-tabs
function createResultPanel(printToDivID){
var str = '<div class="panel panel-info">';
str += '<div class="panel-heading">';
str += '<h3 class="panel-title"> ' + WHAT_T + ' ( '+avgScore+' )</h3>';
str += '</div>';
str += '<div class="panel-body" id="div_dispatchResult">';
str += '<ul class="nav nav-tabs">';
str += '<li class="active"><a href="#resultRegion" data-toggle="tab"></a></li>';
str += '<li><a href="#resultPersonal" data-toggle="tab"></a></li>';
// color block
str += '<li><canvas width="13" height="13" class="colorBlock" style="background:' + fontColors.typeHome + ';"></canvas> </li>';
str += '<li><canvas width="13" height="13" class="colorBlock" style="background:' + fontColors.type1 + ';"></canvas> +</li>';
str += '<li><canvas width="13" height="13" class="colorBlock" style="background:' + fontColors.type2 + ';"></canvas> +</li>';
str += '<li><canvas width="13" height="13" class="colorBlock" style="background:' + fontColors.type3 + ';"></canvas> +</li>';
str += '<li><canvas width="13" height="13" class="colorBlock" style="background:' + fontColors.type4 + ';"></canvas> +</li>';
str += '<li><canvas width="13" height="13" class="colorBlock" style="background:' + fontColors.typeKicked + ';"></canvas> </li>';
str += '</ul>';
str += '<div id="resultTabContent" class="tab-content">';
str += ' <div class="tab-pane fade active in" id="resultRegion"></div>';
str += ' <div class="tab-pane fade" id="resultPersonal"></div>';
str += '</div>';
str += '</div>';
str += '<div class="panel-fotter">';
str += ' <div class="btn-group btn-group-justified">';
str += ' <a href="" class="btn btn-primary" id="btn_downloadTXT">(.txt)</a>';
str += ' <a href="" class="btn btn-info" id="<API key>">(.csv)</a>';
str += ' <a href="" class="btn btn-success" id="<API key>">(.csv)</a>';
str += ' </div>';
str += '</div>';
str += '</div>';
$("#"+printToDivID).html(str);
}
function doRound(){
// queue student.result round
for(var i=0;i<regionDatas.length;i++){
regionDatas[i].queue = new Array();
}
// Step 1: N queue (N depend on round)
var regionDatasLength = regionDatas.length;
for(var k=0;k<TOTAL_STUDENT;k++){
if(students[k].result != NO_REGION_RESULT){
continue;
}
// TODO: key hash
for(var i=0;i<regionDatasLength;i++){
if(students[k].wish1 == regionDatas[i].name){
regionDatas[i].queue.push(students[k]);
}
}
}
// Step 2: queue resultArray
for(var i=0;i<regionDatasLength;i++){
var region = regionDatas[i];
if(region.resultArray.length == region.available){
continue;
}
else if(region.queue.length <= region.available){
region.queue.sort(function(a, b){return a.score-b.score});
<API key>(region, region.queue.length);
}
// resultArray
else{
region.queue.sort(function(a, b){return a.score-b.score});
// "" [30, 40, 60, 90, 100]
// Array.pop() pop ""
cruelFunction(i, region);
}
}
}
// This function is so cruel that I cannot even look at it.
function cruelFunction(regionID, region){
if(regionID<=3){
<API key>(region, region.available);
}else{
region.queue.sort(function(a, b){
if((a.score >= avgScore && b.score >= avgScore) || (a.score < avgScore && b.score < avgScore)){
if(a.home == region.homeName && b.home != region.homeName){
return 1;
}else if(b.home == region.homeName && a.home != region.homeName){
return -1;
}
}
return 0;
});
// queue pop()
region.queue.sort(function(a, b){
if(a.homeFirst==true){
return 1;
}
return 0;
});
<API key>(region, region.available);
}
}
// region queue numberOfItems resultArray
function <API key>(region, numberOfItems){
for(var k=0;k<numberOfItems;k++){
region.resultArray.push(region.queue.pop());
}
<API key>(region.homeName, region.resultArray);
}
// result attribute (resultArray[] items result )
function <API key>(regionName, resultArray){
var length = resultArray.length;
for(var i=0;i<length;i++){
resultArray[i].result = regionName;
}
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>olturf Namespace: toolbars</title>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]
<link type="text/css" rel="stylesheet" href="styles/sunlight.default.css">
<link type="text/css" rel="stylesheet" href="styles/site.simplex.css">
</head>
<body>
<div class="navbar navbar-default navbar-fixed-top ">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="index.html">olturf</a>
<button class="navbar-toggle" type="button" data-toggle="collapse" data-target="#topNavigation">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="navbar-collapse collapse" id="topNavigation">
<ul class="nav navbar-nav">
<li class="dropdown">
<a href="namespaces.list.html" class="dropdown-toggle" data-toggle="dropdown">Namespaces<b class="caret"></b></a>
<ul class="dropdown-menu ">
<li><a href="external-ol.control.html">external:ol.control</a></li><li><a href="olturf.html">olturf</a></li><li><a href="olturf.toolbars.html">olturf.toolbars</a></li>
</ul>
</li>
<li class="dropdown">
<a href="classes.list.html" class="dropdown-toggle" data-toggle="dropdown">Classes<b class="caret"></b></a>
<ul class="dropdown-menu ">
<li><a href="external-ol.control.Control.html">external:ol.control.Control</a></li><li><a href="olturf.Toolbar.html">olturf.Toolbar</a></li>
</ul>
</li>
<li class="dropdown">
<a href="externals.list.html" class="dropdown-toggle" data-toggle="dropdown">Externals<b class="caret"></b></a>
<ul class="dropdown-menu ">
<li><a href="external-ol.html">ol</a></li>
</ul>
</li>
</ul>
<div class="col-sm-3 col-md-3">
<form class="navbar-form" role="search">
<div class="input-group">
<input type="text" class="form-control" placeholder="Search" name="q" id="search-input">
<div class="input-group-btn">
<button class="btn btn-default" id="search-submit"><i class="glyphicon glyphicon-search"></i></button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<div class="container" id="toc-content">
<div class="row">
<div class="col-md-8">
<div id="main">
<h1 class="page-title">Namespace: toolbars</h1>
<section>
<header>
<h2>
<span class="ancestors"><a href="olturf.html">olturf</a>.</span>
toolbars
</h2>
</header>
<article>
<div class="container-overview">
<dl class="details">
</dl>
</div>
<h3 class="subsection-title">Methods</h3>
<dl>
<hr>
<dt>
<h4 class="name" id=".aggregation"><span class="type-signature"><static> </span>aggregation()</h4>
</dt>
<dd>
<div class="description">
<p>Aggregation toolbar: 'collect'</p>
</div>
<dl class="details">
</dl>
<h5>Returns:</h5>
<div class="param-desc">
<p>Control names for the aggregation toolbar</p>
</div>
<dl>
<dt>
Type
</dt>
<dd>
<span class="param-type">Array.<string></span>
</dd>
</dl>
</dd>
<hr>
<dt>
<h4 class="name" id=".all"><span class="type-signature"><static> </span>all()</h4>
</dt>
<dd>
<div class="description">
<p>Toolbar with all controls: 'distance', 'line-distance', 'area', 'bearing',
'center-of-mass', 'center', 'centroid', 'midpoint', 'point-on-surface',
'envelope', 'square', 'circle', 'along', 'destination', 'bezier', 'buffer',
'concave', 'convex', 'difference', 'intersect', 'simplify', 'union',
'combine', 'explode', 'flip', 'kinks', 'line-slice-along', 'point-on-line',
'inside', 'tag', 'within', 'nearest', 'collect', 'random', 'sample',
'isolines', 'planepoint', 'tin', 'hex-grid', 'point-grid', 'square-grid',
'triangle-grid', 'tesselate'</p>
</div>
<dl class="details">
</dl>
<h5>Returns:</h5>
<div class="param-desc">
<p>Control names for all the controls</p>
</div>
<dl>
<dt>
Type
</dt>
<dd>
<span class="param-type">Array.<string></span>
</dd>
</dl>
</dd>
<hr>
<dt>
<h4 class="name" id=".classification"><span class="type-signature"><static> </span>classification()</h4>
</dt>
<dd>
<div class="description">
<p>Classification toolbar: 'nearest'</p>
</div>
<dl class="details">
</dl>
<h5>Returns:</h5>
<div class="param-desc">
<p>Control names for the classification toolbar</p>
</div>
<dl>
<dt>
Type
</dt>
<dd>
<span class="param-type">Array.<string></span>
</dd>
</dl>
</dd>
<hr>
<dt>
<h4 class="name" id=".data"><span class="type-signature"><static> </span>data()</h4>
</dt>
<dd>
<div class="description">
<p>Data toolbar: 'random', 'sample'</p>
</div>
<dl class="details">
</dl>
<h5>Returns:</h5>
<div class="param-desc">
<p>Control names for the data toolbar</p>
</div>
<dl>
<dt>
Type
</dt>
<dd>
<span class="param-type">Array.<string></span>
</dd>
</dl>
</dd>
<hr>
<dt>
<h4 class="name" id=".grids"><span class="type-signature"><static> </span>grids()</h4>
</dt>
<dd>
<div class="description">
<p>Grids toolbar: 'hex-grid', 'point-grid', 'square-grid', 'triangle-grid',
'tesselate'</p>
</div>
<dl class="details">
</dl>
<h5>Returns:</h5>
<div class="param-desc">
<p>Control names for the grids toolbar</p>
</div>
<dl>
<dt>
Type
</dt>
<dd>
<span class="param-type">Array.<string></span>
</dd>
</dl>
</dd>
<hr>
<dt>
<h4 class="name" id=".interpolation"><span class="type-signature"><static> </span>interpolation()</h4>
</dt>
<dd>
<div class="description">
<p>Interpolation toolbar: 'isolines', 'planepoint', 'tin'</p>
</div>
<dl class="details">
</dl>
<h5>Returns:</h5>
<div class="param-desc">
<p>Control names for the interpolation toolbar</p>
</div>
<dl>
<dt>
Type
</dt>
<dd>
<span class="param-type">Array.<string></span>
</dd>
</dl>
</dd>
<hr>
<dt>
<h4 class="name" id=".joins"><span class="type-signature"><static> </span>joins()</h4>
</dt>
<dd>
<div class="description">
<p>Joins toolbar: 'inside', 'tag', 'within'</p>
</div>
<dl class="details">
</dl>
<h5>Returns:</h5>
<div class="param-desc">
<p>Control names for the joins toolbar</p>
</div>
<dl>
<dt>
Type
</dt>
<dd>
<span class="param-type">Array.<string></span>
</dd>
</dl>
</dd>
<hr>
<dt>
<h4 class="name" id=".measurement"><span class="type-signature"><static> </span>measurement()</h4>
</dt>
<dd>
<div class="description">
<p>Measurement toolbar: 'distance', 'line-distance', 'area', 'bearing',
'center-of-mass', 'center', 'centroid', 'midpoint',
'point-on-surface', 'envelope', 'square', 'circle',
'along', 'destination'</p>
</div>
<dl class="details">
</dl>
<h5>Returns:</h5>
<div class="param-desc">
<p>Control names for the measurement toolbar</p>
</div>
<dl>
<dt>
Type
</dt>
<dd>
<span class="param-type">Array.<string></span>
</dd>
</dl>
</dd>
<hr>
<dt>
<h4 class="name" id=".misc"><span class="type-signature"><static> </span>misc()</h4>
</dt>
<dd>
<div class="description">
<p>Miscellaneous toolbar: 'combine', 'explode', 'flip', 'kinks',
'line-slice-along', 'point-on-line'</p>
</div>
<dl class="details">
</dl>
<h5>Returns:</h5>
<div class="param-desc">
<p>Control names for the miscellaneous toolbar</p>
</div>
<dl>
<dt>
Type
</dt>
<dd>
<span class="param-type">Array.<string></span>
</dd>
</dl>
</dd>
<hr>
<dt>
<h4 class="name" id=".transformation"><span class="type-signature"><static> </span>transformation()</h4>
</dt>
<dd>
<div class="description">
<p>Transformation toolbar: 'bezier', 'buffer', 'concave', 'convex',
'difference', 'intersect', 'simplify', 'union'</p>
</div>
<dl class="details">
</dl>
<h5>Returns:</h5>
<div class="param-desc">
<p>Control names for the transformation toolbar</p>
</div>
<dl>
<dt>
Type
</dt>
<dd>
<span class="param-type">Array.<string></span>
</dd>
</dl>
</dd>
</dl>
</article>
</section>
</div>
</div>
<div class="clearfix"></div>
<div class="col-md-3">
<div id="toc" class="col-md-3 hidden-xs hidden-sm hidden-md"></div>
</div>
</div>
</div>
<div class="modal fade" id="searchResults">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Search results</h4>
</div>
<div class="modal-body"></div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div>
<footer>
<span class="jsdoc-message">
Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.6.4</a>
using the <a href="https://github.com/docstrap/docstrap">DocStrap template</a>.
</span>
</footer>
<script src="scripts/docstrap.lib.js"></script>
<script src="scripts/toc.js"></script>
<script type="text/javascript" src="scripts/fulltext-search-ui.js"></script>
<script>
$( function () {
$( "[id*='$']" ).each( function () {
var $this = $( this );
$this.attr( "id", $this.attr( "id" ).replace( "$", "__" ) );
} );
$( ".tutorial-section pre, .readme-section pre, pre.prettyprint.source" ).each( function () {
var $this = $( this );
var example = $this.find( "code" );
exampleText = example.html();
var lang = /{@lang (.*?)}/.exec( exampleText );
if ( lang && lang[1] ) {
exampleText = exampleText.replace( lang[0], "" );
example.html( exampleText );
lang = lang[1];
} else {
var langClassMatch = example.parent()[0].className.match(/lang\-(\S+)/);
lang = langClassMatch ? langClassMatch[1] : "javascript";
}
if ( lang ) {
$this
.addClass( "sunlight-highlight-" + lang )
.addClass( "linenums" )
.html( example.html() );
}
} );
Sunlight.highlightAll( {
lineNumbers : false,
showMenu : true,
enableDoclinks : true
} );
$.catchAnchorLinks( {
navbarOffset: 10
} );
$( "#toc" ).toc( {
anchorName : function ( i, heading, prefix ) {
return $( heading ).attr( "id" ) || ( prefix + i );
},
selectors : "#toc-content h1,#toc-content h2,#toc-content h3,#toc-content h4",
showAndHide : false,
smoothScrolling: true
} );
$( "#main span[id^='toc']" ).addClass( "toc-shim" );
$( '.dropdown-toggle' ).dropdown();
$( "table" ).each( function () {
var $this = $( this );
$this.addClass('table');
} );
} );
</script>
<!--Navigation and Symbol Display
<!--Google Analytics
<script type="text/javascript">
$(document).ready(function() {
SearcherDisplay.init();
});
</script>
</body>
</html>
|
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using QEngine.Physics.Shared;
using QEngine.Physics.Tools.Triangulation.Delaunay.Delaunay;
using QEngine.Physics.Tools.Triangulation.Delaunay.Delaunay.Sweep;
namespace QEngine.Physics.Tools.Triangulation.Delaunay
{
<summary>
2D constrained Delaunay triangulation algorithm.
Based on the paper "Sweep-line algorithm for constrained Delaunay triangulation" by V. Domiter and and B. Zalik
Properties:
- Creates triangles with a large interior angle.
- Supports holes
- Generate a lot of garbage due to incapsulation of the Poly2Tri library.
- Running time is O(n^2), n = number of vertices.
- Does not care about winding order.
Source: http://code.google.com/p/poly2tri/
</summary>
internal static class CDTDecomposer
{
<summary>
Decompose the polygon into several smaller non-concave polygon.
</summary>
public static List<Vertices> ConvexPartition(Vertices vertices)
{
System.Diagnostics.Debug.Assert(vertices.Count > 3);
Polygon.Polygon poly = new Polygon.Polygon();
foreach (Vector2 vertex in vertices)
poly.Points.Add(new TriangulationPoint(vertex.X, vertex.Y));
if (vertices.Holes != null)
{
foreach (Vertices holeVertices in vertices.Holes)
{
Polygon.Polygon hole = new Polygon.Polygon();
foreach (Vector2 vertex in holeVertices)
hole.Points.Add(new TriangulationPoint(vertex.X, vertex.Y));
poly.AddHole(hole);
}
}
DTSweepContext tcx = new DTSweepContext();
tcx.<API key>(poly);
DTSweep.Triangulate(tcx);
List<Vertices> results = new List<Vertices>();
foreach (DelaunayTriangle triangle in poly.Triangles)
{
Vertices v = new Vertices();
foreach (TriangulationPoint p in triangle.Points)
{
v.Add(new Vector2((float)p.X, (float)p.Y));
}
results.Add(v);
}
return results;
}
}
}
|
// ViewController.h
// XSInfoView
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
|
<?php
namespace Sf\TodoBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class SfTodoBundle extends Bundle
{
}
|
import * as _ from 'lodash';
import Vuex from 'vuex';
import {Deck} from '../models/Deck'
import DeckState from '../models/state/DeckState'
const store =
{
state: new DeckState(),
mutations:
{
addToDeck(state, card)
{
if (!card) { return; }
state.currentDeck.cards.push(card);
if (!_.some(state.allDecks, thatDeck => thatDeck == state.currentDeck))
{
state.allDecks.push(state.currentDeck);
}
localStorage["currentDeck"] = JSON.stringify(state.currentDeck);
},
removeFromDeck(state, card)
{
if (card == undefined) { return; }
let cardIndex = state.currentDeck.cards.indexOf(card);
if (cardIndex < 0) { return; }
state.currentDeck.cards.splice(cardIndex, 1);
localStorage["currentDeck"] = JSON.stringify(state.currentDeck);
},
removeAllFromDeck(state, card)
{
if (card == undefined) { return; }
var filtered = state.currentDeck.cards.filter(c => c.multiverseid != card.multiverseid);
state.currentDeck.cards = filtered;
localStorage["currentDeck"] = JSON.stringify(state.currentDeck);
},
loadDeck(state, deck)
{
if (deck == undefined) { return; }
state.allDecks.push(deck);
state.currentDeck = state.allDecks[state.allDecks.length - 1];
},
deleteCurrentDeck(state)
{
var deckIndex = state.allDecks.indexOf(state.currentDeck);
state.allDecks.splice(deckIndex, 1);
},
clearDeck(state)
{
state.currentDeck.cards = [];
localStorage["currentDeck"] = JSON.stringify(state.currentDeck);
},
setCurrentDeck(state, deck)
{
if (deck == undefined) { return; }
state.currentDeck = deck;
localStorage["currentDeck"] = JSON.stringify(state.currentDeck);
}
}
};
export default store
|
namespace _01.SchoolClasses
{
// Disciplines have name, number of lectures and number of exercises
using System;
class Disciplines : <API key>
{
private int lecturesNumber;
private int exercisesNumber;
public Disciplines(string name, int lecturesNumber, int exercisesNumber)
:base(name)
{
this.LecturesNumber = lecturesNumber;
this.ExercisesNumber = exercisesNumber;
}
public int LecturesNumber
{
get
{
return this.lecturesNumber;
}
private set
{
if (CheckForValidValue(value))
{
this.lecturesNumber = value;
}
}
}
public int ExercisesNumber
{
get
{
return this.exercisesNumber;
}
private set
{
if (CheckForValidValue(value))
{
this.exercisesNumber = value;
}
}
}
private static bool CheckForValidValue(int value)
{
if (value < 1 || value > 10)
{
throw new <API key>("THe number of Lectures Or Exercises should be bewtween 1 and 10");
}
return true;
}
}
}
|
module Language.Aspell (
-- * Constructors
SpellChecker,
spellChecker,
<API key>,
<API key>,
-- * Using the spell checker
check,
suggest
) where
import Data.ByteString.Char8
import Foreign
#if !MIN_VERSION_base(4,7,0)
hiding (unsafePerformIO)
#endif
import Foreign.C.String
import Foreign.C.Types
import Language.Aspell.Options
import System.IO.Unsafe
type AspellConfig = ForeignPtr ()
type SpellChecker = ForeignPtr ()
type CAspellConfig = Ptr ()
type CSpellChecker = Ptr ()
type CAspellCanHaveError = Ptr ()
type CWordList = Ptr ()
type CStringEnumeration = Ptr ()
newConfig :: IO AspellConfig
newConfig = do
cf <- new_aspell_config
newForeignPtr <API key> cf
setOpts :: [ACOption] -> AspellConfig -> IO AspellConfig
setOpts (Dictionary dict:opts) pt = setOpt "master" dict pt >>= setOpts opts
setOpts (WordListDir dir:opts) pt = setOpt "dict-dir" dir pt >>= setOpts opts
setOpts (Lang lang:opts) pt = setOpt "lang" lang pt >>= setOpts opts
setOpts (Size size:opts) pt = setOpt "size" newSize pt >>= setOpts opts
where
newSize = case size of
Tiny -> "+10"
ReallySmall -> "+20"
Small -> "+30"
MediumSmall -> "+40"
Medium -> "+50"
MediumLarge -> "+60"
Large -> "+70"
Huge -> "+80"
Insane -> "+90"
setOpts (PersonalWordList wl:opts) pt = setOpt "personal" wl pt >>= setOpts opts
setOpts (ReplacementsList rl:opts) pt = setOpt "repl" rl pt >>= setOpts opts
setOpts (Encoding encoding:opts) pt = setOpt "encoding" enc pt >>= setOpts opts
where
enc = case encoding of
UTF8 -> "utf-8"
Latin1 -> "iso-8859-1"
setOpts (Normalize n:opts) pt = setOptBool "normalize" n pt >>= setOpts opts
setOpts (NormalizeStrict n:opts) pt = setOptBool "norm-strict" n pt >>= setOpts opts
setOpts (NormalizeForm form:opts) pt = setOpt "norm-form" nform pt >>= setOpts opts
where
nform = case form of
None -> "none"
NFD -> "nfd"
NFC -> "nfc"
Composed -> "comp"
setOpts (NormalizeRequired b:opts) pt = setOptBool "norm-required" b pt >>= setOpts opts
setOpts (Ignore i:opts) pt = setOptInteger "ignore" i pt >>= setOpts opts
setOpts (IgnoreReplace b:opts) pt = setOptBool "ignore-repl" b pt >>= setOpts opts
setOpts (SaveReplace b:opts) pt = setOptBool "save-repl" b pt >>= setOpts opts
setOpts (KeyboardDef s:opts) pt = setOpt "keyboard" s pt >>= setOpts opts
setOpts (SuggestMode sm:opts) pt = setOpt "sug-mode" mode pt >>= setOpts opts
where
mode = case sm of
Ultra -> "ultra"
Fast -> "fast"
Normal -> "normal"
Slow -> "slow"
BadSpellers -> "bad-spellers"
setOpts (IgnoreCase b:opts) pt = setOptBool "ignore-case" b pt >>= setOpts opts
setOpts (IgnoreAccents b:opts) pt = setOptBool "ignore-accents" b pt >>= setOpts opts
setOpts (FilterMode s:opts) pt = setOpt "mode" s pt >>= setOpts opts
setOpts (EmailMargin n:opts) pt = setOptInteger "email-margin" n pt >>= setOpts opts
setOpts (TeXCheckComments b:opts) pt = setOptBool "tex-check-comments" b pt >>= setOpts opts
setOpts (ContextVisibleFirst b:opts) pt = setOptBool "<API key>" b pt >>= setOpts opts
setOpts (RunTogether b:opts) pt = setOptBool "run-together" b pt >>= setOpts opts
setOpts (RunTogetherLimit n:opts) pt = setOptInteger "run-together-limit" n pt >>= setOpts opts
setOpts (RunTogetherMin n:opts) pt = setOptInteger "run-together-min" n pt >>= setOpts opts
setOpts (MainConfig s:opts) pt = setOpt "conf" s pt >>= setOpts opts
setOpts (MainConfigDir s:opts) pt = setOpt "conf-dir" s pt >>= setOpts opts
setOpts (DataDir s:opts) pt = setOpt "data-dir" s pt >>= setOpts opts
setOpts (LocalDataDir s:opts) pt = setOpt "local-data-dir" s pt >>= setOpts opts
setOpts (HomeDir s:opts) pt = setOpt "home-dir" s pt >>= setOpts opts
setOpts (PersonalConfig s:opts) pt = setOpt "per-conf" s pt >>= setOpts opts
setOpts (Layout s:opts) pt = setOpt "keyboard" s pt >>= setOpts opts
setOpts (Prefix s:opts) pt = setOpt "prefix" s pt >>= setOpts opts
setOpts (SetPrefix b:opts) pt = setOptBool "set-prefix" b pt >>= setOpts opts
setOpts [] pt = return pt
setOpt :: ByteString
-> ByteString
-> AspellConfig
-> IO AspellConfig
setOpt key value pt = do
withForeignPtr pt $ \ac ->
useAsCString key $ \k ->
useAsCString value $ <API key> ac k
return pt
setOptBool :: ByteString -> Bool -> AspellConfig -> IO AspellConfig
setOptBool k v = setOpt k (if v then "true" else "false")
setOptInteger :: ByteString -> Integer -> AspellConfig -> IO AspellConfig
setOptInteger k v = setOpt k (pack $ show v)
-- | Creates a spell checker with default options.
-- 'spellChecker' = '<API key>' []
spellChecker :: IO (Either ByteString SpellChecker)
spellChecker = <API key> []
-- | Creates a spell checker with a custom set of options.
<API key> :: [ACOption] -> IO (Either ByteString SpellChecker)
<API key> opts = do
cf <- newConfig
setOpts opts cf
canError <- withForeignPtr cf new_aspell_speller
(errNum :: Int) <- fromIntegral `fmap` aspell_error_number canError
if errNum > 0
then do
errMsg <- <API key> canError >>= packCString
return $ Left errMsg
else do
speller <- to_aspell_speller canError
for <- newForeignPtr <API key> speller
return $ Right for
-- | Convenience function for specifying a dictionary.
-- You can determine which dictionaries are available to you with @aspell dump dicts@.
-- '<API key>' dict = '<API key>' ['Dictionary' dict]
<API key> :: ByteString -> IO (Either ByteString SpellChecker)
<API key> b = <API key> [Dictionary b]
-- | Checks if a word has been spelled correctly.
check :: SpellChecker -> ByteString -> Bool
check checker word = unsafePerformIO $
withForeignPtr checker $ \ck ->
useAsCString word $ \w -> do
res <- <API key> ck w $ negate 1
return $ res == 1
-- | Lists suggestions for misspelled words.
-- If the input is not misspelled according to the dictionary, returns @[]@.
suggest :: SpellChecker -> ByteString -> IO [ByteString]
suggest checker word = withForeignPtr checker $ \ck ->
useAsCString word $ \w -> do
wlist <- <API key> ck w (negate 1)
elems <- <API key> wlist
suggestions <- strEnumToList elems
<API key> elems
return suggestions
strEnumToList :: CStringEnumeration -> IO [ByteString]
strEnumToList enum = go enum
where go e = do
nw <- <API key> enum
if nw == nullPtr
then return []
else do
curWord <- packCString nw
next <- go e
return $ curWord:next
foreign import ccall unsafe "aspell.h &<API key>"
<API key> :: FunPtr (CAspellConfig -> IO ())
foreign import ccall unsafe "aspell.h &<API key>"
<API key> :: FunPtr (CSpellChecker -> IO ())
foreign import ccall unsafe "aspell.h <API key>"
<API key> :: CStringEnumeration -> IO ()
foreign import ccall unsafe "aspell.h new_aspell_config"
new_aspell_config :: IO CAspellConfig
foreign import ccall unsafe "aspell.h <API key>"
<API key> :: CAspellConfig
-> CString
-> CString
-> IO CAspellConfig
foreign import ccall unsafe "aspell.h new_aspell_speller"
new_aspell_speller :: CAspellConfig
-> IO CAspellCanHaveError
foreign import ccall unsafe "aspell.h aspell_error_number"
aspell_error_number :: CAspellCanHaveError
-> IO CUInt
foreign import ccall unsafe "aspell.h <API key>"
<API key> :: CAspellCanHaveError
-> IO CString
foreign import ccall unsafe "aspell.h to_aspell_speller"
to_aspell_speller :: CAspellCanHaveError
-> IO CSpellChecker
foreign import ccall unsafe "aspell.h <API key>"
<API key> :: CSpellChecker
-> CString
-> CInt
-> IO CInt
foreign import ccall unsafe "aspell.h <API key>"
<API key> :: CSpellChecker
-> CString
-> CInt
-> IO CWordList
foreign import ccall unsafe "aspell.h <API key>"
<API key> :: CWordList
-> IO CStringEnumeration
foreign import ccall unsafe "aspell.h <API key>"
<API key> :: CStringEnumeration
-> IO CString
|
# == Schema Information
# Table name: github_stargazers
# id :integer not null, primary key
# linked_account_id :integer not null
# tracker_id :integer not null
# stargazer :boolean
# subscriber :boolean
# forker :boolean
# synced_at :datetime
# created_at :datetime
# updated_at :datetime
class GithubStargazer < ApplicationRecord
belongs_to :linked_account, class_name: 'LinkedAccount::Github::User'
belongs_to :tracker, class_name: 'Github::Repository'
# options
# - oauth_token
# - tracker_ids:[123,456] | tracker_id:123
def self.sync_stargazers_for(options)
# require trackers
return if options[:tracker_ids].blank?
# get array of all stargazers, watchers, and forkers
start_time = Time.now
responses = <API key>(options)
logger.error "STARGAZER API TIME: #{Time.now-start_time}"
# # delete existing stargazers
GithubStargazer.where(tracker_id: options[:tracker_ids]).delete_all
# translate array into hash and group by github user and tracker id
response_hash = responses.inject({}) do |h,(tr_id, gh_uid, w_type)|
h[gh_uid] ||= {}
h[gh_uid][tr_id] ||= {}
h[gh_uid][tr_id][w_type] = true
h
end
# create all linked accounts
time_now_sql = GithubStargazer.connection.quote(Time.now)
response_hash.to_a.in_groups_of(1000,false) do |group|
# find which github remote ids we're dealing with
gh_uids = group.map(&:first)
# create any missing linked_accounts
rails_autoload = [LinkedAccount::Github, LinkedAccount::Github::Organization, LinkedAccount::Github::User]
existing_gh_uids = LinkedAccount::Github.where(uid: gh_uids).pluck(:uid)
missing_gh_uids = gh_uids - existing_gh_uids
if missing_gh_uids.length > 0
missing_gh_uids_sql = missing_gh_uids.map { |uid| "(#{time_now_sql}, #{time_now_sql}, 'LinkedAccount::Github::User', #{uid.to_i})" }
LinkedAccount::Github.connection.insert("INSERT INTO linked_accounts (created_at, updated_at, type, uid) VALUES #{missing_gh_uids_sql.join(',')}")
end
# create linked account hash
linked_account_hash = LinkedAccount::Github.where(uid: gh_uids).pluck(:id, :uid).inject({}) { |h,(id,uid)| h[uid]=id; h }
stargazer_inserts = []
group.each do |ghuid, tracker_map|
tracker_map.each do |tracker_id, hash|
stargazer_inserts << "(#{time_now_sql}, #{time_now_sql}, #{linked_account_hash[ghuid]}, #{tracker_id}, #{!!hash[:stargazer]}, #{!!hash[:subscriber]}, #{!!hash[:forker]})"
end
end
GithubStargazer.connection.insert("INSERT INTO github_stargazers (created_at, updated_at, linked_account_id, tracker_id, stargazer, subscriber, forker) VALUES #{stargazer_inserts.join(',')}")
end
end
protected
# this is an event machine that does 20 concurrent connections to get all of the stargazers, watchers, and forkers
def self.<API key>(options)
# queue up initial page loads, with page=nil
requests = []
tracker_map = Tracker.where(id: options[:tracker_ids]).pluck(:id, :remote_id).inject({}) { |h,(id,remote_id)| h[id] = remote_id; h }
options[:tracker_ids].each do |tracker_id|
[:stargazer, :subscriber, :forker].each do |watch_type|
requests.push(
tracker_id: tracker_id,
<API key>: tracker_map[tracker_id],
watch_type: watch_type
)
end
end
# where the responses go
responses = []
concurrent_requests = 0
<API key> = 20
no_requests_until = Time.now
EM.run do
repeater = Proc.new do
# puts "REPEATER #{concurrent_requests} < #{<API key>} && #{requests.length} > 0 && #{no_requests_until} < #{Time.now}"
if concurrent_requests < <API key> && requests.length > 0 && no_requests_until < Time.now
concurrent_requests += 1
request = requests.shift
url_path = case request[:watch_type]
when :stargazer then 'stargazers'
when :subscriber then 'subscribers'
when :forker then 'forks'
end
# generate request
params = { per_page: 25 }
params[:page] = request[:page] if request[:page]
if options[:oauth_token]
params[:oauth_token] = options[:oauth_token]
else
params[:client_id] = Api::Application.config.github_api[:client_id]
params[:client_secret] = Api::Application.config.github_api[:client_secret]
end
url = "https://api.github.com/repositories/#{request[:<API key>]}/#{url_path}?#{params.to_param}"
# puts "REQUEST: #{url}"
http = EventMachine::HttpRequest.new(url).get
callback = proc { |http|
# puts "RESPONSE: #{url}"
concurrent_requests -= 1
if http.response_header.status == 200
# if the request was for the first page (page=nil), then queue up the rest of the pages
if http.response_header['LINK'] && !request[:page]
last_page = http.response_header['LINK'].scan(/page=(\d+)>; rel="last"/)[0][0].to_i
(2..last_page).each { |page| requests << request.merge(page: page) }
end
# parse response
JSON.parse(http.response).each do |row|
responses << [
request[:tracker_id],
request[:watch_type] == :forker ? row['owner']['id'] : row['id'],
request[:watch_type]
]
end
# queue the next one
repeater.call
elsif http.response_header.status == 404
# tracker deleted! queue remote_sync so it gets marked as deleted
Tracker.find(request[:tracker_id]).delay.remote_sync
elsif http.response.try(:include?, "abuse-rate-limits") && (request[:retries]||0) < 3
puts "DELAY 60 SECONDS"
no_requests_until = Time.now + 60.seconds
requests << request.merge(retries: (request[:retries]||0) + 1)
else
puts "ERROR: #{url}"
puts http.try(:errors)
puts http.response
pp http.response_header
EM.stop
end
}
http.callback &callback
http.errback &callback
# if we queued a request, maybe we can queue another
repeater.call
elsif concurrent_requests == 0 && requests.length == 0
EM.stop
end
end
EventMachine::PeriodicTimer.new(1) { repeater.call }
repeater.call
end
responses
end
end
|
'use strict';
angular.module('articles').controller('<API key>', ['$scope', '$timeout', '$stateParams', '$window', 'Authentication', 'FileUploader', 'Articles',
function ($scope, $timeout, $stateParams, $window, Authentication, FileUploader, Articles) {
$scope.user = Authentication.user;
$scope.article = Articles.get({
articleId: $stateParams.articleId
});
$scope.imageURL = $scope.article.headerMedia || null;
// Create file uploader instance
$scope.uploader = new FileUploader({
url: 'api/articles/' + $stateParams.articleId + '/headerimage',
alias: 'newHeaderImage'
});
// Set file uploader image filter
$scope.uploader.filters.push({
name: 'imageFilter',
fn: function (item, options) {
var type = '|' + item.type.slice(item.type.lastIndexOf('/') + 1) + '|';
return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1;
}
});
// Called after the user selected a new picture file
$scope.uploader.onAfterAddingFile = function (fileItem) {
if ($window.FileReader) {
var fileReader = new FileReader();
fileReader.readAsDataURL(fileItem._file);
fileReader.onload = function (fileReaderEvent) {
$timeout(function () {
$scope.imageURL = fileReaderEvent.target.result;
}, 0);
};
}
};
// Called after the article has been assigned a new header image
$scope.uploader.onSuccessItem = function (fileItem, response, status, headers) {
// Show success message
$scope.success = true;
// Populate user object
$scope.user = Authentication.user = response;
// Clear upload buttons
$scope.cancelUpload();
};
// Called after the user has failed to upload a new picture
$scope.uploader.onErrorItem = function (fileItem, response, status, headers) {
// Clear upload buttons
$scope.cancelUpload();
// Show error message
$scope.error = response.message;
};
// Change article header image
$scope.uploadHeaderImage = function () {
console.log($scope);
// Clear messages
$scope.success = $scope.error = null;
// Start upload
$scope.uploader.uploadAll();
};
// Cancel the upload process
$scope.cancelUpload = function () {
$scope.uploader.clearQueue();
//$scope.imageURL = $scope.article.profileImageURL;
};
}
]);
|
#chrome-heart {
display: inline-block;
margin-bottom: -30px;
background: url(../images/chrome_logo.png) 50% 50% no-repeat;
width: 100px;
height: 100px;
background-position: 50% 50%;
background-size: cover;
}
.spin {
-<API key>: rotateRight;
-<API key>: 10s;
-<API key>: linear;
-<API key>: 50% 50%;
-<API key>: infinite;
}
.spin:hover {
-<API key>: 0.1s;
}
@-webkit-keyframes rotateRight {
from {
-webkit-transform: rotate(0);
}
to {
-webkit-transform: rotate(360deg);
}
}
|
# Halitosis
TODO: Write a gem description
## Installation
Add this line to your application's Gemfile:
gem 'halitosis'
And then execute:
$ bundle
Or install it yourself as:
$ gem install halitosis
## Usage
TODO: Write usage instructions here
## Contributing
1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request
|
/** @jsx h */
import h from '../../../helpers/h'
import { Mark } from '../../../..'
export default function(change) {
change.addMark(
Mark.create({
type: 'bold',
data: { thing: 'value' },
})
)
}
export const input = (
<value>
<document>
<paragraph>
<anchor />w<focus />ord
</paragraph>
</document>
</value>
)
export const output = (
<value>
<document>
<paragraph>
<anchor />
<b thing="value">w</b>
<focus />ord
</paragraph>
</document>
</value>
)
|
<?php
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* App\Entity$<API key>.
*
* @ORM\Table(name="<API key>")
* @ORM\Entity(repositoryClass="App\Repository\<API key>")
*/
class <API key>
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var Editeur
*
* @ORM\ManyToOne(
* targetEntity="App\Entity\Editeur",
* inversedBy="<API key>"
* )
* @ORM\JoinColumn(nullable=false)
*/
private $editeur;
/**
* @var NatureSupport
*
* @ORM\ManyToOne(
* targetEntity="App\Entity\NatureSupport",
* inversedBy="<API key>"
* )
* @ORM\JoinColumn(
* name="naturesupport_id",
* <API key>="id",
* nullable=false
* )
*/
private $natureSupport;
/**
* @var Collection
*
* @ORM\ManyToMany(
* targetEntity="App\Entity\CategorieOeuvre",
* inversedBy="<API key>"
* )
* @ORM\JoinTable(
* name="<API key>",
* joinColumns={
* @ORM\JoinColumn(
* name="<API key>",
* <API key>="id"
* )
* },
* inverseJoinColumns={
* @ORM\JoinColumn(
* name="categorieoeuvre_id",
* <API key>="id"
* )
* }
* )
*/
private $categoriesOeuvres;
/**
* @var Collection
*
* @ORM\OneToMany(
* targetEntity="App\Entity\Support",
* mappedBy="<API key>"
* )
*/
private $supports;
/**
* Constructeur.
*
* @param Editeur|null $editeur
* @param NatureSupport|null $natureSupport
*/
public function __construct(
Editeur $editeur = null,
NatureSupport $natureSupport = null
) {
$this->editeur = $editeur;
$this->natureSupport = $natureSupport;
$this->categoriesOeuvres = new ArrayCollection();
}
/**
* Get id.
*
* @return int
*/
public function getId(): int
{
return $this->id;
}
/**
* Set editeur.
*
* @param Editeur|null $editeur
*/
public function setEditeur(Editeur $editeur = null): void
{
$this->editeur = $editeur;
}
/**
* Get editeur.
*
* @return Editeur
*/
public function getEditeur(): ?Editeur
{
return $this->editeur;
}
/**
* Set natureSupport.
*
* @param NatureSupport|null $natureSupport
*/
public function setNatureSupport(NatureSupport $natureSupport = null): void
{
$this->editeur = $natureSupport;
}
/**
* Get natureSupport.
*
* @return NatureSupport|null
*/
public function getNatureSupport(): ?NatureSupport
{
return $this->natureSupport;
}
/**
* Add categorieOeuvre.
*
* @param CategorieOeuvre $categorieOeuvre
*/
public function addCategorieOeuvre(CategorieOeuvre $categorieOeuvre): void
{
if (!$this->categoriesOeuvres->contains($categorieOeuvre)) {
$this->categoriesOeuvres[] = $categorieOeuvre;
$categorieOeuvre-><API key>($this);
}
}
/**
* Remove categorieOeuvre.
*
* @param CategorieOeuvre $categorieOeuvre
*/
public function <API key>(CategorieOeuvre $categorieOeuvre): void
{
if ($this->categoriesOeuvres->contains($categorieOeuvre)) {
$this->categoriesOeuvres->removeElement($categorieOeuvre);
$categorieOeuvre-><API key>($this);
}
}
/**
* Get categoriesOeuvres.
*
* @return Collection
*/
public function <API key>(): Collection
{
return $this->categoriesOeuvres;
}
/**
* Add support.
*
* @param Support $support
*/
public function addSupport(Support $support): void
{
if (!$this->supports->contains($support)) {
$this->supports[] = $support;
}
$support-><API key>($this);
}
/**
* Remove support.
*
* @param Support $support
*/
public function removeSupport(Support $support): void
{
if ($this->supports->contains($support)) {
$this->supports->removeElement($support);
}
$support-><API key>(null);
}
/**
* Get supports.
*
* @return Collection
*/
public function getSupports(): Collection
{
return $this->supports;
}
}
|
package main
import (
"net/http"
"sync"
"time"
"github.com/1lann/airlift/airlift"
humanize "github.com/dustin/go-humanize"
"github.com/gin-gonic/contrib/renders/multitemplate"
"github.com/gin-gonic/contrib/sessions"
"github.com/gin-gonic/gin"
)
func formatBasicTime(t time.Time) string {
return getDay(t) + " " + t.Format("January 2006 at 3:04 PM")
}
func init() {
registers = append(registers, func(r *gin.RouterGroup, t multitemplate.Render) {
t.AddFromFiles("notes", viewsPath+"/notes.tmpl",
viewsPath+"/components/base.tmpl")
r.GET("/notes", viewUserNotes)
t.AddFromFiles("view-note", viewsPath+"/view-note.tmpl",
viewsPath+"/components/base.tmpl")
r.GET("/notes/:id", viewNote)
r.POST("/notes/:id/star", func(c *gin.Context) {
starred := c.PostForm("starred") == "true"
username := c.MustGet("user").(airlift.User).Username
err := airlift.SetNoteStar(c.Param("id"), username, starred)
if err != nil {
panic(err)
}
c.JSON(http.StatusOK, gin.H{"status": "ok"})
})
})
}
func viewNote(c *gin.Context) {
id := c.Param("id")
user := c.MustGet("user").(airlift.User)
note, err := airlift.GetFullNote(id, user.Username)
if err != nil {
panic(err)
}
if note.Title == "" {
c.HTML(http.StatusNotFound, "not-found", nil)
return
}
files := []fileCard{
{
Name: "Notes",
Size: humanize.Bytes(note.Size),
URL: "/download/notes/" + note.ID,
},
}
session := sessions.Default(c)
uploadFlashes := session.Flashes("upload")
uploadSuccess := ""
if len(uploadFlashes) > 0 {
uploadSuccess = uploadFlashes[0].(string)
}
session.Save()
htmlOK(c, "view-note", gin.H{
"ActiveMenu": "notes",
"Note": note,
"Files": files,
"IsUploader": note.Uploader == user.Username,
"UploadTime": formatBasicTime(note.UploadTime),
"UpdatedTime": formatBasicTime(note.UpdatedTime),
"UploadSuccess": uploadSuccess,
})
}
func viewUserNotes(c *gin.Context) {
user := c.MustGet("user").(airlift.User)
wg := new(sync.WaitGroup)
wg.Add(2)
var starred []airlift.Note
go func() {
defer func() {
wg.Done()
}()
var err error
starred, err = airlift.GetStarredNotes(user.Username)
if err != nil {
panic(err)
}
}()
var uploaded []airlift.Note
go func() {
defer func() {
wg.Done()
}()
var err error
uploaded, err = airlift.GetUploadedNotes(user.Username)
if err != nil {
panic(err)
}
}()
deleted := false
session := sessions.Default(c)
uploadFlashes := session.Flashes("upload")
if len(uploadFlashes) > 0 && uploadFlashes[0] == "delete" {
deleted = true
}
session.Save()
wg.Wait()
htmlOK(c, "notes", gin.H{
"ActiveMenu": "notes",
"Starred": starred,
"Uploaded": uploaded,
"Deleted": deleted,
})
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.