code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 4
991
| language
stringclasses 9
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace XamarinFormsHello.WinPhone
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage
{
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
LoadApplication(new XamarinFormsHello.App());
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached.
/// This parameter is typically used to configure the page.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
// TODO: Prepare page for display here.
// TODO: If your application contains multiple pages, ensure that you are
// handling the hardware Back button by registering for the
// Windows.Phone.UI.Input.HardwareButtons.BackPressed event.
// If you are using the NavigationHelper provided by some templates,
// this event is handled for you.
}
}
}
|
xamarin-samples/XamarinFormsHello
|
XamarinFormsHello/XamarinFormsHello.WinPhone/MainPage.xaml.cs
|
C#
|
mit
| 1,557 |
<?php
namespace LeadCommerce\Shopware\SDK\Query;
use LeadCommerce\Shopware\SDK\Util\Constants;
/**
* Class CustomerQuery
*
* @author Alexander Mahrt <amahrt@leadcommerce.de>
* @copyright 2016 LeadCommerce <amahrt@leadcommerce.de>
*/
class CustomerQuery extends Base
{
/**
* @var array
*/
protected $methodsAllowed = [
Constants::METHOD_CREATE,
Constants::METHOD_GET,
Constants::METHOD_GET_BATCH,
Constants::METHOD_UPDATE,
Constants::METHOD_DELETE,
];
/**
* @return mixed
*/
protected function getClass()
{
return 'LeadCommerce\\Shopware\\SDK\\Entity\\Customer';
}
/**
* Gets the query path to look for entities.
* E.G: 'variants' or 'articles'
*
* @return string
*/
protected function getQueryPath()
{
return 'customers';
}
}
|
LeadCommerceDE/shopware-sdk
|
src/LeadCommerce/Shopware/SDK/Query/CustomerQuery.php
|
PHP
|
mit
| 881 |
<?php
namespace GFire\InvoiceBundle\Entity\Interfaces;
interface InvoiceInterface{
}
|
jerickduguran/gfirev2
|
src/GFire/InvoiceBundle/Entity/Interfaces/InvoiceInterface.php
|
PHP
|
mit
| 87 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package test.thread;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Administrator
*/
public class CallableAndFutureTest {
private final ExecutorService executor = Executors.newFixedThreadPool(2);
void start() throws Exception {
final Callable<List<Integer>> task = new Callable<List<Integer>>() {
public List<Integer> call() throws Exception {
// get obj
final List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < 100; i++) {
Thread.sleep(50);
list.add(i);
}
return list;
}
};
final Future<List<Integer>> future = executor.submit(task);
//do sthing others..
//example: due to show some data..
try {
final List<Integer> list = future.get(); //这个函数还可以接受超时检测http://www.javaeye.com/topic/671314
System.out.println(list);
} catch (final InterruptedException ex) {
Logger.getLogger(CallableAndFutureTest.class.getName()).log(Level.SEVERE, null, ex);
future.cancel(true);
} catch (final ExecutionException ex) {
Logger.getLogger(CallableAndFutureTest.class.getName()).log(Level.SEVERE, null, ex);
throw new ExecutionException(ex);
} finally {
executor.shutdown();
}
}
public static void main(final String args[]) {
try {
new CallableAndFutureTest().start();
} catch (final Exception ex) {
Logger.getLogger(CallableAndFutureTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
|
atealxt/work-workspaces
|
Test_Java/src/test/thread/CallableAndFutureTest.java
|
Java
|
mit
| 2,091 |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
/// <summary>
/// The interface IWorkbookFunctionsCumPrincRequestBuilder.
/// </summary>
public partial interface IWorkbookFunctionsCumPrincRequestBuilder
{
/// <summary>
/// Builds the request.
/// </summary>
/// <param name="options">The query and header options for the request.</param>
/// <returns>The built request.</returns>
IWorkbookFunctionsCumPrincRequest Request(IEnumerable<Option> options = null);
}
}
|
garethj-msft/msgraph-sdk-dotnet
|
src/Microsoft.Graph/Requests/Generated/IWorkbookFunctionsCumPrincRequestBuilder.cs
|
C#
|
mit
| 997 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.eventhubs.generated;
import com.azure.core.util.Context;
/** Samples for ConsumerGroups ListByEventHub. */
public final class ConsumerGroupsListByEventHubSamples {
/*
* x-ms-original-file: specification/eventhub/resource-manager/Microsoft.EventHub/stable/2021-11-01/examples/ConsumerGroup/EHConsumerGroupListByEventHub.json
*/
/**
* Sample code: ConsumerGroupsListAll.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void consumerGroupsListAll(com.azure.resourcemanager.AzureResourceManager azure) {
azure
.eventHubs()
.manager()
.serviceClient()
.getConsumerGroups()
.listByEventHub("ArunMonocle", "sdk-Namespace-2661", "sdk-EventHub-6681", null, null, Context.NONE);
}
}
|
Azure/azure-sdk-for-java
|
sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/eventhubs/generated/ConsumerGroupsListByEventHubSamples.java
|
Java
|
mit
| 1,031 |
/** @jsx m */
import m from 'mithril';
import { linkTo, hrefTo } from '@storybook/addon-links';
const Main = {
view: vnode => (
<article
style={{
padding: 15,
lineHeight: 1.4,
fontFamily: '"Helvetica Neue", Helvetica, "Segoe UI", Arial, freesans, sans-serif',
backgroundColor: '#ffffff',
}}
>
{vnode.children}
</article>
),
};
const Title = {
view: vnode => <h1>{vnode.children}</h1>,
};
const Note = {
view: vnode => (
<p
style={{
opacity: 0.5,
}}
>
{vnode.children}
</p>
),
};
const InlineCode = {
view: vnode => (
<code
style={{
fontSize: 15,
fontWeight: 600,
padding: '2px 5px',
border: '1px solid #eae9e9',
borderRadius: 4,
backgroundColor: '#f3f2f2',
color: '#3a3a3a',
}}
>
{vnode.children}
</code>
),
};
const Link = {
view: vnode => (
<a
style={{
color: '#1474f3',
textDecoration: 'none',
borderBottom: '1px solid #1474f3',
paddingBottom: 2,
}}
{...vnode.attrs}
>
{vnode.children}
</a>
),
};
const NavButton = {
view: vnode => (
<button
type="button"
style={{
borderTop: 'none',
borderRight: 'none',
borderLeft: 'none',
backgroundColor: 'transparent',
padding: 0,
cursor: 'pointer',
font: 'inherit',
}}
{...vnode.attrs}
>
{vnode.children}
</button>
),
};
const StoryLink = {
oninit: vnode => {
// eslint-disable-next-line no-param-reassign
vnode.state.href = '/';
// eslint-disable-next-line no-param-reassign
vnode.state.onclick = () => {
linkTo(vnode.attrs.kind, vnode.attrs.story)();
return false;
};
StoryLink.updateHref(vnode);
},
updateHref: async vnode => {
const href = await hrefTo(vnode.attrs.kind, vnode.attrs.story);
// eslint-disable-next-line no-param-reassign
vnode.state.href = href;
m.redraw();
},
view: vnode => (
<a
href={vnode.state.href}
style={{
color: '#1474f3',
textDecoration: 'none',
borderBottom: '1px solid #1474f3',
paddingBottom: 2,
}}
onClick={vnode.state.onclick}
>
{vnode.children}
</a>
),
};
const Welcome = {
view: vnode => (
<Main>
<Title>Welcome to storybook</Title>
<p>This is a UI component dev environment for your app.</p>
<p>
We've added some basic stories inside the <InlineCode>src/stories</InlineCode> directory.
<br />A story is a single state of one or more UI components. You can have as many stories
as you want.
<br />
(Basically a story is like a visual test case.)
</p>
<p>
See these sample
{vnode.attrs.showApp ? (
<NavButton onclick={vnode.attrs.showApp}>stories</NavButton>
) : (
<StoryLink kind={vnode.attrs.showKind} story={vnode.attrs.showStory}>
stories
</StoryLink>
)}
for a component called <InlineCode>Button</InlineCode>.
</p>
<p>
Just like that, you can add your own components as stories.
<br />
You can also edit those components and see changes right away.
<br />
(Try editing the <InlineCode>Button</InlineCode> stories located at
<InlineCode>src/stories/1-Button.stories.js</InlineCode>
.)
</p>
<p>
Usually we create stories with smaller UI components in the app.
<br />
Have a look at the
<Link
href="https://storybook.js.org/basics/writing-stories"
target="_blank"
rel="noopener noreferrer"
>
Writing Stories
</Link>
section in our documentation.
</p>
<Note>
<b>NOTE:</b>
<br />
Have a look at the <InlineCode>.storybook/webpack.config.js</InlineCode> to add webpack
loaders and plugins you are using in this project.
</Note>
</Main>
),
};
export default Welcome;
|
storybooks/react-storybook
|
lib/cli/generators/MITHRIL/template-csf/stories/Welcome.js
|
JavaScript
|
mit
| 4,185 |
from simtk.openmm import app
import simtk.openmm as mm
from simtk import unit
def findForce(system, forcetype, add=True):
""" Finds a specific force in the system force list - added if not found."""
for force in system.getForces():
if isinstance(force, forcetype):
return force
if add==True:
system.addForce(forcetype())
return findForce(system, forcetype)
return None
def setGlobalForceParameter(force, key, value):
for i in range(force.getNumGlobalParameters()):
if force.getGlobalParameterName(i)==key:
print('setting force parameter', key, '=', value)
force.setGlobalParameterDefaultValue(i, value);
def atomIndexInResidue(residue):
""" list of atom index in residue """
index=[]
for a in list(residue.atoms()):
index.append(a.index)
return index
def getResiduePositions(residue, positions):
""" Returns array w. atomic positions of residue """
ndx = atomIndexInResidue(residue)
return np.array(positions)[ndx]
def uniquePairs(index):
""" list of unique, internal pairs """
return list(combinations( range(index[0],index[-1]+1),2 ) )
def addHarmonicConstraint(harmonicforce, pairlist, positions, threshold, k):
""" add harmonic bonds between pairs if distance is smaller than threshold """
print('Constraint force constant =', k)
for i,j in pairlist:
distance = unit.norm( positions[i]-positions[j] )
if distance<threshold:
harmonicforce.addBond( i,j,
distance.value_in_unit(unit.nanometer),
k.value_in_unit( unit.kilojoule/unit.nanometer**2/unit.mole ))
print("added harmonic bond between", i, j, 'with distance',distance)
def addExclusions(nonbondedforce, pairlist):
""" add nonbonded exclusions between pairs """
for i,j in pairlist:
nonbondedforce.addExclusion(i,j)
def rigidifyResidue(residue, harmonicforce, positions, nonbondedforce=None,
threshold=6.0*unit.angstrom, k=2500*unit.kilojoule/unit.nanometer**2/unit.mole):
""" make residue rigid by adding constraints and nonbonded exclusions """
index = atomIndexInResidue(residue)
pairlist = uniquePairs(index)
addHarmonicConstraint(harmonic, pairlist, pdb.positions, threshold, k)
if nonbondedforce is not None:
for i,j in pairlist:
print('added nonbonded exclusion between', i, j)
nonbonded.addExclusion(i,j)
|
mlund/pyha
|
pyha/openmm.py
|
Python
|
mit
| 2,333 |
namespace InControl
{
using System;
// @cond nodoc
[AutoDiscover]
public class EightBitdoSNES30AndroidProfile : UnityInputDeviceProfile
{
public EightBitdoSNES30AndroidProfile()
{
Name = "8Bitdo SNES30 Controller";
Meta = "8Bitdo SNES30 Controller on Android";
// Link = "https://www.amazon.com/Wireless-Bluetooth-Controller-Classic-Joystick/dp/B014QP2H1E";
DeviceClass = InputDeviceClass.Controller;
DeviceStyle = InputDeviceStyle.NintendoSNES;
IncludePlatforms = new[] {
"Android"
};
JoystickNames = new[] {
"8Bitdo SNES30 GamePad",
};
ButtonMappings = new[] {
new InputControlMapping {
Handle = "A",
Target = InputControlType.Action2,
Source = Button( 0 ),
},
new InputControlMapping {
Handle = "B",
Target = InputControlType.Action1,
Source = Button( 1 ),
},
new InputControlMapping {
Handle = "X",
Target = InputControlType.Action4,
Source = Button( 2 ),
},
new InputControlMapping {
Handle = "Y",
Target = InputControlType.Action3,
Source = Button( 3 ),
},
new InputControlMapping {
Handle = "L",
Target = InputControlType.LeftBumper,
Source = Button( 4 ),
},
new InputControlMapping {
Handle = "R",
Target = InputControlType.RightBumper,
Source = Button( 5 ),
},
new InputControlMapping {
Handle = "Select",
Target = InputControlType.Select,
Source = Button( 11 ),
},
new InputControlMapping {
Handle = "Start",
Target = InputControlType.Start,
Source = Button( 10 ),
},
};
AnalogMappings = new[] {
new InputControlMapping {
Handle = "DPad Left",
Target = InputControlType.DPadLeft,
Source = Analog( 0 ),
SourceRange = InputRange.ZeroToMinusOne,
TargetRange = InputRange.ZeroToOne,
},
new InputControlMapping {
Handle = "DPad Right",
Target = InputControlType.DPadRight,
Source = Analog( 0 ),
SourceRange = InputRange.ZeroToOne,
TargetRange = InputRange.ZeroToOne,
},
new InputControlMapping {
Handle = "DPad Up",
Target = InputControlType.DPadUp,
Source = Analog( 1 ),
SourceRange = InputRange.ZeroToMinusOne,
TargetRange = InputRange.ZeroToOne,
},
new InputControlMapping {
Handle = "DPad Down",
Target = InputControlType.DPadDown,
Source = Analog( 1 ),
SourceRange = InputRange.ZeroToOne,
TargetRange = InputRange.ZeroToOne,
},
};
}
}
// @endcond
}
|
benthroop/Frankenweapon
|
Assets/InControl/Source/Unity/DeviceProfiles/EightBitdoSNES30AndroidProfile.cs
|
C#
|
mit
| 2,543 |
package context
import (
"github.com/Everlane/evan/common"
"github.com/satori/go.uuid"
)
// Stores state relating to a deployment.
type Deployment struct {
uuid uuid.UUID
application common.Application
environment string
strategy common.Strategy
ref string
sha1 string
flags map[string]interface{}
store common.Store
// Internal state
currentState common.DeploymentState
currentPhase common.Phase
lastError error
}
// Create a deployment for the given application to an environment.
func NewDeployment(app common.Application, environment string, strategy common.Strategy, ref string, flags map[string]interface{}) *Deployment {
return &Deployment{
uuid: uuid.NewV1(),
application: app,
environment: environment,
strategy: strategy,
ref: ref,
flags: flags,
currentState: common.DEPLOYMENT_PENDING,
}
}
func NewBareDeployment() *Deployment {
return &Deployment{
flags: make(map[string]interface{}),
}
}
func (deployment *Deployment) UUID() uuid.UUID {
return deployment.uuid
}
func (deployment *Deployment) Application() common.Application {
return deployment.application
}
func (deployment *Deployment) Environment() string {
return deployment.environment
}
func (deployment *Deployment) Strategy() common.Strategy {
return deployment.strategy
}
func (deployment *Deployment) Ref() string {
return deployment.ref
}
func (deployment *Deployment) SHA1() string {
return deployment.sha1
}
func (deployment *Deployment) SetSHA1(sha1 string) {
deployment.sha1 = sha1
}
func (deployment *Deployment) MostPreciseRef() string {
if deployment.sha1 != "" {
return deployment.sha1
} else {
return deployment.ref
}
}
func (deployment *Deployment) SetStoreAndSave(store common.Store) error {
deployment.store = store
return store.SaveDeployment(deployment)
}
// Will panic if it is unable to save. This will be called *after*
// `SetStoreAndSave` should have been called, so we're assuming that if that
// worked then this should also work.
func (deployment *Deployment) setStateAndSave(state common.DeploymentState) {
deployment.currentState = state
err := deployment.store.SaveDeployment(deployment)
if err != nil {
panic(err)
}
}
func (deployment *Deployment) Flags() map[string]interface{} {
return deployment.flags
}
func (deployment *Deployment) HasFlag(key string) bool {
_, present := deployment.flags[key]
return present
}
func (deployment *Deployment) Flag(key string) interface{} {
return deployment.flags[key]
}
func (deployment *Deployment) SetFlag(key string, value interface{}) {
deployment.flags[key] = value
}
// Looks for the "force" boolean in the `flags`.
func (deployment *Deployment) IsForce() bool {
if force, ok := deployment.Flag("force").(bool); ok {
return force
} else {
return false
}
}
func (deployment *Deployment) Status() common.DeploymentStatus {
var phase common.Phase
if deployment.currentState == common.RUNNING_PHASE {
phase = deployment.currentPhase
}
return common.DeploymentStatus{
State: deployment.currentState,
Phase: phase,
Error: nil,
}
}
func (deployment *Deployment) CheckPreconditions() error {
deployment.setStateAndSave(common.RUNNING_PRECONDITIONS)
preconditions := deployment.strategy.Preconditions()
for _, precondition := range preconditions {
err := precondition.Status(deployment)
if err != nil {
return err
}
}
return nil
}
// Internal implementation of running phases. Manages setting
// `deployment.currentPhase` to the phase currently executing.
func (deployment *Deployment) runPhases(preloadResults PreloadResults) error {
phases := deployment.strategy.Phases()
for _, phase := range phases {
deployment.currentPhase = phase
preloadResult := preloadResults.Get(phase)
err := phase.Execute(deployment, preloadResult)
if err != nil {
return err
}
}
return nil
}
// Runs all the phases configured in the `Strategy`. Sets `currentState` and
// `currentPhase` fields as appropriate. If an error occurs it will also set
// the `lastError` field to that error.
func (deployment *Deployment) RunPhases() error {
results, err := deployment.RunPhasePreloads()
if err != nil {
deployment.lastError = err
deployment.setStateAndSave(common.DEPLOYMENT_ERROR)
return err
}
deployment.setStateAndSave(common.RUNNING_PHASE)
err = deployment.runPhases(results)
if err != nil {
deployment.lastError = err
deployment.setStateAndSave(common.DEPLOYMENT_ERROR)
return err
} else {
deployment.setStateAndSave(common.DEPLOYMENT_DONE)
return nil
}
}
type preloadResult struct {
data interface{}
err error
}
type PreloadResults map[common.Phase]interface{}
func (results PreloadResults) Get(phase common.Phase) interface{} {
return results[phase]
}
func (results PreloadResults) Set(phase common.Phase, data interface{}) {
results[phase] = data
}
// Phases can expose preloads to gather any additional information they may
// need before executing. This will run those preloads in parallel.
func (deployment *Deployment) RunPhasePreloads() (PreloadResults, error) {
preloadablePhases := make([]common.PreloadablePhase, 0)
for _, phase := range deployment.strategy.Phases() {
if phase.CanPreload() {
preloadablePhases = append(preloadablePhases, phase.(common.PreloadablePhase))
}
}
resultChan := make(chan preloadResult)
for _, phase := range preloadablePhases {
go func() {
data, err := phase.Preload(deployment)
resultChan <- preloadResult{data: data, err: err}
}()
}
results := make(PreloadResults)
for _, phase := range preloadablePhases {
result := <-resultChan
if result.err != nil {
return nil, result.err
} else {
results.Set(phase.(common.Phase), result.data)
}
}
return results, nil
}
|
Everlane/evan
|
context/deployment.go
|
GO
|
mit
| 5,804 |
window.Lunchiatto.module('Transfer', function(Transfer, App, Backbone, Marionette, $, _) {
return Transfer.Layout = Marionette.LayoutView.extend({
template: 'transfers/layout',
ui: {
receivedTransfers: '.received-transfers',
submittedTransfers: '.submitted-transfers'
},
behaviors: {
Animateable: {
types: ['fadeIn']
},
Titleable: {}
},
regions: {
receivedTransfers: '@ui.receivedTransfers',
submittedTransfers: '@ui.submittedTransfers'
},
onRender() {
this._showTransfers('received');
this._showTransfers('submitted');
},
_showTransfers(type) {
const transfers = new App.Entities.Transfers([], {type});
transfers.optionedFetch({
success: transfers => {
App.getUsers().then(() => {
const view = new App.Transfer.List({
collection: transfers});
this[`${type}Transfers`].show(view);
});
}
});
},
_htmlTitle() {
return 'Transfers';
}
});
});
|
lunchiatto/web
|
app/assets/javascripts/modules/transfer/views/layout.js
|
JavaScript
|
mit
| 1,061 |
package analytics
import (
"fmt"
elastic "gopkg.in/olivere/elastic.v3"
)
//Elasticsearch stores configuration related to the AWS elastic cache isntance.
type Elasticsearch struct {
URL string
IndexName string
DocType string
client *elastic.Client
}
//Initialize initializes the analytics engine.
func (e *Elasticsearch) Initialize() error {
client, err := elastic.NewSimpleClient(elastic.SetURL(e.URL))
if err != nil {
return err
}
e.client = client
s := e.client.IndexExists(e.IndexName)
exists, err := s.Do()
if err != nil {
return err
}
if !exists {
s := e.client.CreateIndex(e.IndexName)
_, err := s.Do()
if err != nil {
return err
}
}
return nil
}
//SendAnalytics is used to send the data to the analytics engine.
func (e *Elasticsearch) SendAnalytics(data string) error {
fmt.Println(data)
_, err := e.client.Index().Index(e.IndexName).Type(e.DocType).BodyJson(data).Do()
if err != nil {
return err
}
return nil
}
|
awkhan/go-utility
|
analytics/elasticsearch.go
|
GO
|
mit
| 979 |
'use strict';
var i18n = require('./i18n.js')
i18n.add_translation("pt-BR", {
test: 'OK',
greetings: {
hello: 'Olá',
welcome: 'Bem vindo'
}
});
i18n.locale = 'pt-BR';
console.log(i18n.t('greetings.hello'));
console.log(i18n.t('greetings.welcome'));
console.log("Hallo");
// Example 2
i18n.add_translation("pt-BR", {
greetings: {
hello: 'Olá',
welcome: 'Bem vindo'
}
});
console.log(i18n.t('greetings.hello'));
i18n.add_translation("pt-BR", {
test: 'OK',
greetings: {
hello: 'Oi',
bye: 'Tchau'
}
});
console.log(i18n.t('greetings.hello'));
console.log(i18n.t('test'));
|
felipediesel/simple-i18n
|
node.js
|
JavaScript
|
mit
| 617 |
/**
* @flow
*/
/* eslint-disable */
'use strict';
/*::
import type { ReaderFragment } from 'relay-runtime';
export type ReactionContent = "CONFUSED" | "EYES" | "HEART" | "HOORAY" | "LAUGH" | "ROCKET" | "THUMBS_DOWN" | "THUMBS_UP" | "%future added value";
import type { FragmentReference } from "relay-runtime";
declare export opaque type emojiReactionsView_reactable$ref: FragmentReference;
declare export opaque type emojiReactionsView_reactable$fragmentType: emojiReactionsView_reactable$ref;
export type emojiReactionsView_reactable = {|
+id: string,
+reactionGroups: ?$ReadOnlyArray<{|
+content: ReactionContent,
+viewerHasReacted: boolean,
+users: {|
+totalCount: number
|},
|}>,
+viewerCanReact: boolean,
+$refType: emojiReactionsView_reactable$ref,
|};
export type emojiReactionsView_reactable$data = emojiReactionsView_reactable;
export type emojiReactionsView_reactable$key = {
+$data?: emojiReactionsView_reactable$data,
+$fragmentRefs: emojiReactionsView_reactable$ref,
};
*/
const node/*: ReaderFragment*/ = {
"kind": "Fragment",
"name": "emojiReactionsView_reactable",
"type": "Reactable",
"metadata": null,
"argumentDefinitions": [],
"selections": [
{
"kind": "ScalarField",
"alias": null,
"name": "id",
"args": null,
"storageKey": null
},
{
"kind": "LinkedField",
"alias": null,
"name": "reactionGroups",
"storageKey": null,
"args": null,
"concreteType": "ReactionGroup",
"plural": true,
"selections": [
{
"kind": "ScalarField",
"alias": null,
"name": "content",
"args": null,
"storageKey": null
},
{
"kind": "ScalarField",
"alias": null,
"name": "viewerHasReacted",
"args": null,
"storageKey": null
},
{
"kind": "LinkedField",
"alias": null,
"name": "users",
"storageKey": null,
"args": null,
"concreteType": "ReactingUserConnection",
"plural": false,
"selections": [
{
"kind": "ScalarField",
"alias": null,
"name": "totalCount",
"args": null,
"storageKey": null
}
]
}
]
},
{
"kind": "ScalarField",
"alias": null,
"name": "viewerCanReact",
"args": null,
"storageKey": null
}
]
};
// prettier-ignore
(node/*: any*/).hash = 'fde156007f42d841401632fce79875d5';
module.exports = node;
|
atom/github
|
lib/views/__generated__/emojiReactionsView_reactable.graphql.js
|
JavaScript
|
mit
| 2,624 |
require 'bio-ucsc'
describe "Bio::Ucsc::Hg19::WgEncodeAffyRnaChipFiltTransfragsKeratinocyteCytosolLongnonpolya" do
describe "#find_by_interval" do
context "given range chr1:1-100,000" do
it "returns an array of results" do
Bio::Ucsc::Hg19::DBConnection.default
Bio::Ucsc::Hg19::DBConnection.connect
i = Bio::GenomicInterval.parse("chr1:1-100,000")
r = Bio::Ucsc::Hg19::WgEncodeAffyRnaChipFiltTransfragsKeratinocyteCytosolLongnonpolya.find_all_by_interval(i)
r.should have(1).items
end
it "returns an array of results with column accessors" do
Bio::Ucsc::Hg19::DBConnection.default
Bio::Ucsc::Hg19::DBConnection.connect
i = Bio::GenomicInterval.parse("chr1:1-100,000")
r = Bio::Ucsc::Hg19::WgEncodeAffyRnaChipFiltTransfragsKeratinocyteCytosolLongnonpolya.find_by_interval(i)
r.chrom.should == "chr1"
end
end
end
end
|
misshie/bioruby-ucsc-api
|
spec/hg19/wgencodeaffyrnachipfilttransfragskeratinocytecytosollongnonpolya_spec.rb
|
Ruby
|
mit
| 935 |
require File.expand_path("../../../test_helper", __FILE__)
describe Redcarpet::Render::HTMLAbbreviations do
before do
@renderer = Class.new do
include Redcarpet::Render::HTMLAbbreviations
end
end
describe "#preprocess" do
it "converts markdown abbrevations to HTML" do
markdown = <<-EOS.strip_heredoc
YOLO
*[YOLO]: You Only Live Once
EOS
@renderer.new.preprocess(markdown).must_equal <<-EOS.strip_heredoc.chomp
<abbr title="You Only Live Once">YOLO</abbr>
EOS
end
it "converts hyphenated abbrevations to HTML" do
markdown = <<-EOS.strip_heredoc
JSON-P
*[JSON-P]: JSON with Padding
EOS
@renderer.new.preprocess(markdown).must_equal <<-EOS.strip_heredoc.chomp
<abbr title="JSON with Padding">JSON-P</abbr>
EOS
end
it "converts abbrevations with numbers to HTML" do
markdown = <<-EOS.strip_heredoc
ES6
*[ES6]: ECMAScript 6
EOS
@renderer.new.preprocess(markdown).must_equal <<-EOS.strip_heredoc.chomp
<abbr title="ECMAScript 6">ES6</abbr>
EOS
end
end
describe "#acronym_regexp" do
it "matches an acronym at the beginning of a line" do
"FOO bar".must_match @renderer.new.acronym_regexp("FOO")
end
it "matches an acronym at the end of a line" do
"bar FOO".must_match @renderer.new.acronym_regexp("FOO")
end
it "matches an acronym next to punctuation" do
".FOO.".must_match @renderer.new.acronym_regexp("FOO")
end
it "matches an acronym with hyphens" do
"JSON-P".must_match @renderer.new.acronym_regexp("JSON-P")
end
it "doesn't match an acronym in the middle of a word" do
"YOLOFOOYOLO".wont_match @renderer.new.acronym_regexp("FOO")
end
it "matches numbers" do
"ES6".must_match @renderer.new.acronym_regexp("ES6")
end
end
end
|
brandonweiss/redcarpet-abbreviations
|
test/redcarpet/render/html_abbreviations_test.rb
|
Ruby
|
mit
| 1,921 |
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateList extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('modelList', function(Blueprint $table)
{
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('modelList');
}
}
|
paufsc/Kanban
|
web/app/database/migrations/2014_10_24_214547_create_list.php
|
PHP
|
mit
| 488 |
module Tire
module Model
module Persistence
# Provides infrastructure for storing records in _Elasticsearch_.
#
module Storage
def self.included(base)
base.class_eval do
extend ClassMethods
include InstanceMethods
end
end
module ClassMethods
def create(args={})
document = new(args)
return false unless document.valid?
if result = document.save
document
else
result
end
end
end
module InstanceMethods
def update_attribute(name, value)
__update_attributes name => value
save
end
def update_attributes(attributes={})
__update_attributes attributes
save
end
def update_index
run_callbacks :update_elasticsearch_index do
if destroyed?
response = index.remove self
else
if response = index.store( self, {:percolate => percolator} )
self.id ||= response['_id']
self._index = response['_index']
self._type = response['_type']
self._version = response['_version']
self.matches = response['matches']
end
end
response
end
end
def save
return false unless valid?
run_callbacks :save do
response = update_index
!! response['ok']
end
end
def destroy
run_callbacks :destroy do
@destroyed = true
response = update_index
! response.nil?
end
end
def destroyed? ; !!@destroyed; end
def persisted? ; !!id && !!_version; end
def new_record? ; !persisted?; end
end
end
end
end
end
|
HenleyChiu/tire
|
lib/tire/model/persistence/storage.rb
|
Ruby
|
mit
| 2,068 |
require 'googleanalytics/mobile'
|
mono0x/googleanalytics-mobile
|
lib/googleanalytics-mobile.rb
|
Ruby
|
mit
| 33 |
class ItemsController < ApplicationController
def create
item = Item.new(item_params)
item.user_id = @user.id
if item.save
render json: item, status: 201
else
render json: item.errors, status: 422
end
end
def destroy
item = find_item
item.destroy
head 204
end
def index
render json: @user.items.as_json, status: 200
end
def show
item = find_item
render json: item.as_json, status: 200
end
def update
item = find_item
if item.update(item_params)
render json: item.as_json, status: 200
end
end
def find_item
Item.find(params[:id])
end
private
def item_params
params.require(:item).permit(:type, :brand, :size, :color, :description)
end
end
|
StuartPearlman/ClosetKeeperAPI
|
app/controllers/items_controller.rb
|
Ruby
|
mit
| 701 |
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class Killer : MonoBehaviour {
public Transform RobotPlayer;
public GameObject Robot;
public Text GameOVER;
// Use this for initialization
void Start() {
RobotPlayer = GetComponent<Transform>();
}
void FixedUpdate()
{
if(RobotPlayer.gameObject.transform.position.y < -2)
{
GameOVER.gameObject.SetActive(true);
}
}
}
|
ArcherSys/ArcherSys
|
C#/Unity/Capital Pursuit Alpha/Assets/Scripts/Killer.cs
|
C#
|
mit
| 487 |
module Linter
class Base
def self.can_lint?(filename)
self::FILE_REGEXP === filename
end
def initialize(hound_config:, build:, repository_owner_name:)
@hound_config = hound_config
@build = build
@repository_owner_name = repository_owner_name
end
def file_review(commit_file)
attributes = build_review_job_attributes(commit_file)
file_review = FileReview.create!(
build: build,
filename: commit_file.filename,
)
enqueue_job(attributes)
file_review
end
def enabled?
config.linter_names.any? do |linter_name|
hound_config.enabled_for?(linter_name)
end
end
def file_included?(*)
true
end
def name
self.class.name.demodulize.underscore
end
private
attr_reader :hound_config, :build, :repository_owner_name
def build_review_job_attributes(commit_file)
{
commit_sha: build.commit_sha,
config: config.content,
content: commit_file.content,
filename: commit_file.filename,
patch: commit_file.patch,
pull_request_number: build.pull_request_number,
}
end
def enqueue_job(attributes)
Resque.enqueue(job_class, attributes)
end
def job_class
"#{name.classify}ReviewJob".constantize
end
def config
@config ||= ConfigBuilder.for(hound_config, name)
end
end
end
|
Koronen/hound
|
app/models/linter/base.rb
|
Ruby
|
mit
| 1,430 |
(function() {
'use strict';
angular
.module('app.match')
.run(appRun);
appRun.$inject = ['routerHelper'];
/* @ngInject */
function appRun(routerHelper) {
routerHelper.configureStates(getStates());
}
function getStates() {
return [{
state: 'match',
config: {
url: '/match/:id',
templateUrl: 'app/match/match.html',
controller: 'MatchController',
controllerAs: 'vm',
title: 'Match',
settings: {
nav: 2,
content: '<i class="fa fa-lock"></i> Match'
}
}
}];
}
})();
|
otaviosoares/f2f
|
src/client/app/match/match.route.js
|
JavaScript
|
mit
| 593 |
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-docu',
templateUrl: './docu.component.html',
styleUrls: ['./docu.component.scss']
})
export class DocuComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
|
TeoGia/http-on-fire
|
src/app/docu/docu.component.ts
|
TypeScript
|
mit
| 262 |
class Portal::CollaborationPolicy < ApplicationPolicy
end
|
concord-consortium/rigse
|
rails/app/policies/portal/collaboration_policy.rb
|
Ruby
|
mit
| 58 |
import { DOCUMENT } from '@angular/common';
import { ApplicationRef, ComponentFactoryResolver, Inject, Injectable, Injector } from '@angular/core';
import { BaseService } from 'ngx-weui/core';
import { ToptipsComponent, ToptipsType } from './toptips.component';
@Injectable({ providedIn: 'root' })
export class ToptipsService extends BaseService {
constructor(
protected readonly resolver: ComponentFactoryResolver,
protected readonly applicationRef: ApplicationRef,
protected readonly injector: Injector,
@Inject(DOCUMENT) protected readonly doc: any,
) {
super();
}
/**
* 构建一个Toptips并显示
*
* @param text 文本
* @param type 类型
* @param 显示时长后自动关闭(单位:ms)
*/
show(text: string, type: ToptipsType, time: number = 2000): ToptipsComponent {
const componentRef = this.build(ToptipsComponent);
if (type) {
componentRef.instance.type = type;
}
if (text) {
componentRef.instance.text = text;
}
componentRef.instance.time = time;
componentRef.instance.hide.subscribe(() => {
setTimeout(() => {
this.destroy(componentRef);
}, 100);
});
return componentRef.instance.onShow();
}
/**
* 构建一个Warn Toptips并显示
*
* @param text 文本
* @param time 显示时长后自动关闭(单位:ms)
*/
warn(text: string, time: number = 2000): ToptipsComponent {
return this.show(text, 'warn', time);
}
/**
* 构建一个Info Toptips并显示
*
* @param text 文本
* @param time 显示时长后自动关闭(单位:ms)
*/
info(text: string, time: number = 2000): ToptipsComponent {
return this.show(text, 'info', time);
}
/**
* 构建一个Primary Toptips并显示
*
* @param text 文本
* @param time 显示时长后自动关闭(单位:ms)
*/
primary(text: string, time: number = 2000): ToptipsComponent {
return this.show(text, 'primary', time);
}
/**
* 构建一个Success Toptips并显示
*
* @param text 文本
* @param time 显示时长后自动关闭(单位:ms)
*/
success(text: string, time: number = 2000): ToptipsComponent {
return this.show(text, 'primary', time);
}
/**
* 构建一个Default Toptips并显示
*
* @param text 文本
* @param time 显示时长后自动关闭(单位:ms)
*/
default(text: string, time: number = 2000): ToptipsComponent {
return this.show(text, 'default', time);
}
}
|
cipchk/ngx-weui
|
components/toptips/toptips.service.ts
|
TypeScript
|
mit
| 2,518 |
require 'test_helper'
class QuestionSubjectiveTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
|
Glastonbury/snusurvey
|
test/models/question_subjective_test.rb
|
Ruby
|
mit
| 132 |
var loadJsons = require('../lib/loadJsons');
describe("Get a recursive directory load of JSONs", function() {
var data;
beforeEach(function(done) {
if(data) done();
else {
loadJsons("./specs")(function(d) {
data = d;
done();
});
}
});
it("Should return right number of jsons", function() {
expect(data.length).toBe(6);
});
it("Should have a @type field on all objects", function() {
data.forEach(function(d) {
expect(d['@type']).toBeDefined();
});
});
});
|
polidore/dfg
|
specs/fileBased.spec.js
|
JavaScript
|
mit
| 531 |
using System;
using System.Diagnostics;
using System.Text;
namespace BgeniiusUniversity.Logging
{
public class Logger : ILogger
{
public void Information(string message)
{
Trace.TraceInformation(message);
}
public void Information(string fmt, params object[] vars)
{
Trace.TraceInformation(fmt, vars);
}
public void Information(Exception exception, string fmt, params object[] vars)
{
Trace.TraceInformation(FormatExceptionMessage(exception, fmt, vars));
}
public void Warning(string message)
{
Trace.TraceWarning(message);
}
public void Warning(string fmt, params object[] vars)
{
Trace.TraceWarning(fmt, vars);
}
public void Warning(Exception exception, string fmt, params object[] vars)
{
Trace.TraceWarning(FormatExceptionMessage(exception, fmt, vars));
}
public void Error(string message)
{
Trace.TraceError(message);
}
public void Error(string fmt, params object[] vars)
{
Trace.TraceError(fmt, vars);
}
public void Error(Exception exception, string fmt, params object[] vars)
{
Trace.TraceError(FormatExceptionMessage(exception, fmt, vars));
}
public void TraceApi(string componentName, string method, TimeSpan timespan)
{
TraceApi(componentName, method, timespan, "");
}
public void TraceApi(string componentName, string method, TimeSpan timespan, string fmt, params object[] vars)
{
TraceApi(componentName, method, timespan, string.Format(fmt, vars));
}
public void TraceApi(string componentName, string method, TimeSpan timespan, string properties)
{
string message = String.Concat("Component:", componentName, ";Method:", method, ";Timespan:", timespan.ToString(), ";Properties:", properties);
Trace.TraceInformation(message);
}
private static string FormatExceptionMessage(Exception exception, string fmt, object[] vars)
{
// Simple exception formatting: for a more comprehensive version see
// http://code.msdn.microsoft.com/windowsazure/Fix-It-app-for-Building-cdd80df4
var sb = new StringBuilder();
sb.Append(string.Format(fmt, vars));
sb.Append(" Exception: ");
sb.Append(exception.ToString());
return sb.ToString();
}
}
}
|
bgeniius/bgUniversity
|
ContosoUniversity/Logging/Logger.cs
|
C#
|
mit
| 2,619 |
<?php
/**
* Rule for required elements
*
* PHP version 5
*
* LICENSE:
*
* Copyright (c) 2006-2010, Alexey Borzov <avb@php.net>,
* Bertrand Mansion <golgote@mamasam.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The names of the authors may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @category HTML
* @package HTML_QuickForm2
* @author Alexey Borzov <avb@php.net>
* @author Bertrand Mansion <golgote@mamasam.com>
* @license http://opensource.org/licenses/bsd-license.php New BSD License
* @version SVN: $Id: Required.php 294057 2010-01-26 21:10:28Z avb $
* @link http://pear.php.net/package/HTML_QuickForm2
*/
/**
* Rule checking that the form field is not empty
*/
require_once 'HTML/QuickForm2/Rule/Nonempty.php';
/**
* Rule for required elements
*
* The main difference from "nonempty" Rule is that
* - elements to which this Rule is attached will be considered required
* ({@link HTML_QuickForm2_Node::isRequired()} will return true for them) and
* marked accordingly when outputting the form
* - this Rule can only be added directly to the element and other Rules can
* only be added to it via and_() method
*
* @category HTML
* @package HTML_QuickForm2
* @author Alexey Borzov <avb@php.net>
* @author Bertrand Mansion <golgote@mamasam.com>
* @version Release: 0.4.0
*/
class HTML_QuickForm2_Rule_Required extends HTML_QuickForm2_Rule_Nonempty
{
/**
* Disallows adding a rule to the chain with an "or" operator
*
* Required rules are different from all others because they affect the
* visual representation of an element ("* denotes required field").
* Therefore we cannot allow chaining other rules to these via or_(), since
* this will effectively mean that the field is not required anymore and the
* visual difference is bogus.
*
* @param HTML_QuickForm2_Rule
* @throws HTML_QuickForm2_Exception
*/
public function or_(HTML_QuickForm2_Rule $next)
{
throw new HTML_QuickForm2_Exception(
'or_(): Cannot add a rule to "required" rule'
);
}
}
?>
|
N3X15/ATBBS-Plus
|
includes/3rdParty/HTML/QuickForm2/Rule/Required.php
|
PHP
|
mit
| 3,540 |
class String
def split_on_unescaped(str)
self.split(/\s*(?<!\\)#{str}\s*/).map{|s| s.gsub(/\\(?=#{str})/, '') }
end
end
|
rubysuperhero/hero-notes
|
lib/clitasks/split_on_unescaped.rb
|
Ruby
|
mit
| 128 |
import axios from 'axios';
import { updateRadius } from './radius-reducer';
import { AddBType } from './b-type-reducer';
// import { create as createUser } from './users';
// import history from '../history';
/* ------------------ ACTIONS --------------------- */
const ADD_B_TYPE = 'ADD_B_TYPE';
const ADD_LNG_LAT = 'ADD_LNG_LAT';
const UPDATE_RADIUS = 'UPDATE_RADIUS';
const SWITCH_MEASUREMENT = 'SWITCH_MEASUREMENT';
/* -------------- ACTION CREATORS ----------------- */
export const addLngLat = (latitude, longitude) => ({
type: ADD_LNG_LAT,
latitude,
longitude
});
export const switchMeasurement = measurement => ({
type: SWITCH_MEASUREMENT,
measurement
});
/* ------------------ REDUCER --------------------- */
export default function reducer (state = {
latitude: null,
longitude: null,
radius: null,
businessType: null,
distanceMeasurement: 'miles'
}, action) {
switch (action.type) {
case ADD_B_TYPE:
state.businessType = action.typeStr;
break;
case ADD_LNG_LAT:
state.latitude = action.latitude;
state.longitude = action.longitude;
break;
case UPDATE_RADIUS:
state.radius = action.radInt;
break;
case SWITCH_MEASUREMENT:
state.distanceMeasurement = action.measurement;
break;
default:
return state;
}
return state;
}
|
Bullseyed/Bullseye
|
app/reducers/report.js
|
JavaScript
|
mit
| 1,361 |
module Softlayer
module User
class Customer
module Access
autoload :Authentication, 'softlayer/user/customer/access/authentication'
end
end
end
end
|
zertico/softlayer
|
lib/softlayer/user/customer/access.rb
|
Ruby
|
mit
| 180 |
(function (global, factory) {
if (typeof define === 'function' && define.amd) {
define(['exports', 'module', 'skatejs'], factory);
} else if (typeof exports !== 'undefined' && typeof module !== 'undefined') {
factory(exports, module, require('skatejs'));
} else {
var mod = {
exports: {}
};
factory(mod.exports, mod, global.skate);
global.skate = mod.exports;
}
})(this, function (exports, module, _skatejs) {
'use strict';
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _skate = _interopRequireDefault(_skatejs);
var auiSkate = _skate['default'].noConflict();
module.exports = auiSkate;
});
//# sourceMappingURL=../../../js/aui/internal/skate.js.map
|
parambirs/aui-demos
|
node_modules/@atlassian/aui/lib/js/aui/internal/skate.js
|
JavaScript
|
mit
| 757 |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UIButton : MonoBehaviour {
[SerializeField] private GameObject targetObject;
[SerializeField] private string targetMessage;
public Color highlightColor = Color.cyan;
public void OnMouseOver() {
SpriteRenderer sprite = GetComponent<SpriteRenderer>();
if (sprite != null) {
sprite.color = highlightColor;
}
}
public void OnMouseExit() {
SpriteRenderer sprite = GetComponent<SpriteRenderer>();
if (sprite != null) {
sprite.color = Color.white;
}
}
public void OnMouseDown() {
transform.localScale *= 1.1f;
}
public void OnMouseUp() {
transform.localScale = Vector3.one;
if (targetObject != null) {
targetObject.SendMessage(targetMessage);
}
}
}
|
ivanarellano/unity-in-action-book
|
Ch05/Assets/UIButton.cs
|
C#
|
mit
| 904 |
<footer class="main-footer">
<div class="pull-right hidden-xs">
</div>
<strong>Orange TV.</strong> All rights reserved.
</footer>
<!-- Control Sidebar -->
<!-- /.control-sidebar -->
<!-- Add the sidebar's background. This div must be placed
immediately after the control sidebar -->
<div class="control-sidebar-bg"></div>
</div>
<!-- ./wrapper -->
<!-- jQuery 2.2.3 -->
<script src="assets/plugins/jQuery/jquery-2.2.3.min.js"></script>
<!-- jQuery UI 1.11.4 -->
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<!-- Resolve conflict in jQuery UI tooltip with Bootstrap tooltip -->
<script>
$.widget.bridge('uibutton', $.ui.button);
</script>
<!-- DataTables -->
<script src="assets/plugins/datatables/jquery.dataTables.min.js"></script>
<script src="assets/plugins/datatables/dataTables.bootstrap.min.js"></script>
<!--<script src="assets/plugins/ckeditor/adapters/jquery.js"></script>-->
<!-- Bootstrap 3.3.6 -->
<script src="assets/bootstrap/js/bootstrap.min.js"></script>
<!-- <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script> -->
<!-- Morris.js charts -->
<!--
<script src="https://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
<script src="assets/plugins/morris/morris.min.js"></script>
-->
<!-- Sparkline -->
<script src="assets/plugins/sparkline/jquery.sparkline.min.js"></script>
<!-- jvectormap -->
<script src="assets/plugins/jvectormap/jquery-jvectormap-1.2.2.min.js"></script>
<script src="assets/plugins/jvectormap/jquery-jvectormap-world-mill-en.js"></script>
<!-- jQuery Knob Chart -->
<script src="assets/plugins/knob/jquery.knob.js"></script>
<!-- daterangepicker -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.2/moment.min.js"></script>
<script src="assets/plugins/daterangepicker/daterangepicker.js"></script>
<!-- datepicker -->
<script src="assets/plugins/datepicker/bootstrap-datepicker.js"></script>
<!-- Bootstrap WYSIHTML5 -->
<script src="assets/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.min.js"></script>
<!-- Slimscroll -->
<script src="assets/plugins/slimScroll/jquery.slimscroll.min.js"></script>
<!-- FastClick -->
<script src="assets/plugins/fastclick/fastclick.js"></script>
<!-- AdminLTE App -->
<script src="assets/dist/js/app.min.js"></script>
<!-- AdminLTE dashboard demo (This is only for demo purposes) -->
<!--<script src="assets/dist/js/pages/dashboard.js"></script>-->
<!-- AdminLTE for demo purposes -->
<script src="assets/dist/js/demo.js"></script>
<script src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.2.4/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.2.4/js/buttons.flash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/2.5.0/jszip.min.js"></script>
<!--
<script src="https://cdn.rawgit.com/bpampuch/pdfmake/0.1.18/build/pdfmake.min.js"></script>
<script src="https://cdn.rawgit.com/bpampuch/pdfmake/0.1.18/build/vfs_fonts.js"></script>
-->
<script src="https://cdn.datatables.net/buttons/1.2.4/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.2.4/js/buttons.print.min.js"></script>
<script src="assets/dist/js/custom.js"></script>
<script>
$(function () {
/*
var table = $('#example').DataTable( {
dom: 'Bfrtip',
buttons: [
'copy', 'csv', 'excel', 'pdf', 'print'
]
} );
table.buttons().container()
.appendTo( $('div.eight.column:eq(0)', table.table().container()) );
$('#example2').DataTable( {
buttons: [
{
extend: 'excel',
text: 'Save current page',
exportOptions: {
modifier: {
page: 'current'
}
}
}
]
} );
*/
$('#example').DataTable( {
dom: 'Bfrtip',
pageLength: 5,
//dom : 'Bflit',
buttons: ['copy', 'csv', 'excel', 'pdf', 'print'],
responsive: true
} );
$("#example1").DataTable();
$("#example2").DataTable({
"paging": false
});
$('#example3').DataTable({
"paging": true,
"lengthChange": false,
"searching": false,
"ordering": true,
"info": true,
"autoWidth": false
});
$('#example30').DataTable({
"paging": true,
"lengthChange": false,
"searching": false,
"ordering": true,
"info": true,
"autoWidth": false
});
});
// datatable paging
$(function() {
table = $('#example2c').DataTable({
"processing": true, //Feature control the processing indicator.
"serverSide": true, //Feature control DataTables' server-side processing mode.
"order": [], //Initial no order.
// Load data for the table's content from an Ajax source
"ajax": {
"url": "<?php if(isset($url)) {echo $url; } ?>",
"type": "POST"
},
//Set column definition initialisation properties.
"columnDefs": [
{
"targets": [ 0 ], //first column / numbering column
"orderable": false, //set not orderable
},
],
});
});
</script>
</body>
</html>
|
ariefstd/cdone_server_new
|
application/views/footer.php
|
PHP
|
mit
| 5,358 |
using Newtonsoft.Json;
using System.Collections.Generic;
namespace EaToGliffy.Gliffy.Model
{
public class GliffyParentObject : GliffyObject
{
[JsonProperty(PropertyName = "children")]
public List<GliffyObject> Children { get; set; }
}
}
|
vzoran/eatogliffy
|
eatogliffy/gliffy/model/GliffyParentObject.cs
|
C#
|
mit
| 269 |
// Copyright (c) 2011-2015 The Cryptonote developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "JsonOutputStreamSerializer.h"
#include <cassert>
#include <stdexcept>
#include "Common/StringTools.h"
using Common::JsonValue;
using namespace CryptoNote;
namespace CryptoNote {
std::ostream& operator<<(std::ostream& out, const JsonOutputStreamSerializer& enumerator) {
out << enumerator.root;
return out;
}
}
namespace {
template <typename T>
void insertOrPush(JsonValue& js, Common::StringView name, const T& value) {
if (js.isArray()) {
js.pushBack(JsonValue(value));
} else {
js.insert(std::string(name), JsonValue(value));
}
}
}
JsonOutputStreamSerializer::JsonOutputStreamSerializer() : root(JsonValue::OBJECT) {
chain.push_back(&root);
}
JsonOutputStreamSerializer::~JsonOutputStreamSerializer() {
}
ISerializer::SerializerType JsonOutputStreamSerializer::type() const {
return ISerializer::OUTPUT;
}
bool JsonOutputStreamSerializer::beginObject(Common::StringView name) {
JsonValue& parent = *chain.back();
JsonValue obj(JsonValue::OBJECT);
if (parent.isObject()) {
chain.push_back(&parent.insert(std::string(name), obj));
} else {
chain.push_back(&parent.pushBack(obj));
}
return true;
}
void JsonOutputStreamSerializer::endObject() {
assert(!chain.empty());
chain.pop_back();
}
bool JsonOutputStreamSerializer::beginArray(size_t& size, Common::StringView name) {
JsonValue val(JsonValue::ARRAY);
JsonValue& res = chain.back()->insert(std::string(name), val);
chain.push_back(&res);
return true;
}
void JsonOutputStreamSerializer::endArray() {
assert(!chain.empty());
chain.pop_back();
}
bool JsonOutputStreamSerializer::operator()(uint64_t& value, Common::StringView name) {
int64_t v = static_cast<int64_t>(value);
return operator()(v, name);
}
bool JsonOutputStreamSerializer::operator()(uint16_t& value, Common::StringView name) {
uint64_t v = static_cast<uint64_t>(value);
return operator()(v, name);
}
bool JsonOutputStreamSerializer::operator()(int16_t& value, Common::StringView name) {
int64_t v = static_cast<int64_t>(value);
return operator()(v, name);
}
bool JsonOutputStreamSerializer::operator()(uint32_t& value, Common::StringView name) {
uint64_t v = static_cast<uint64_t>(value);
return operator()(v, name);
}
bool JsonOutputStreamSerializer::operator()(int32_t& value, Common::StringView name) {
int64_t v = static_cast<int64_t>(value);
return operator()(v, name);
}
bool JsonOutputStreamSerializer::operator()(int64_t& value, Common::StringView name) {
insertOrPush(*chain.back(), name, value);
return true;
}
bool JsonOutputStreamSerializer::operator()(double& value, Common::StringView name) {
insertOrPush(*chain.back(), name, value);
return true;
}
bool JsonOutputStreamSerializer::operator()(std::string& value, Common::StringView name) {
insertOrPush(*chain.back(), name, value);
return true;
}
bool JsonOutputStreamSerializer::operator()(uint8_t& value, Common::StringView name) {
insertOrPush(*chain.back(), name, static_cast<int64_t>(value));
return true;
}
bool JsonOutputStreamSerializer::operator()(bool& value, Common::StringView name) {
insertOrPush(*chain.back(), name, value);
return true;
}
bool JsonOutputStreamSerializer::binary(void* value, size_t size, Common::StringView name) {
std::string hex = Common::toHex(value, size);
return (*this)(hex, name);
}
bool JsonOutputStreamSerializer::binary(std::string& value, Common::StringView name) {
return binary(const_cast<char*>(value.data()), value.size(), name);
}
|
tobeyrowe/StarKingdomCoin
|
src/Serialization/JsonOutputStreamSerializer.cpp
|
C++
|
mit
| 3,698 |
# Be sure to restart your server when you modify this file.
Refinery::Application.config.session_store :cookie_store, :key => '_skwarcan_session'
# Use the database for sessions instead of the cookie-based default,
# which shouldn't be used to store highly confidential information
# (create the session table with "rake db:sessions:create")
# Refinery::Application.config.session_store :active_record_store
|
mskwarcan/skwarcan
|
config/initializers/session_store.rb
|
Ruby
|
mit
| 409 |
/*
* author: Lisa
* Info: Base64 / UTF8
* 编码 & 解码
*/
function base64Encode(input) {
var keyStr = "ABCDEFGHIJKLMNOP" + "QRSTUVWXYZabcdef" + "ghijklmnopqrstuv" + "wxyz0123456789+/" + "=";
var output = "";
var chr1, chr2, chr3 = "";
var enc1, enc2, enc3, enc4 = "";
var i = 0;
do {
chr1 = input[i++];
chr2 = input[i++];
chr3 = input[i++];
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
keyStr.charAt(enc1) +
keyStr.charAt(enc2) +
keyStr.charAt(enc3) +
keyStr.charAt(enc4);
chr1 = chr2 = chr3 = "";
enc1 = enc2 = enc3 = enc4 = "";
} while (i < input.length);
return output;
}
function base64Decode(input) {
var output = "";
var chr1, chr2, chr3 = "";
var enc1, enc2, enc3, enc4 = "";
var i = 0;
var base64test = /[^A-Za-z0-9/+///=]/g;
if (base64test.exec(input)) {
alert("There were invalid base64 characters in the input text./n" +
"Valid base64 characters are A-Z, a-z, 0-9, '+', '/', and '='/n" +
"Expect errors in decoding.");
}
input = input.replace(/[^A-Za-z0-9/+///=]/g, "");
output=new Array();
do {
enc1 = keyStr.indexOf(input.charAt(i++));
enc2 = keyStr.indexOf(input.charAt(i++));
enc3 = keyStr.indexOf(input.charAt(i++));
enc4 = keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output.push(chr1);
if (enc3 != 64) {
output.push(chr2);
}
if (enc4 != 64) {
output.push(chr3);
}
chr1 = chr2 = chr3 = "";
enc1 = enc2 = enc3 = enc4 = "";
} while (i < input.length);
return output;
}
function UTF8Encode(str){
var temp = "",rs = "";
for( var i=0 , len = str.length; i < len; i++ ){
temp = str.charCodeAt(i).toString(16);
rs += "\\u"+ new Array(5-temp.length).join("0") + temp;
}
return rs;
}
function UTF8Decode(str){
return str.replace(/(\\u)(\w{4}|\w{2})/gi, function($0,$1,$2){
return String.fromCharCode(parseInt($2,16));
});
}
exports.base64Encode = base64Encode;
exports.base64Decode = base64Decode;
exports.UTF8Encode = UTF8Encode;
exports.UTF8Decode = UTF8Decode;
|
jrcjing/cbg-log
|
lib/Tool/base64.js
|
JavaScript
|
mit
| 2,332 |
<?php namespace ShinyDeploy\Domain\Database;
use ShinyDeploy\Core\Crypto\PasswordCrypto;
use ShinyDeploy\Core\Helper\StringHelper;
use ShinyDeploy\Exceptions\DatabaseException;
use ShinyDeploy\Exceptions\MissingDataException;
use ShinyDeploy\Traits\CryptableDomain;
class ApiKeys extends DatabaseDomain
{
use CryptableDomain;
/**
* Generates new API key and stores it to database.
*
* @param int $deploymentId
* @throws DatabaseException
* @throws MissingDataException
* @throws \ShinyDeploy\Exceptions\CryptographyException
* @return array
*/
public function addApiKey(int $deploymentId): array
{
if (empty($this->encryptionKey)) {
throw new MissingDataException('Encryption key not set.');
}
if (empty($deploymentId)) {
throw new MissingDataException('Deployment id can not be empty.');
}
$apiKey = StringHelper::getRandomString(20);
$passwordForUrl = StringHelper::getRandomString(16);
$password = $passwordForUrl . $this->config->get('auth.secret');
$passwordHash = hash('sha256', $password);
$encryption = new PasswordCrypto();
$encryptionKeySave = $encryption->encrypt($this->encryptionKey, $password);
$statement = "INSERT INTO api_keys (`api_key`,`deployment_id`,`password`,`encryption_key`)"
. " VALUES (%s,%i,%s,%s)";
$result = $this->db->prepare($statement, $apiKey, $deploymentId, $passwordHash, $encryptionKeySave)->execute();
if ($result === false) {
throw new DatabaseException('Could not store API key to database.');
}
return [
'apiKey' => $apiKey,
'apiPassword' => $passwordForUrl
];
}
/**
* Deletes all existing API keys for specified deployment.
*
* @param int $deploymentId
* @throws MissingDataException
* @return bool
*/
public function deleteApiKeysByDeploymentId(int $deploymentId): bool
{
if (empty($deploymentId)) {
throw new MissingDataException('Deployment id can not be empty.');
}
try {
$statement = "DELETE FROM api_keys WHERE `deployment_id` = %i";
return $this->db->prepare($statement, $deploymentId)->execute();
} catch (DatabaseException $e) {
return false;
}
}
/**
* Fetches API key data by api-key.
*
* @param string $apiKey
* @return array
* @throws MissingDataException
* @throws DatabaseException
*/
public function getDataByApiKey(string $apiKey): array
{
if (empty($apiKey)) {
throw new MissingDataException('API key can not be empty.');
}
$statement = "SELECT * FROM api_keys WHERE `api_key` = %s";
return $this->db->prepare($statement, $apiKey)->getResult();
}
}
|
nekudo/shiny_deploy
|
src/ShinyDeploy/Domain/Database/ApiKeys.php
|
PHP
|
mit
| 2,903 |
require File.dirname(__FILE__) + '/../spec_helper'
describe "Standard Tags" do
dataset :users_and_pages, :file_not_found, :snippets
it '<r:page> should allow access to the current page' do
page(:home)
page.should render('<r:page:title />').as('Home')
page.should render(%{<r:find url="/radius"><r:title /> | <r:page:title /></r:find>}).as('Radius | Home')
end
[:breadcrumb, :slug, :title, :url].each do |attr|
it "<r:#{attr}> should render the '#{attr}' attribute" do
value = page.send(attr)
page.should render("<r:#{attr} />").as(value.to_s)
end
end
it "<r:url> with a nil relative URL root should scope to the relative root of /" do
ActionController::Base.relative_url_root = nil
page(:home).should render("<r:url />").as("/")
end
it '<r:url> with a relative URL root should scope to the relative root' do
page(:home).should render("<r:url />").with_relative_root("/foo").as("/foo/")
end
it '<r:parent> should change the local context to the parent page' do
page(:parent)
page.should render('<r:parent><r:title /></r:parent>').as(pages(:home).title)
page.should render('<r:parent><r:children:each by="title"><r:title /></r:children:each></r:parent>').as(page_eachable_children(pages(:home)).collect(&:title).join(""))
page.should render('<r:children:each><r:parent:title /></r:children:each>').as(@page.title * page.children.count)
end
it '<r:if_parent> should render the contained block if the current page has a parent page' do
page.should render('<r:if_parent>true</r:if_parent>').as('true')
page(:home).should render('<r:if_parent>true</r:if_parent>').as('')
end
it '<r:unless_parent> should render the contained block unless the current page has a parent page' do
page.should render('<r:unless_parent>true</r:unless_parent>').as('')
page(:home).should render('<r:unless_parent>true</r:unless_parent>').as('true')
end
it '<r:if_children> should render the contained block if the current page has child pages' do
page(:home).should render('<r:if_children>true</r:if_children>').as('true')
page(:childless).should render('<r:if_children>true</r:if_children>').as('')
end
it '<r:unless_children> should render the contained block if the current page has no child pages' do
page(:home).should render('<r:unless_children>true</r:unless_children>').as('')
page(:childless).should render('<r:unless_children>true</r:unless_children>').as('true')
end
describe "<r:children:each>" do
it "should iterate through the children of the current page" do
page(:parent)
page.should render('<r:children:each><r:title /> </r:children:each>').as('Child Child 2 Child 3 ')
page.should render('<r:children:each><r:page><r:slug />/<r:child:slug /> </r:page></r:children:each>').as('parent/child parent/child-2 parent/child-3 ')
page(:assorted).should render(page_children_each_tags).as('a b c d e f g h i j ')
end
it 'should not list draft pages' do
page.should render('<r:children:each by="title"><r:slug /> </r:children:each>').as('a b c d e f g h i j ')
end
it 'should include draft pages with status="all"' do
page.should render('<r:children:each status="all" by="slug"><r:slug /> </r:children:each>').as('a b c d draft e f g h i j ')
end
it "should include draft pages by default on the dev host" do
page.should render('<r:children:each by="slug"><r:slug /> </r:children:each>').as('a b c d draft e f g h i j ').on('dev.site.com')
end
it 'should not list draft pages on dev.site.com when Radiant::Config["dev.host"] is set to something else' do
Radiant::Config['dev.host'] = 'preview.site.com'
page.should render('<r:children:each by="title"><r:slug /> </r:children:each>').as('a b c d e f g h i j ').on('dev.site.com')
end
it 'should paginate results when "paginated" attribute is "true"' do
page.pagination_parameters = {:page => 1, :per_page => 10}
page.should render('<r:children:each paginated="true" per_page="10"><r:slug /> </r:children:each>').as('a b c d e f g h i j ')
page.should render('<r:children:each paginated="true" per_page="2"><r:slug /> </r:children:each>').matching(/div class="pagination"/)
end
it 'should error with invalid "limit" attribute' do
message = "`limit' attribute of `each' tag must be a positive number between 1 and 4 digits"
page.should render(page_children_each_tags(%{limit="a"})).with_error(message)
page.should render(page_children_each_tags(%{limit="-10"})).with_error(message)
page.should render(page_children_each_tags(%{limit="50000"})).with_error(message)
end
it 'should error with invalid "offset" attribute' do
message = "`offset' attribute of `each' tag must be a positive number between 1 and 4 digits"
page.should render(page_children_each_tags(%{offset="a"})).with_error(message)
page.should render(page_children_each_tags(%{offset="-10"})).with_error(message)
page.should render(page_children_each_tags(%{offset="50000"})).with_error(message)
end
it 'should error with invalid "by" attribute' do
message = "`by' attribute of `each' tag must be set to a valid field name"
page.should render(page_children_each_tags(%{by="non-existant-field"})).with_error(message)
end
it 'should error with invalid "order" attribute' do
message = %{`order' attribute of `each' tag must be set to either "asc" or "desc"}
page.should render(page_children_each_tags(%{order="asdf"})).with_error(message)
end
it "should limit the number of children when given a 'limit' attribute" do
page.should render(page_children_each_tags(%{limit="5"})).as('a b c d e ')
end
it "should limit and offset the children when given 'limit' and 'offset' attributes" do
page.should render(page_children_each_tags(%{offset="3" limit="5"})).as('d e f g h ')
end
it "should change the sort order when given an 'order' attribute" do
page.should render(page_children_each_tags(%{order="desc"})).as('j i h g f e d c b a ')
end
it "should sort by the 'by' attribute" do
page.should render(page_children_each_tags(%{by="breadcrumb"})).as('f e d c b a j i h g ')
end
it "should sort by the 'by' attribute according to the 'order' attribute" do
page.should render(page_children_each_tags(%{by="breadcrumb" order="desc"})).as('g h i j a b c d e f ')
end
describe 'with "status" attribute' do
it "set to 'all' should list all children" do
page.should render(page_children_each_tags(%{status="all"})).as("a b c d e f g h i j draft ")
end
it "set to 'draft' should list only children with 'draft' status" do
page.should render(page_children_each_tags(%{status="draft"})).as('draft ')
end
it "set to 'published' should list only children with 'draft' status" do
page.should render(page_children_each_tags(%{status="published"})).as('a b c d e f g h i j ')
end
it "set to an invalid status should render an error" do
page.should render(page_children_each_tags(%{status="askdf"})).with_error("`status' attribute of `each' tag must be set to a valid status")
end
end
end
describe "<r:children:each:if_first>" do
it "should render for the first child" do
tags = '<r:children:each><r:if_first>FIRST:</r:if_first><r:slug /> </r:children:each>'
expected = "FIRST:article article-2 article-3 article-4 "
page(:news).should render(tags).as(expected)
end
end
describe "<r:children:each:unless_first>" do
it "should render for all but the first child" do
tags = '<r:children:each><r:unless_first>NOT-FIRST:</r:unless_first><r:slug /> </r:children:each>'
expected = "article NOT-FIRST:article-2 NOT-FIRST:article-3 NOT-FIRST:article-4 "
page(:news).should render(tags).as(expected)
end
end
describe "<r:children:each:if_last>" do
it "should render for the last child" do
tags = '<r:children:each><r:if_last>LAST:</r:if_last><r:slug /> </r:children:each>'
expected = "article article-2 article-3 LAST:article-4 "
page(:news).should render(tags).as(expected)
end
end
describe "<r:children:each:unless_last>" do
it "should render for all but the last child" do
tags = '<r:children:each><r:unless_last>NOT-LAST:</r:unless_last><r:slug /> </r:children:each>'
expected = "NOT-LAST:article NOT-LAST:article-2 NOT-LAST:article-3 article-4 "
page(:news).should render(tags).as(expected)
end
end
describe "<r:children:each:header>" do
it "should render the header when it changes" do
tags = '<r:children:each><r:header>[<r:date format="%b/%y" />] </r:header><r:slug /> </r:children:each>'
expected = "[Dec/00] article [Feb/01] article-2 article-3 [Mar/01] article-4 "
page(:news).should render(tags).as(expected)
end
it 'with "name" attribute should maintain a separate header' do
tags = %{<r:children:each><r:header name="year">[<r:date format='%Y' />] </r:header><r:header name="month">(<r:date format="%b" />) </r:header><r:slug /> </r:children:each>}
expected = "[2000] (Dec) article [2001] (Feb) article-2 article-3 (Mar) article-4 "
page(:news).should render(tags).as(expected)
end
it 'with "restart" attribute set to one name should restart that header' do
tags = %{<r:children:each><r:header name="year" restart="month">[<r:date format='%Y' />] </r:header><r:header name="month">(<r:date format="%b" />) </r:header><r:slug /> </r:children:each>}
expected = "[2000] (Dec) article [2001] (Feb) article-2 article-3 (Mar) article-4 "
page(:news).should render(tags).as(expected)
end
it 'with "restart" attribute set to two names should restart both headers' do
tags = %{<r:children:each><r:header name="year" restart="month;day">[<r:date format='%Y' />] </r:header><r:header name="month" restart="day">(<r:date format="%b" />) </r:header><r:header name="day"><<r:date format='%d' />> </r:header><r:slug /> </r:children:each>}
expected = "[2000] (Dec) <01> article [2001] (Feb) <09> article-2 <24> article-3 (Mar) <06> article-4 "
page(:news).should render(tags).as(expected)
end
end
describe "<r:children:count>" do
it 'should render the number of children of the current page' do
page(:parent).should render('<r:children:count />').as('3')
end
it "should accept the same scoping conditions as <r:children:each>" do
page.should render('<r:children:count />').as('10')
page.should render('<r:children:count status="all" />').as('11')
page.should render('<r:children:count status="draft" />').as('1')
page.should render('<r:children:count status="hidden" />').as('0')
end
end
describe "<r:children:first>" do
it 'should render its contents in the context of the first child page' do
page(:parent).should render('<r:children:first:title />').as('Child')
end
it 'should accept the same scoping attributes as <r:children:each>' do
page.should render(page_children_first_tags).as('a')
page.should render(page_children_first_tags(%{limit="5"})).as('a')
page.should render(page_children_first_tags(%{offset="3" limit="5"})).as('d')
page.should render(page_children_first_tags(%{order="desc"})).as('j')
page.should render(page_children_first_tags(%{by="breadcrumb"})).as('f')
page.should render(page_children_first_tags(%{by="breadcrumb" order="desc"})).as('g')
end
it "should render nothing when no children exist" do
page(:first).should render('<r:children:first:title />').as('')
end
end
describe "<r:children:last>" do
it 'should render its contents in the context of the last child page' do
page(:parent).should render('<r:children:last:title />').as('Child 3')
end
it 'should accept the same scoping attributes as <r:children:each>' do
page.should render(page_children_last_tags).as('j')
page.should render(page_children_last_tags(%{limit="5"})).as('e')
page.should render(page_children_last_tags(%{offset="3" limit="5"})).as('h')
page.should render(page_children_last_tags(%{order="desc"})).as('a')
page.should render(page_children_last_tags(%{by="breadcrumb"})).as('g')
page.should render(page_children_last_tags(%{by="breadcrumb" order="desc"})).as('f')
end
it "should render nothing when no children exist" do
page(:first).should render('<r:children:last:title />').as('')
end
end
describe "<r:content>" do
it "should render the 'body' part by default" do
page.should render('<r:content />').as('Assorted body.')
end
it "with 'part' attribute should render the specified part" do
page(:home).should render('<r:content part="extended" />').as("Just a test.")
end
it "should prevent simple recursion" do
page(:recursive_parts).should render('<r:content />').with_error("Recursion error: already rendering the `body' part.")
end
it "should prevent deep recursion" do
page(:recursive_parts).should render('<r:content part="one"/>').with_error("Recursion error: already rendering the `one' part.")
page(:recursive_parts).should render('<r:content part="two"/>').with_error("Recursion error: already rendering the `two' part.")
end
it "should allow repetition" do
page(:recursive_parts).should render('<r:content part="repeat"/>').as('xx')
end
it "should not prevent rendering a part more than once in sequence" do
page(:home).should render('<r:content /><r:content />').as('Hello world!Hello world!')
end
describe "with inherit attribute" do
it "missing or set to 'false' should render the current page's part" do
page.should render('<r:content part="sidebar" />').as('')
page.should render('<r:content part="sidebar" inherit="false" />').as('')
end
describe "set to 'true'" do
it "should render an ancestor's part" do
page.should render('<r:content part="sidebar" inherit="true" />').as('Assorted sidebar.')
end
it "should render nothing when no ancestor has the part" do
page.should render('<r:content part="part_that_doesnt_exist" inherit="true" />').as('')
end
describe "and contextual attribute" do
it "set to 'true' should render the part in the context of the current page" do
page(:parent).should render('<r:content part="sidebar" inherit="true" contextual="true" />').as('Parent sidebar.')
page(:child).should render('<r:content part="sidebar" inherit="true" contextual="true" />').as('Child sidebar.')
page(:grandchild).should render('<r:content part="sidebar" inherit="true" contextual="true" />').as('Grandchild sidebar.')
end
it "set to 'false' should render the part in the context of its containing page" do
page(:parent).should render('<r:content part="sidebar" inherit="true" contextual="false" />').as('Home sidebar.')
end
it "should maintain the global page" do
page(:first)
page.should render('<r:content part="titles" inherit="true" contextual="true"/>').as('First First')
page.should render('<r:content part="titles" inherit="true" contextual="false"/>').as('Home First')
end
end
end
it "set to an erroneous value should render an error" do
page.should render('<r:content part="sidebar" inherit="weird value" />').with_error(%{`inherit' attribute of `content' tag must be set to either "true" or "false"})
end
it "should render parts with respect to the current contextual page" do
expected = "Child body. Child 2 body. Child 3 body. "
page(:parent).should render('<r:children:each><r:content /> </r:children:each>').as(expected)
end
end
end
describe "<r:if_content>" do
it "without 'part' attribute should render the contained block if the 'body' part exists" do
page.should render('<r:if_content>true</r:if_content>').as('true')
end
it "should render the contained block if the specified part exists" do
page.should render('<r:if_content part="body">true</r:if_content>').as('true')
end
it "should not render the contained block if the specified part does not exist" do
page.should render('<r:if_content part="asdf">true</r:if_content>').as('')
end
describe "with more than one part given (separated by comma)" do
it "should render the contained block only if all specified parts exist" do
page(:home).should render('<r:if_content part="body, extended">true</r:if_content>').as('true')
end
it "should not render the contained block if at least one of the specified parts does not exist" do
page(:home).should render('<r:if_content part="body, madeup">true</r:if_content>').as('')
end
describe "with inherit attribute set to 'true'" do
it 'should render the contained block if the current or ancestor pages have the specified parts' do
page(:guests).should render('<r:if_content part="favors, extended" inherit="true">true</r:if_content>').as('true')
end
it 'should not render the contained block if the current or ancestor pages do not have all of the specified parts' do
page(:guests).should render('<r:if_content part="favors, madeup" inherit="true">true</r:if_content>').as('')
end
describe "with find attribute set to 'any'" do
it 'should render the contained block if the current or ancestor pages have any of the specified parts' do
page(:guests).should render('<r:if_content part="favors, madeup" inherit="true" find="any">true</r:if_content>').as('true')
end
it 'should still render the contained block if first of the specified parts has not been found' do
page(:guests).should render('<r:if_content part="madeup, favors" inherit="true" find="any">true</r:if_content>').as('true')
end
end
end
describe "with inherit attribute set to 'false'" do
it 'should render the contained block if the current page has the specified parts' do
page(:guests).should render('<r:if_content part="favors, games" inherit="false">true</r:if_content>').as('')
end
it 'should not render the contained block if the current or ancestor pages do not have all of the specified parts' do
page(:guests).should render('<r:if_content part="favors, madeup" inherit="false">true</r:if_content>').as('')
end
end
describe "with the 'find' attribute set to 'any'" do
it "should render the contained block if any of the specified parts exist" do
page.should render('<r:if_content part="body, asdf" find="any">true</r:if_content>').as('true')
end
end
describe "with the 'find' attribute set to 'all'" do
it "should render the contained block if all of the specified parts exist" do
page(:home).should render('<r:if_content part="body, sidebar" find="all">true</r:if_content>').as('true')
end
it "should not render the contained block if all of the specified parts do not exist" do
page.should render('<r:if_content part="asdf, madeup" find="all">true</r:if_content>').as('')
end
end
end
end
describe "<r:unless_content>" do
describe "with inherit attribute set to 'true'" do
it 'should not render the contained block if the current or ancestor pages have the specified parts' do
page(:guests).should render('<r:unless_content part="favors, extended" inherit="true">true</r:unless_content>').as('')
end
it 'should render the contained block if the current or ancestor pages do not have the specified parts' do
page(:guests).should render('<r:unless_content part="madeup, imaginary" inherit="true">true</r:unless_content>').as('true')
end
it "should not render the contained block if the specified part does not exist but does exist on an ancestor" do
page.should render('<r:unless_content part="sidebar" inherit="true">false</r:unless_content>').as('')
end
describe "with find attribute set to 'any'" do
it 'should not render the contained block if the current or ancestor pages have any of the specified parts' do
page(:guests).should render('<r:unless_content part="favors, madeup" inherit="true" find="any">true</r:unless_content>').as('')
end
it 'should still not render the contained block if first of the specified parts has not been found' do
page(:guests).should render('<r:unless_content part="madeup, favors" inherit="true" find="any">true</r:unless_content>').as('')
end
end
end
it "without 'part' attribute should not render the contained block if the 'body' part exists" do
page.should render('<r:unless_content>false</r:unless_content>').as('')
end
it "should not render the contained block if the specified part exists" do
page.should render('<r:unless_content part="body">false</r:unless_content>').as('')
end
it "should render the contained block if the specified part does not exist" do
page.should render('<r:unless_content part="asdf">false</r:unless_content>').as('false')
end
it "should render the contained block if the specified part does not exist but does exist on an ancestor" do
page.should render('<r:unless_content part="sidebar">false</r:unless_content>').as('false')
end
describe "with more than one part given (separated by comma)" do
it "should not render the contained block if all of the specified parts exist" do
page(:home).should render('<r:unless_content part="body, extended">true</r:unless_content>').as('')
end
it "should render the contained block if at least one of the specified parts exists" do
page(:home).should render('<r:unless_content part="body, madeup">true</r:unless_content>').as('true')
end
describe "with the 'inherit' attribute set to 'true'" do
it "should render the contained block if the current or ancestor pages have none of the specified parts" do
page.should render('<r:unless_content part="imaginary, madeup" inherit="true">true</r:unless_content>').as('true')
end
it "should not render the contained block if all of the specified parts are present on the current or ancestor pages" do
page(:party).should render('<r:unless_content part="favors, extended" inherit="true">true</r:unless_content>').as('')
end
end
describe "with the 'find' attribute set to 'all'" do
it "should not render the contained block if all of the specified parts exist" do
page(:home).should render('<r:unless_content part="body, sidebar" find="all">true</r:unless_content>').as('')
end
it "should render the contained block unless all of the specified parts exist" do
page.should render('<r:unless_content part="body, madeup" find="all">true</r:unless_content>').as('true')
end
end
describe "with the 'find' attribute set to 'any'" do
it "should not render the contained block if any of the specified parts exist" do
page.should render('<r:unless_content part="body, madeup" find="any">true</r:unless_content>').as('')
end
end
end
end
describe "<r:author>" do
it "should render the author of the current page" do
page.should render('<r:author />').as('Admin')
end
it "should render nothing when the page has no author" do
page(:no_user).should render('<r:author />').as('')
end
end
describe "<r:gravatar>" do
it "should render the Gravatar URL of author of the current page" do
page.should render('<r:gravatar />').as('http://www.gravatar.com/avatar.php?gravatar_id=e64c7d89f26bd1972efa854d13d7dd61&rating=G&size=32')
end
it "should render the Gravatar URL of the name user" do
page.should render('<r:gravatar name="Admin" />').as('http://www.gravatar.com/avatar.php?gravatar_id=e64c7d89f26bd1972efa854d13d7dd61&rating=G&size=32')
end
it "should render the default avatar when the user has not set an email address" do
page.should render('<r:gravatar name="Designer" />').as('http://testhost.tld/images/admin/avatar_32x32.png')
end
it "should render the specified size" do
page.should render('<r:gravatar name="Designer" size="96px" />').as('http://testhost.tld/images/admin/avatar_96x96.png')
end
it "should render the specified rating" do
page.should render('<r:gravatar rating="X" />').as('http://www.gravatar.com/avatar.php?gravatar_id=e64c7d89f26bd1972efa854d13d7dd61&rating=X&size=32')
end
end
describe "<r:date>" do
before :each do
page(:dated)
end
it "should render the published date of the page" do
page.should render('<r:date />').as('Wednesday, January 11, 2006')
end
it "should format the published date according to the 'format' attribute" do
page.should render('<r:date format="%d %b %Y" />').as('11 Jan 2006')
end
describe "with 'for' attribute" do
it "set to 'now' should render the current date in the current Time.zone" do
page.should render('<r:date for="now" />').as(Time.zone.now.strftime("%A, %B %d, %Y"))
end
it "set to 'created_at' should render the creation date" do
page.should render('<r:date for="created_at" />').as('Tuesday, January 10, 2006')
end
it "set to 'updated_at' should render the update date" do
page.should render('<r:date for="updated_at" />').as('Thursday, January 12, 2006')
end
it "set to 'published_at' should render the publish date" do
page.should render('<r:date for="published_at" />').as('Wednesday, January 11, 2006')
end
it "set to an invalid attribute should render an error" do
page.should render('<r:date for="blah" />').with_error("Invalid value for 'for' attribute.")
end
end
it "should use the currently set timezone" do
Time.zone = "Tokyo"
format = "%H:%m"
expected = page.published_at.in_time_zone(ActiveSupport::TimeZone['Tokyo']).strftime(format)
page.should render(%Q(<r:date format="#{format}" />) ).as(expected)
end
end
describe "<r:link>" do
it "should render a link to the current page" do
page.should render('<r:link />').as('<a href="/assorted/">Assorted</a>')
end
it "should render its contents as the text of the link" do
page.should render('<r:link>Test</r:link>').as('<a href="/assorted/">Test</a>')
end
it "should pass HTML attributes to the <a> tag" do
expected = '<a href="/assorted/" class="test" id="assorted">Assorted</a>'
page.should render('<r:link class="test" id="assorted" />').as(expected)
end
it "should add the anchor attribute to the link as a URL anchor" do
page.should render('<r:link anchor="test">Test</r:link>').as('<a href="/assorted/#test">Test</a>')
end
it "should render a link for the current contextual page" do
expected = %{<a href="/parent/child/">Child</a> <a href="/parent/child-2/">Child 2</a> <a href="/parent/child-3/">Child 3</a> }
page(:parent).should render('<r:children:each><r:link /> </r:children:each>' ).as(expected)
end
it "should scope the link within the relative URL root" do
page(:assorted).should render('<r:link />').with_relative_root('/foo').as('<a href="/foo/assorted/">Assorted</a>')
end
end
describe "<r:snippet>" do
it "should render the contents of the specified snippet" do
page.should render('<r:snippet name="first" />').as('test')
end
it "should render an error when the snippet does not exist" do
page.should render('<r:snippet name="non-existant" />').with_error('snippet not found')
end
it "should render an error when not given a 'name' attribute" do
page.should render('<r:snippet />').with_error("`snippet' tag must contain `name' attribute")
end
it "should filter the snippet with its assigned filter" do
page.should render('<r:page><r:snippet name="markdown" /></r:page>').matching(%r{<p><strong>markdown</strong></p>})
end
it "should maintain the global page inside the snippet" do
page(:parent).should render('<r:snippet name="global_page_cascade" />').as("#{@page.title} " * @page.children.count)
end
it "should maintain the global page when the snippet renders recursively" do
page(:child).should render('<r:snippet name="recursive" />').as("Great GrandchildGrandchildChild")
end
it "should render the specified snippet when called as an empty double-tag" do
page.should render('<r:snippet name="first"></r:snippet>').as('test')
end
it "should capture contents of a double tag, substituting for <r:yield/> in snippet" do
page.should render('<r:snippet name="yielding">inner</r:snippet>').
as('Before...inner...and after')
end
it "should do nothing with contents of double tag when snippet doesn't yield" do
page.should render('<r:snippet name="first">content disappears!</r:snippet>').
as('test')
end
it "should render nested yielding snippets" do
page.should render('<r:snippet name="div_wrap"><r:snippet name="yielding">Hello, World!</r:snippet></r:snippet>').
as('<div>Before...Hello, World!...and after</div>')
end
it "should render double-tag snippets called from within a snippet" do
page.should render('<r:snippet name="nested_yields">the content</r:snippet>').
as('<snippet name="div_wrap">above the content below</snippet>')
end
it "should render contents each time yield is called" do
page.should render('<r:snippet name="yielding_often">French</r:snippet>').
as('French is Frencher than French')
end
end
it "should do nothing when called from page body" do
page.should render('<r:yield/>').as("")
end
it '<r:random> should render a randomly selected contained <r:option>' do
page.should render("<r:random> <r:option>1</r:option> <r:option>2</r:option> <r:option>3</r:option> </r:random>").matching(/^(1|2|3)$/)
end
it '<r:random> should render a randomly selected, dynamically set <r:option>' do
page(:parent).should render("<r:random:children:each:option:title />").matching(/^(Child|Child\ 2|Child\ 3)$/)
end
it '<r:comment> should render nothing it contains' do
page.should render('just a <r:comment>small </r:comment>test').as('just a test')
end
describe "<r:navigation>" do
it "should render the nested <r:normal> tag by default" do
tags = %{<r:navigation urls="Home: / | Assorted: /assorted/ | Parent: /parent/">
<r:normal><r:title /></r:normal>
</r:navigation>}
expected = %{Home Assorted Parent}
page.should render(tags).as(expected)
end
it "should render the nested <r:selected> tag for URLs that match the current page" do
tags = %{<r:navigation urls="Home: / | Assorted: /assorted/ | Parent: /parent/ | Radius: /radius/">
<r:normal><r:title /></r:normal>
<r:selected><strong><r:title/></strong></r:selected>
</r:navigation>}
expected = %{<strong>Home</strong> Assorted <strong>Parent</strong> Radius}
page(:parent).should render(tags).as(expected)
end
it "should render the nested <r:here> tag for URLs that exactly match the current page" do
tags = %{<r:navigation urls="Home: Boy: / | Assorted: /assorted/ | Parent: /parent/">
<r:normal><a href="<r:url />"><r:title /></a></r:normal>
<r:here><strong><r:title /></strong></r:here>
<r:selected><strong><a href="<r:url />"><r:title /></a></strong></r:selected>
<r:between> | </r:between>
</r:navigation>}
expected = %{<strong><a href="/">Home: Boy</a></strong> | <strong>Assorted</strong> | <a href="/parent/">Parent</a>}
page.should render(tags).as(expected)
end
it "should render the nested <r:between> tag between each link" do
tags = %{<r:navigation urls="Home: / | Assorted: /assorted/ | Parent: /parent/">
<r:normal><r:title /></r:normal>
<r:between> :: </r:between>
</r:navigation>}
expected = %{Home :: Assorted :: Parent}
page.should render(tags).as(expected)
end
it 'without urls should render nothing' do
page.should render(%{<r:navigation><r:normal /></r:navigation>}).as('')
end
it 'without a nested <r:normal> tag should render an error' do
page.should render(%{<r:navigation urls="something:here"></r:navigation>}).with_error( "`navigation' tag must include a `normal' tag")
end
it 'with urls without trailing slashes should match corresponding pages' do
tags = %{<r:navigation urls="Home: / | Assorted: /assorted | Parent: /parent | Radius: /radius">
<r:normal><r:title /></r:normal>
<r:here><strong><r:title /></strong></r:here>
</r:navigation>}
expected = %{Home <strong>Assorted</strong> Parent Radius}
page.should render(tags).as(expected)
end
it 'should prune empty blocks' do
tags = %{<r:navigation urls="Home: Boy: / | Archives: /archive/ | Radius: /radius/ | Docs: /documentation/">
<r:normal><a href="<r:url />"><r:title /></a></r:normal>
<r:here></r:here>
<r:selected><strong><a href="<r:url />"><r:title /></a></strong></r:selected>
<r:between> | </r:between>
</r:navigation>}
expected = %{<strong><a href="/">Home: Boy</a></strong> | <a href="/archive/">Archives</a> | <a href="/documentation/">Docs</a>}
page(:radius).should render(tags).as(expected)
end
it 'should render text under <r:if_first> and <r:if_last> only on the first and last item, respectively' do
tags = %{<r:navigation urls="Home: / | Assorted: /assorted | Parent: /parent | Radius: /radius">
<r:normal><r:if_first>(</r:if_first><a href="<r:url />"><r:title /></a><r:if_last>)</r:if_last></r:normal>
<r:here><r:if_first>(</r:if_first><r:title /><r:if_last>)</r:if_last></r:here>
<r:selected><r:if_first>(</r:if_first><strong><a href="<r:url />"><r:title /></a></strong><r:if_last>)</r:if_last></r:selected>
</r:navigation>}
expected = %{(<strong><a href=\"/\">Home</a></strong> <a href=\"/assorted\">Assorted</a> <a href=\"/parent\">Parent</a> Radius)}
page(:radius).should render(tags).as(expected)
end
it 'should render text under <r:unless_first> on every item but the first' do
tags = %{<r:navigation urls="Home: / | Assorted: /assorted | Parent: /parent | Radius: /radius">
<r:normal><r:unless_first>> </r:unless_first><a href="<r:url />"><r:title /></a></r:normal>
<r:here><r:unless_first>> </r:unless_first><r:title /></r:here>
<r:selected><r:unless_first>> </r:unless_first><strong><a href="<r:url />"><r:title /></a></strong></r:selected>
</r:navigation>}
expected = %{<strong><a href=\"/\">Home</a></strong> > <a href=\"/assorted\">Assorted</a> > <a href=\"/parent\">Parent</a> > Radius}
page(:radius).should render(tags).as(expected)
end
it 'should render text under <r:unless_last> on every item but the last' do
tags = %{<r:navigation urls="Home: / | Assorted: /assorted | Parent: /parent | Radius: /radius">
<r:normal><a href="<r:url />"><r:title /></a><r:unless_last> ></r:unless_last></r:normal>
<r:here><r:title /><r:unless_last> ></r:unless_last></r:here>
<r:selected><strong><a href="<r:url />"><r:title /></a></strong><r:unless_last> ></r:unless_last></r:selected>
</r:navigation>}
expected = %{<strong><a href=\"/\">Home</a></strong> > <a href=\"/assorted\">Assorted</a> > <a href=\"/parent\">Parent</a> > Radius}
page(:radius).should render(tags).as(expected)
end
end
describe "<r:find>" do
it "should change the local page to the page specified in the 'url' attribute" do
page.should render(%{<r:find url="/parent/child/"><r:title /></r:find>}).as('Child')
end
it "should render an error without the 'url' attribute" do
page.should render(%{<r:find />}).with_error("`find' tag must contain `url' attribute")
end
it "should render nothing when the 'url' attribute does not point to a page" do
page.should render(%{<r:find url="/asdfsdf/"><r:title /></r:find>}).as('')
end
it "should render nothing when the 'url' attribute does not point to a page and a custom 404 page exists" do
page.should render(%{<r:find url="/gallery/asdfsdf/"><r:title /></r:find>}).as('')
end
it "should scope contained tags to the found page" do
page.should render(%{<r:find url="/parent/"><r:children:each><r:slug /> </r:children:each></r:find>}).as('child child-2 child-3 ')
end
it "should accept a path relative to the current page" do
page(:great_grandchild).should render(%{<r:find url="../../../child-2"><r:title/></r:find>}).as("Child 2")
end
end
it '<r:escape_html> should escape HTML-related characters into entities' do
page.should render('<r:escape_html><strong>a bold move</strong></r:escape_html>').as('<strong>a bold move</strong>')
end
it '<r:rfc1123_date> should render an RFC1123-compatible date' do
page(:dated).should render('<r:rfc1123_date />').as('Wed, 11 Jan 2006 00:00:00 GMT')
end
describe "<r:breadcrumbs>" do
it "should render a series of breadcrumb links separated by >" do
expected = %{<a href="/">Home</a> > <a href="/parent/">Parent</a> > <a href="/parent/child/">Child</a> > <a href="/parent/child/grandchild/">Grandchild</a> > Great Grandchild}
page(:great_grandchild).should render('<r:breadcrumbs />').as(expected)
end
it "with a 'separator' attribute should use the separator instead of >" do
expected = %{<a href="/">Home</a> :: Parent}
page(:parent).should render('<r:breadcrumbs separator=" :: " />').as(expected)
end
it "with a 'nolinks' attribute set to 'true' should not render links" do
expected = %{Home > Parent}
page(:parent).should render('<r:breadcrumbs nolinks="true" />').as(expected)
end
it "with a relative URL root should scope links to the relative root" do
expected = '<a href="/foo/">Home</a> > Assorted'
page(:assorted).should render('<r:breadcrumbs />').with_relative_root('/foo').as(expected)
end
end
describe "<r:if_url>" do
describe "with 'matches' attribute" do
it "should render the contained block if the page URL matches" do
page.should render('<r:if_url matches="a.sorted/$">true</r:if_url>').as('true')
end
it "should not render the contained block if the page URL does not match" do
page.should render('<r:if_url matches="fancypants">true</r:if_url>').as('')
end
it "set to a malformatted regexp should render an error" do
page.should render('<r:if_url matches="as(sorted/$">true</r:if_url>').with_error("Malformed regular expression in `matches' argument of `if_url' tag: unmatched (: /as(sorted\\/$/")
end
it "without 'ignore_case' attribute should ignore case by default" do
page.should render('<r:if_url matches="asSorted/$">true</r:if_url>').as('true')
end
describe "with 'ignore_case' attribute" do
it "set to 'true' should use a case-insensitive match" do
page.should render('<r:if_url matches="asSorted/$" ignore_case="true">true</r:if_url>').as('true')
end
it "set to 'false' should use a case-sensitive match" do
page.should render('<r:if_url matches="asSorted/$" ignore_case="false">true</r:if_url>').as('')
end
end
end
it "with no attributes should render an error" do
page.should render('<r:if_url>test</r:if_url>').with_error("`if_url' tag must contain a `matches' attribute.")
end
end
describe "<r:unless_url>" do
describe "with 'matches' attribute" do
it "should not render the contained block if the page URL matches" do
page.should render('<r:unless_url matches="a.sorted/$">true</r:unless_url>').as('')
end
it "should render the contained block if the page URL does not match" do
page.should render('<r:unless_url matches="fancypants">true</r:unless_url>').as('true')
end
it "set to a malformatted regexp should render an error" do
page.should render('<r:unless_url matches="as(sorted/$">true</r:unless_url>').with_error("Malformed regular expression in `matches' argument of `unless_url' tag: unmatched (: /as(sorted\\/$/")
end
it "without 'ignore_case' attribute should ignore case by default" do
page.should render('<r:unless_url matches="asSorted/$">true</r:unless_url>').as('')
end
describe "with 'ignore_case' attribute" do
it "set to 'true' should use a case-insensitive match" do
page.should render('<r:unless_url matches="asSorted/$">true</r:unless_url>').as('')
end
it "set to 'false' should use a case-sensitive match" do
page.should render('<r:unless_url matches="asSorted/$" ignore_case="false">true</r:unless_url>').as('true')
end
end
end
it "with no attributes should render an error" do
page.should render('<r:unless_url>test</r:unless_url>').with_error("`unless_url' tag must contain a `matches' attribute.")
end
end
describe "<r:cycle>" do
it "should render passed values in succession" do
page.should render('<r:cycle values="first, second" /> <r:cycle values="first, second" />').as('first second')
end
it "should return to the beginning of the cycle when reaching the end" do
page.should render('<r:cycle values="first, second" /> <r:cycle values="first, second" /> <r:cycle values="first, second" />').as('first second first')
end
it "should use a default cycle name of 'cycle'" do
page.should render('<r:cycle values="first, second" /> <r:cycle values="first, second" name="cycle" />').as('first second')
end
it "should maintain separate cycle counters" do
page.should render('<r:cycle values="first, second" /> <r:cycle values="one, two" name="numbers" /> <r:cycle values="first, second" /> <r:cycle values="one, two" name="numbers" />').as('first one second two')
end
it "should reset the counter" do
page.should render('<r:cycle values="first, second" /> <r:cycle values="first, second" reset="true"/>').as('first first')
end
it "should require the values attribute" do
page.should render('<r:cycle />').with_error("`cycle' tag must contain a `values' attribute.")
end
end
describe "<r:if_dev>" do
it "should render the contained block when on the dev site" do
page.should render('-<r:if_dev>dev</r:if_dev>-').as('-dev-').on('dev.site.com')
end
it "should not render the contained block when not on the dev site" do
page.should render('-<r:if_dev>dev</r:if_dev>-').as('--')
end
describe "on an included page" do
it "should render the contained block when on the dev site" do
page.should render('-<r:find url="/devtags/"><r:content part="if_dev" /></r:find>-').as('-dev-').on('dev.site.com')
end
it "should not render the contained block when not on the dev site" do
page.should render('-<r:find url="/devtags/"><r:content part="if_dev" /></r:find>-').as('--')
end
end
end
describe "<r:unless_dev>" do
it "should not render the contained block when not on the dev site" do
page.should render('-<r:unless_dev>not dev</r:unless_dev>-').as('--').on('dev.site.com')
end
it "should render the contained block when not on the dev site" do
page.should render('-<r:unless_dev>not dev</r:unless_dev>-').as('-not dev-')
end
describe "on an included page" do
it "should not render the contained block when not on the dev site" do
page.should render('-<r:find url="/devtags/"><r:content part="unless_dev" /></r:find>-').as('--').on('dev.site.com')
end
it "should render the contained block when not on the dev site" do
page.should render('-<r:find url="/devtags/"><r:content part="unless_dev" /></r:find>-').as('-not dev-')
end
end
end
describe "<r:status>" do
it "should render the status of the current page" do
status_tag = "<r:status/>"
page(:a).should render(status_tag).as("Published")
page(:hidden).should render(status_tag).as("Hidden")
page(:draft).should render(status_tag).as("Draft")
end
describe "with the downcase attribute set to 'true'" do
it "should render the lowercased status of the current page" do
status_tag_lc = "<r:status downcase='true'/>"
page(:a).should render(status_tag_lc).as("published")
page(:hidden).should render(status_tag_lc).as("hidden")
page(:draft).should render(status_tag_lc).as("draft")
end
end
end
describe "<r:if_ancestor_or_self>" do
it "should render the tag's content when the current page is an ancestor of tag.locals.page" do
page(:radius).should render(%{<r:find url="/"><r:if_ancestor_or_self>true</r:if_ancestor_or_self></r:find>}).as('true')
end
it "should not render the tag's content when current page is not an ancestor of tag.locals.page" do
page(:parent).should render(%{<r:find url="/radius"><r:if_ancestor_or_self>true</r:if_ancestor_or_self></r:find>}).as('')
end
end
describe "<r:unless_ancestor_or_self>" do
it "should render the tag's content when the current page is not an ancestor of tag.locals.page" do
page(:parent).should render(%{<r:find url="/radius"><r:unless_ancestor_or_self>true</r:unless_ancestor_or_self></r:find>}).as('true')
end
it "should not render the tag's content when current page is an ancestor of tag.locals.page" do
page(:radius).should render(%{<r:find url="/"><r:unless_ancestor_or_self>true</r:unless_ancestor_or_self></r:find>}).as('')
end
end
describe "<r:if_self>" do
it "should render the tag's content when the current page is the same as the local contextual page" do
page(:home).should render(%{<r:find url="/"><r:if_self>true</r:if_self></r:find>}).as('true')
end
it "should not render the tag's content when the current page is not the same as the local contextual page" do
page(:radius).should render(%{<r:find url="/"><r:if_self>true</r:if_self></r:find>}).as('')
end
end
describe "<r:unless_self>" do
it "should render the tag's content when the current page is not the same as the local contextual page" do
page(:radius).should render(%{<r:find url="/"><r:unless_self>true</r:unless_self></r:find>}).as('true')
end
it "should not render the tag's content when the current page is the same as the local contextual page" do
page(:home).should render(%{<r:find url="/"><r:unless_self>true</r:unless_self></r:find>}).as('')
end
end
describe "<r:meta>" do
it "should render <meta> tags for the description and keywords" do
page(:home).should render('<r:meta/>').as(%{<meta name="description" content="The homepage" /><meta name="keywords" content="Home, Page" />})
end
it "should render <meta> tags with escaped values for the description and keywords" do
page.should render('<r:meta/>').as(%{<meta name="description" content="sweet & harmonious biscuits" /><meta name="keywords" content="sweet & harmonious biscuits" />})
end
describe "with 'tag' attribute set to 'false'" do
it "should render the contents of the description and keywords" do
page(:home).should render('<r:meta tag="false" />').as(%{The homepageHome, Page})
end
it "should escape the contents of the description and keywords" do
page.should render('<r:meta tag="false" />').as("sweet & harmonious biscuitssweet & harmonious biscuits")
end
end
end
describe "<r:meta:description>" do
it "should render a <meta> tag for the description" do
page(:home).should render('<r:meta:description/>').as(%{<meta name="description" content="The homepage" />})
end
it "should render a <meta> tag with escaped value for the description" do
page.should render('<r:meta:description />').as(%{<meta name="description" content="sweet & harmonious biscuits" />})
end
describe "with 'tag' attribute set to 'false'" do
it "should render the contents of the description" do
page(:home).should render('<r:meta:description tag="false" />').as(%{The homepage})
end
it "should escape the contents of the description" do
page.should render('<r:meta:description tag="false" />').as("sweet & harmonious biscuits")
end
end
end
describe "<r:meta:keywords>" do
it "should render a <meta> tag for the keywords" do
page(:home).should render('<r:meta:keywords/>').as(%{<meta name="keywords" content="Home, Page" />})
end
it "should render a <meta> tag with escaped value for the keywords" do
page.should render('<r:meta:keywords />').as(%{<meta name="keywords" content="sweet & harmonious biscuits" />})
end
describe "with 'tag' attribute set to 'false'" do
it "should render the contents of the keywords" do
page(:home).should render('<r:meta:keywords tag="false" />').as(%{Home, Page})
end
it "should escape the contents of the keywords" do
page.should render('<r:meta:keywords tag="false" />').as("sweet & harmonious biscuits")
end
end
end
private
def page(symbol = nil)
if symbol.nil?
@page ||= pages(:assorted)
else
@page = pages(symbol)
end
end
def page_children_each_tags(attr = nil)
attr = ' ' + attr unless attr.nil?
"<r:children:each#{attr}><r:slug /> </r:children:each>"
end
def page_children_first_tags(attr = nil)
attr = ' ' + attr unless attr.nil?
"<r:children:first#{attr}><r:slug /></r:children:first>"
end
def page_children_last_tags(attr = nil)
attr = ' ' + attr unless attr.nil?
"<r:children:last#{attr}><r:slug /></r:children:last>"
end
def page_eachable_children(page)
page.children.select(&:published?).reject(&:virtual)
end
end
|
joshfrench/radiant
|
spec/models/standard_tags_spec.rb
|
Ruby
|
mit
| 51,194 |
module ParametresHelper
end
|
Henrik41/jQuery-Validation-Engine-rails
|
thingo2/app/helpers/parametres_helper.rb
|
Ruby
|
mit
| 28 |
class CreateMappableMaps < ActiveRecord::Migration
def change
create_table :mappable_maps do |t|
t.string :subject
t.string :attr
t.string :from
t.string :to
t.timestamps
end
end
end
|
mikebannister/mappable
|
db/migrate/20110919042052_create_mappable_maps.rb
|
Ruby
|
mit
| 226 |
export function mockGlobalFile() {
// @ts-ignore
global.File = class MockFile {
name: string;
size: number;
type: string;
parts: (string | Blob | ArrayBuffer | ArrayBufferView)[];
properties?: FilePropertyBag;
lastModified: number;
constructor(
parts: (string | Blob | ArrayBuffer | ArrayBufferView)[],
name: string,
properties?: FilePropertyBag
) {
this.parts = parts;
this.name = name;
this.size = parts.join('').length;
this.type = 'txt';
this.properties = properties;
this.lastModified = 1234567890000; // Sat Feb 13 2009 23:31:30 GMT+0000.
}
};
}
export function testFile(filename: string, size: number = 42) {
return new File(['x'.repeat(size)], filename, undefined);
}
|
ProtonMail/WebClient
|
applications/drive/src/app/helpers/test/file.ts
|
TypeScript
|
mit
| 879 |
package net.talayhan.android.vibeproject.Controller;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.ipaulpro.afilechooser.utils.FileUtils;
import net.talayhan.android.vibeproject.R;
import net.talayhan.android.vibeproject.Util.Constants;
import java.io.File;
import butterknife.ButterKnife;
import butterknife.InjectView;
import cn.pedant.SweetAlert.SweetAlertDialog;
public class MainActivity extends Activity {
@InjectView(R.id.fileChooser_bt) Button mFileChooser_bt;
@InjectView(R.id.playBack_btn) Button mPlayback_bt;
@InjectView(R.id.chart_bt) Button mChart_bt;
private String videoPath;
private String vidAddress = "https://archive.org/download/ksnn_compilation_master_the_internet/ksnn_compilation_master_the_internet_512kb.mp4";
private SweetAlertDialog pDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
mFileChooser_bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
/* Progress dialog */
pDialog = new SweetAlertDialog(MainActivity.this, SweetAlertDialog.NORMAL_TYPE);
pDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
pDialog.setTitleText("Network Type");
pDialog.setContentText("How would you like to watch video?");
pDialog.setConfirmText("Local");
pDialog.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
@Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
// Local
// Create the ACTION_GET_CONTENT Intent
Intent getContentIntent = FileUtils.createGetContentIntent();
Intent intent = Intent.createChooser(getContentIntent, "Select a file");
startActivityForResult(intent, Constants.REQUEST_CHOOSER);
sweetAlertDialog.dismissWithAnimation();
}
});
pDialog.setCancelText("Internet");
pDialog.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
@Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
/* check the device network state */
if (!isOnline()){
new SweetAlertDialog(MainActivity.this, SweetAlertDialog.WARNING_TYPE)
.setContentText("Your device is now offline!\n" +
"Please open your Network.")
.setTitleText("Open Network Connection")
.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
@Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
showNoConnectionDialog(MainActivity.this);
sweetAlertDialog.dismissWithAnimation();
}
})
.show();
}else {
// Create the intent to start video activity
Intent i = new Intent(MainActivity.this, LocalVideoActivity.class);
i.putExtra(Constants.EXTRA_ANSWER_IS_TRUE, vidAddress);
startActivity(i);
sweetAlertDialog.dismissWithAnimation();
}
}
});
pDialog.setCancelable(true);
pDialog.show();
}
});
mPlayback_bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new SweetAlertDialog(MainActivity.this, SweetAlertDialog.NORMAL_TYPE)
.setContentText("Please first label some video!\n" +
"Later come back here!.")
.setTitleText("Playback")
.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
@Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
sweetAlertDialog.dismissWithAnimation();
}
})
.show();
}
});
mChart_bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, ChartRecyclerView.class);
startActivityForResult(i, Constants.REQUEST_CHART);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case Constants.REQUEST_CHOOSER:
if (resultCode == RESULT_OK) {
final Uri uri = data.getData();
// Get the File path from the Uri
String path = FileUtils.getPath(this, uri);
Toast.makeText(this, "Choosen file: " + path,Toast.LENGTH_LONG).show();
// Alternatively, use FileUtils.getFile(Context, Uri)
if (path != null && FileUtils.isLocal(path)) {
File file = new File(path);
}
// Create the intent to start video activity
Intent i = new Intent(MainActivity.this, LocalVideoActivity.class);
i.putExtra(Constants.EXTRA_ANSWER_IS_TRUE,path);
startActivity(i);
}
break;
}
}
/*
* This method checks network situation, if device is airplane mode or something went wrong on
* network stuff. Method returns false, otherwise return true.
*
* - This function inspired by below link,
* http://stackoverflow.com/questions/1560788/how-to-check-internet-access-on-android-inetaddress-never-timeouts
*
* @return boolean - network state
* * * */
public boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
/**
* Display a dialog that user has no internet connection
* @param ctx1
*
* Code from: http://osdir.com/ml/Android-Developers/2009-11/msg05044.html
*/
public static void showNoConnectionDialog(Context ctx1) {
final Context ctx = ctx1;
final SweetAlertDialog builder = new SweetAlertDialog(ctx, SweetAlertDialog.SUCCESS_TYPE);
builder.setCancelable(true);
builder.setContentText("Open internet connection");
builder.setTitle("No connection error!");
builder.setConfirmText("Open wirless.");
builder.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
@Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
ctx.startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
builder.dismissWithAnimation();
}
});
builder.show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}else if (id == R.id.action_search){
openSearch();
return true;
}
return super.onOptionsItemSelected(item);
}
private void openSearch() {
Toast.makeText(this,"Clicked Search button", Toast.LENGTH_SHORT).show();
}
}
|
stalayhan/vibeapp
|
app/src/main/java/net/talayhan/android/vibeproject/Controller/MainActivity.java
|
Java
|
mit
| 9,208 |
<?php
namespace Oro\Bundle\ApiBundle\Processor\Shared\Rest;
use Oro\Bundle\ApiBundle\Metadata\RouteLinkMetadata;
use Oro\Bundle\ApiBundle\Processor\Context;
use Oro\Bundle\ApiBundle\Provider\ResourcesProvider;
use Oro\Bundle\ApiBundle\Request\AbstractDocumentBuilder as ApiDoc;
use Oro\Bundle\ApiBundle\Request\ApiAction;
use Oro\Bundle\ApiBundle\Request\RequestType;
use Oro\Bundle\ApiBundle\Request\Rest\RestRoutesRegistry;
use Oro\Component\ChainProcessor\ContextInterface;
use Oro\Component\ChainProcessor\ProcessorInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
/**
* Adds "self" HATEOAS link to a whole document of success response.
* @link https://jsonapi.org/recommendations/#including-links
*/
class AddHateoasLinks implements ProcessorInterface
{
/** @var RestRoutesRegistry */
private $routesRegistry;
/** @var UrlGeneratorInterface */
private $urlGenerator;
/** @var ResourcesProvider */
private $resourcesProvider;
/**
* @param RestRoutesRegistry $routesRegistry
* @param UrlGeneratorInterface $urlGenerator
* @param ResourcesProvider $resourcesProvider
*/
public function __construct(
RestRoutesRegistry $routesRegistry,
UrlGeneratorInterface $urlGenerator,
ResourcesProvider $resourcesProvider
) {
$this->routesRegistry = $routesRegistry;
$this->urlGenerator = $urlGenerator;
$this->resourcesProvider = $resourcesProvider;
}
/**
* {@inheritdoc}
*/
public function process(ContextInterface $context)
{
/** @var Context $context */
$documentBuilder = $context->getResponseDocumentBuilder();
if (null === $documentBuilder || !$context->isSuccessResponse()) {
return;
}
$requestType = $context->getRequestType();
$entityClass = $context->getClassName();
if (ApiAction::GET_LIST !== $context->getAction()
&& $this->isGetListActionExcluded($entityClass, $context->getVersion(), $requestType)
) {
return;
}
$documentBuilder->addLinkMetadata(ApiDoc::LINK_SELF, new RouteLinkMetadata(
$this->urlGenerator,
$this->routesRegistry->getRoutes($requestType)->getListRouteName(),
[],
['entity' => $documentBuilder->getEntityAlias($entityClass, $requestType)]
));
}
/**
* @param string $entityClass
* @param string $version
* @param RequestType $requestType
*
* @return bool
*/
private function isGetListActionExcluded(string $entityClass, string $version, RequestType $requestType): bool
{
return \in_array(
ApiAction::GET_LIST,
$this->resourcesProvider->getResourceExcludeActions($entityClass, $version, $requestType),
true
);
}
}
|
orocrm/platform
|
src/Oro/Bundle/ApiBundle/Processor/Shared/Rest/AddHateoasLinks.php
|
PHP
|
mit
| 2,893 |
const
path = require('path'),
fs = require('fs'),
glob = require('glob'),
pug = require('pug'),
stylus = require('stylus'),
nib = require('nib'),
autoprefixer = require('autoprefixer-stylus'),
{rollup} = require('rollup'),
rollupPluginPug = require('rollup-plugin-pug'),
rollupPluginResolve = require('rollup-plugin-node-resolve'),
rollupPluginReplace = require('rollup-plugin-replace'),
rollupPluginCommonjs = require('rollup-plugin-commonjs'),
rollupPluginGlobImport = require('rollup-plugin-glob-import'),
rollupPluginAlias = require('rollup-plugin-alias'),
rollupPluginBabel = require('rollup-plugin-babel'),
sgUtil = require('./util');
class AppBuilder {
constructor(conf, CollectorStore) {
this.conf = conf;
this.CollectorStore = CollectorStore;
this.name = this.conf.get('package.name');
this.viewerDest = this.conf.get('viewerDest');
this.source = path.resolve(__dirname, '..', 'app');
this.sections = [];
this.generateViewerPages = this.generateViewerPages.bind(this);
this.generateViewerStyles = this.generateViewerStyles.bind(this);
this.rollupViewerScripts = this.rollupViewerScripts.bind(this);
this.getViewerPagesLocals = this.getViewerPagesLocals.bind(this);
this.onEnd = this.onEnd.bind(this);
}
renderCollected() {
if (!this.watcher) {
this.CollectorStore.getFiles()
.forEach(async (file) => {
if (!file.exclude) {
await file.render;
}
});
}
return this;
}
saveCollectedData() {
if (!this.watcher) {
const {viewerDest, CollectorStore: {getCollectedData}} = this;
sgUtil.writeJsonFile(path.join(viewerDest, 'structure.json'), getCollectedData());
}
}
getViewerPagesLocals() {
return {
description: this.conf.get('package.description', 'No description'),
version: this.conf.get('version', this.conf.get('package.version') || 'dev')
};
}
onEnd(message) {
return (error) => {
if (error) {
throw error;
}
sgUtil.log(`[✓] ${this.name} ${message}`, 'info');
};
}
async generateViewerPages() {
const
{source, viewerDest, getViewerPagesLocals} = this,
onEnd = this.onEnd('viewer html generated.'),
templateFile = path.join(source, 'templates', 'viewer', 'index.pug'),
renderOptions = Object.assign({
pretty: true,
cache: false
},
getViewerPagesLocals());
sgUtil.writeFile(path.join(viewerDest, 'index.html'), pug.renderFile(templateFile, renderOptions), onEnd);
}
async generateViewerStyles() {
const
{source, viewerDest} = this,
onEnd = this.onEnd('viewer css generated.'),
stylusStr = glob.sync(`${source}/style/**/!(_)*.styl`)
.map((file) => fs.readFileSync(file, 'utf8'))
.join('\n');
stylus(stylusStr)
.set('include css', true)
.set('prefix', 'dsc-')
.use(nib())
.use(autoprefixer({
browsers: ['> 5%', 'last 1 versions'],
cascade: false
}))
.include(path.join(source, 'style'))
.import('_reset')
.import('_mixins')
.import('_variables')
.render((err, css) => {
if (err) {
onEnd(err);
}
else {
sgUtil.writeFile(path.join(viewerDest, 'css', 'app.css'), css, onEnd);
}
});
}
async rollupViewerScripts() {
const
{source, viewerDest} = this,
destFile = path.join(viewerDest, 'scripts', 'app.js');
sgUtil.createPath(destFile);
try {
const bundle = await rollup({
input: path.join(source, 'scripts', 'index.js'),
plugins: [
rollupPluginGlobImport({
rename(name, id) {
if (path.basename(id) !== 'index.js') {
return null;
}
return path.basename(path.dirname(id));
}
}),
rollupPluginAlias({
vue: 'node_modules/vue/dist/vue.esm.js'
}),
rollupPluginResolve({
jsnext: true,
main: true,
module: true
}),
rollupPluginPug(),
rollupPluginReplace({
'process.env.NODE_ENV': JSON.stringify('development')
}),
rollupPluginCommonjs(),
rollupPluginBabel()
]
});
await bundle.write({
file: destFile,
format: 'iife',
sourcemap: false
});
}
catch (error) {
throw error;
}
this.onEnd('viewer js bundle generated.');
}
}
module.exports = AppBuilder;
|
stefan-lehmann/atomatic
|
lib/AppBuilder.js
|
JavaScript
|
mit
| 4,620 |
module ActiveWarehouse #:nodoc:
# Class that supports prejoining a fact table with dimensions. This is useful if you need
# to list facts along with some or all of their detail information.
class PrejoinFact
# The fact class that this engine instance is connected to
attr_accessor :fact_class
delegate :prejoined_table_name,
:connection,
:prejoined_fields,
:dimension_relationships,
:dimension_class,
:table_name,
:columns, :to => :fact_class
# Initialize the engine instance
def initialize(fact_class)
@fact_class = fact_class
end
# Populate the prejoined fact table.
def populate(options={})
populate_prejoined_fact_table(options)
end
protected
# Drop the storage table
def drop_prejoin_fact_table
connection.drop_table(prejoined_table_name) if connection.tables.include?(prejoined_table_name)
end
# Get foreign key names that are excluded.
def excluded_foreign_key_names
excluded_dimension_relations = prejoined_fields.keys.collect {|k| dimension_relationships[k]}
excluded_dimension_relations.collect {|r| r.foreign_key}
end
# Construct the prejoined fact table.
def create_prejoined_fact_table(options={})
connection.transaction {
drop_prejoin_fact_table
connection.create_table(prejoined_table_name, :id => false) do |t|
# get all columns except the foreign_key columns for prejoined dimensions
columns.each do |c|
t.column(c.name, c.type) unless excluded_foreign_key_names.include?(c.name)
end
#prejoined_columns
prejoined_fields.each_pair do |key, value|
dclass = dimension_class(key)
dclass.columns.each do |c|
t.column(c.name, c.type) if value.include?(c.name.to_sym)
end
end
end
}
end
# Populate the prejoined fact table.
def populate_prejoined_fact_table(options={})
fact_columns_string = columns.collect {|c|
"#{table_name}." + c.name unless excluded_foreign_key_names.include?(c.name)
}.compact.join(",\n")
prejoined_columns = []
tables_and_joins = "#{table_name}"
prejoined_fields.each_pair do |key, value|
dimension = dimension_class(key)
tables_and_joins += "\nJOIN #{dimension.table_name} as #{key}"
tables_and_joins += "\n ON #{table_name}.#{dimension_relationships[key].foreign_key} = "
tables_and_joins += "#{key}.#{dimension.primary_key}"
prejoined_columns << value.collect {|v| "#{key}." + v.to_s}
end
if connection.support_select_into_table?
drop_prejoin_fact_table
sql = <<-SQL
SELECT #{fact_columns_string},
#{prejoined_columns.join(",\n")}
FROM #{tables_and_joins}
SQL
sql = connection.add_select_into_table(prejoined_table_name, sql)
else
create_prejoined_fact_table(options)
sql = <<-SQL
INSERT INTO #{prejoined_table_name}
SELECT #{fact_columns_string},
#{prejoined_columns.join(",\n")}
FROM #{tables_and_joins}
SQL
end
connection.transaction { connection.execute(sql) }
end
end
end
|
activewarehouse/activewarehouse
|
lib/active_warehouse/prejoin_fact.rb
|
Ruby
|
mit
| 3,448 |
package utils;
import java.io.*;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ueb01.StringBufferImpl;
/**
* Created with IntelliJ IDEA.
* User: Julian
* Date: 16.10.13
* Time: 13:37
*/
public class Utils {
private static long currentTime;
/**
* http://svn.apache.org/viewvc/camel/trunk/components/camel-test/src/main/java/org/apache/camel/test/AvailablePortFinder.java?view=markup#l130
* Checks to see if a specific port is available.
*
* @param port the port to check for availability
*/
public static boolean available(int port) {
ServerSocket ss = null;
DatagramSocket ds = null;
try {
ss = new ServerSocket(port);
ss.setReuseAddress(true);
ds = new DatagramSocket(port);
ds.setReuseAddress(true);
return true;
} catch (IOException e) {
} finally {
if (ds != null) {
ds.close();
}
if (ss != null) {
try {
ss.close();
} catch (IOException e) {
/* should not be thrown */
}
}
}
return false;
}
public static void stopwatchStart() {
currentTime = java.lang.System.nanoTime();
}
static ExecutorService pool = null;
public static class SyncTcpResponse {
public final Socket socket;
public final String message;
public boolean isValid() {
return this.socket != null;
}
public SyncTcpResponse(Socket s, String m) {
this.socket = s;
this.message = m;
}
}
public static String getTCPSync(final Socket socket) {
StringBuilder sb = new StringBuilder();
try {
Scanner s = new Scanner(socket.getInputStream());
while (s.hasNext()) {
sb.append(s.next());
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
public static SyncTcpResponse getTCPSync(final int port) {
ServerSocket server = null;
Socket client = null;
StringBuilder sb = new StringBuilder();
try {
server = new ServerSocket(port);
client = server.accept();
Scanner s = new Scanner(client.getInputStream());
while (s.hasNext()) {
sb.append(s.next());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (server != null) try {
server.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return new SyncTcpResponse(client, sb.toString());
}
public static Future<String> getTCP(final int port) {
if (pool == null) {
pool = Executors.newCachedThreadPool();
}
return pool.submit(new Callable<String>() {
@Override
public String call() throws Exception {
ServerSocket server = null;
/*try(ServerSocket socket = new ServerSocket(port)){
Socket client = socket.accept();
Scanner s = new Scanner(client.getInputStream());
StringBuilder sb = new StringBuilder();
while (s.hasNext()){
sb.append(s.next());
}
return sb.toString();
} */
return null;
}
});
}
public static Socket sendTCP(InetAddress address, int port, String message) {
try {
Socket s = new Socket(address, port);
return sendTCP(s, message);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static Socket sendTCP(Socket socket, String message) {
PrintWriter out = null;
try {
out = new PrintWriter(socket.getOutputStream());
out.println(message);
out.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
out.close();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return socket;
}
public static void close() {
if (pool != null) {
pool.shutdown();
}
}
public static String wordFromScanner(Scanner scanner) {
StringBuilder result = new StringBuilder();
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
result.append(line);
result.append("\n");
}
return result.toString();
}
public static String[] wordsFromScanner(Scanner scanner) {
List<String> result = new ArrayList<String>();
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] words = line.split(" ");
for (String word : words) {
if (word.length() > 0)
result.add(wordify(word));
}
}
return Utils.<String>listToArrayStr(result);
}
public static String wordify(String word) {
return word.replace(",", "").replace(".", "").replace("'", "").replace("\"", "")
.replace("...", "").replace("!", "").replace(";", "").replace(":", "").toLowerCase();
}
public static <T> T[] listToArray(List<T> list) {
T[] result = (T[]) new Object[list.size()];
for (int i = 0; i < list.size(); i++) {
result[i] = list.get(i);
}
return result;
}
public static String[] listToArrayStr(List<String> list) {
String[] result = new String[list.size()];
for (int i = 0; i < list.size(); i++) {
result[i] = list.get(i);
}
return result;
}
public static void stopwatchEnd() {
long current = java.lang.System.nanoTime();
long dif = current - currentTime;
long millis = dif / 1000000;
System.out.println("Millis: {" + millis + "} Nanos: {" + dif + "}");
}
/**
* Method to send a command to a Process
*
* @param p
* @param command
*/
public static void send(Process p, String command) {
OutputStream os = p.getOutputStream();
try {
os.write(command.getBytes());
} catch (IOException e) {
System.out.println("something went wrong... [Utils.send(..) -> " + e.getMessage());
} finally {
try {
os.close();
} catch (IOException e) {
System.out.println("something went wrong while closing... [Utils.send(..) -> " + e.getMessage());
}
}
}
public static void close(Process p) {
try {
p.getOutputStream().close();
p.getInputStream().close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* easy exceptionless sleep
*
* @param millis
*/
public static void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("ALP5: Utils::sleep crashed..");
}
}
public static int countCharactersInFile(String fileName) {
BufferedReader br = null;
try {
StringBuilder sb = new StringBuilder();
br = new BufferedReader(new FileReader(fileName));
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
}
return sb.length();
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("shit happens... @Utils.countCharactersInFile");
return -1;
} catch (IOException e) {
e.printStackTrace();
System.out.println("shit happens while reading... @Utils.countCharactersInFile");
} finally {
if (br != null) try {
br.close();
} catch (IOException e) {
e.printStackTrace();
return -2;
}
}
return -3;
}
public static String join(String[] l, String connector) {
StringBuilder sb = new StringBuilder();
for (String s : l) {
if (sb.length() > 0) {
sb.append(connector);
}
sb.append(s);
}
return sb.toString();
}
public static String readFromStream(InputStream is){
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
/**
* Method to receive the output of a Process
*
* @param p
* @return
*/
public static String read(Process p) {
StringBuilder sb = new StringBuilder();
InputStream is = p.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String s = null;
try {
while ((s = reader.readLine()) != null) {
if (s.equals("") || s.equals(" ")) break;
sb.append(s);
}
} catch (IOException e) {
System.out.println("something went wrong... [Utils.read(..) -> " + e.getMessage());
}
return sb.toString();
}
public static void main(String[] args) throws IOException, InterruptedException {
System.out.println("yyy");
System.out.println('a' > 'b');
}
/**
* If you want to use your ssh-key-login, you need to generate a pem-File from
* the ssh-private-key and put it into the main folder ( ALP5/ ); You also need
* to define the user with @ (like: jutanke@peking.imp.fu-berlin.de:...)
*
* @param commandId
* @return
*/
public static Process fork(String commandId) {
String username = null; // HARDCODE ME!
String password = null; // HARDCODE ME!
String host = null;
String command = commandId;
if (commandId.contains(":")) {
String[] temp = commandId.split(":");
if (temp[0].length() > 2) {
// if the host is shorter its probably just a windows drive ('d:// ...')
host = temp[0];
if (host.contains("@")) {
String[] t = host.split("@");
username = t[0];
host = t[1];
}
if (temp.length == 3) {
command = temp[1] + ":" + temp[2]; // to "repair" windows drives...
} else {
command = temp[1];
}
}
}
if (host != null) {
Process remoteP = null;
try {
final Connection conn = new Connection(host);
conn.connect();
boolean isAuth = false;
if (password != null) {
isAuth = conn.authenticateWithPassword(username, password);
}
if (!isAuth) {
File f = new File("private.pem");
isAuth = conn.authenticateWithPublicKey(username, f, "");
if (!isAuth) return null;
}
final Session sess = conn.openSession();
sess.execCommand(command);
remoteP = new Process() {
@Override
public OutputStream getOutputStream() {
return sess.getStdin();
}
@Override
public InputStream getInputStream() {
return sess.getStdout();
}
@Override
public InputStream getErrorStream() {
return sess.getStderr();
}
@Override
public int waitFor() throws InterruptedException {
sess.wait();
return 0;
}
@Override
public int exitValue() {
return 0;
}
@Override
public void destroy() {
sess.close();
conn.close();
}
};
} catch (IOException e) {
System.out.println("shit happens with the ssh connection: @Utils.fork .. " + e.getMessage());
return null;
}
return remoteP;
}
ProcessBuilder b = new ProcessBuilder(command.split(" "));
try {
return b.start();
} catch (IOException e) {
System.out.println("shit happens: @Utils.fork .. " + e.getMessage());
}
return null;
}
}
|
justayak/ALP5
|
src/utils/Utils.java
|
Java
|
mit
| 14,112 |
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { onUnexpectedError } from 'vs/base/common/errors';
import { IDisposable } from 'vs/base/common/lifecycle';
import { URI, UriComponents } from 'vs/base/common/uri';
import { EditOperation } from 'vs/editor/common/core/editOperation';
import { Range } from 'vs/editor/common/core/range';
import { ITextModel } from 'vs/editor/common/model';
import { IEditorWorkerService } from 'vs/editor/common/services/editorWorkerService';
import { IModelService } from 'vs/editor/common/services/modelService';
import { IModeService } from 'vs/editor/common/services/modeService';
import { ITextModelService } from 'vs/editor/common/services/resolverService';
import { extHostNamedCustomer } from 'vs/workbench/api/electron-browser/extHostCustomers';
import { ExtHostContext, ExtHostDocumentContentProvidersShape, IExtHostContext, MainContext, MainThreadDocumentContentProvidersShape } from '../node/extHost.protocol';
import { CancellationTokenSource } from 'vs/base/common/cancellation';
@extHostNamedCustomer(MainContext.MainThreadDocumentContentProviders)
export class MainThreadDocumentContentProviders implements MainThreadDocumentContentProvidersShape {
private readonly _resourceContentProvider = new Map<number, IDisposable>();
private readonly _pendingUpdate = new Map<string, CancellationTokenSource>();
private readonly _proxy: ExtHostDocumentContentProvidersShape;
constructor(
extHostContext: IExtHostContext,
@ITextModelService private readonly _textModelResolverService: ITextModelService,
@IModeService private readonly _modeService: IModeService,
@IModelService private readonly _modelService: IModelService,
@IEditorWorkerService private readonly _editorWorkerService: IEditorWorkerService
) {
this._proxy = extHostContext.getProxy(ExtHostContext.ExtHostDocumentContentProviders);
}
dispose(): void {
this._resourceContentProvider.forEach(p => p.dispose());
this._pendingUpdate.forEach(source => source.dispose());
}
$registerTextContentProvider(handle: number, scheme: string): void {
const registration = this._textModelResolverService.registerTextModelContentProvider(scheme, {
provideTextContent: (uri: URI): Thenable<ITextModel> => {
return this._proxy.$provideTextDocumentContent(handle, uri).then(value => {
if (typeof value === 'string') {
const firstLineText = value.substr(0, 1 + value.search(/\r?\n/));
const languageSelection = this._modeService.createByFilepathOrFirstLine(uri.fsPath, firstLineText);
return this._modelService.createModel(value, languageSelection, uri);
}
return undefined;
});
}
});
this._resourceContentProvider.set(handle, registration);
}
$unregisterTextContentProvider(handle: number): void {
const registration = this._resourceContentProvider.get(handle);
if (registration) {
registration.dispose();
this._resourceContentProvider.delete(handle);
}
}
$onVirtualDocumentChange(uri: UriComponents, value: string): void {
const model = this._modelService.getModel(URI.revive(uri));
if (!model) {
return;
}
// cancel and dispose an existing update
if (this._pendingUpdate.has(model.id)) {
this._pendingUpdate.get(model.id).cancel();
}
// create and keep update token
const myToken = new CancellationTokenSource();
this._pendingUpdate.set(model.id, myToken);
this._editorWorkerService.computeMoreMinimalEdits(model.uri, [{ text: value, range: model.getFullModelRange() }]).then(edits => {
// remove token
this._pendingUpdate.delete(model.id);
if (myToken.token.isCancellationRequested) {
// ignore this
return;
}
if (edits.length > 0) {
// use the evil-edit as these models show in readonly-editor only
model.applyEdits(edits.map(edit => EditOperation.replace(Range.lift(edit.range), edit.text)));
}
}).catch(onUnexpectedError);
}
}
|
DustinCampbell/vscode
|
src/vs/workbench/api/electron-browser/mainThreadDocumentContentProviders.ts
|
TypeScript
|
mit
| 4,197 |
//---------------------------------------------------------------------------
//
// <copyright file="ByteAnimationUsingKeyFrames.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// This file was generated, please do not edit it directly.
//
// Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information.
//
//---------------------------------------------------------------------------
using MS.Internal;
using MS.Internal.KnownBoxes;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows;
using System.Windows.Markup;
using System.Windows.Media.Animation;
using System.Windows.Media.Media3D;
using SR=MS.Internal.PresentationCore.SR;
using SRID=MS.Internal.PresentationCore.SRID;
using MS.Internal.PresentationCore;
namespace System.Windows.Media.Animation
{
/// <summary>
/// This class is used to animate a Byte property value along a set
/// of key frames.
/// </summary>
[ContentProperty("KeyFrames")]
public class ByteAnimationUsingKeyFrames : ByteAnimationBase, IKeyFrameAnimation, IAddChild
{
#region Data
private ByteKeyFrameCollection _keyFrames;
private ResolvedKeyFrameEntry[] _sortedResolvedKeyFrames;
private bool _areKeyTimesValid;
#endregion
#region Constructors
/// <Summary>
/// Creates a new KeyFrameByteAnimation.
/// </Summary>
public ByteAnimationUsingKeyFrames()
: base()
{
_areKeyTimesValid = true;
}
#endregion
#region Freezable
/// <summary>
/// Creates a copy of this KeyFrameByteAnimation.
/// </summary>
/// <returns>The copy</returns>
public new ByteAnimationUsingKeyFrames Clone()
{
return (ByteAnimationUsingKeyFrames)base.Clone();
}
/// <summary>
/// Returns a version of this class with all its base property values
/// set to the current animated values and removes the animations.
/// </summary>
/// <returns>
/// Since this class isn't animated, this method will always just return
/// this instance of the class.
/// </returns>
public new ByteAnimationUsingKeyFrames CloneCurrentValue()
{
return (ByteAnimationUsingKeyFrames)base.CloneCurrentValue();
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.FreezeCore">Freezable.FreezeCore</see>.
/// </summary>
protected override bool FreezeCore(bool isChecking)
{
bool canFreeze = base.FreezeCore(isChecking);
canFreeze &= Freezable.Freeze(_keyFrames, isChecking);
if (canFreeze & !_areKeyTimesValid)
{
ResolveKeyTimes();
}
return canFreeze;
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.OnChanged">Freezable.OnChanged</see>.
/// </summary>
protected override void OnChanged()
{
_areKeyTimesValid = false;
base.OnChanged();
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new ByteAnimationUsingKeyFrames();
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CloneCore(System.Windows.Freezable)">Freezable.CloneCore</see>.
/// </summary>
protected override void CloneCore(Freezable sourceFreezable)
{
ByteAnimationUsingKeyFrames sourceAnimation = (ByteAnimationUsingKeyFrames) sourceFreezable;
base.CloneCore(sourceFreezable);
CopyCommon(sourceAnimation, /* isCurrentValueClone = */ false);
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CloneCurrentValueCore(Freezable)">Freezable.CloneCurrentValueCore</see>.
/// </summary>
protected override void CloneCurrentValueCore(Freezable sourceFreezable)
{
ByteAnimationUsingKeyFrames sourceAnimation = (ByteAnimationUsingKeyFrames) sourceFreezable;
base.CloneCurrentValueCore(sourceFreezable);
CopyCommon(sourceAnimation, /* isCurrentValueClone = */ true);
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.GetAsFrozenCore(Freezable)">Freezable.GetAsFrozenCore</see>.
/// </summary>
protected override void GetAsFrozenCore(Freezable source)
{
ByteAnimationUsingKeyFrames sourceAnimation = (ByteAnimationUsingKeyFrames) source;
base.GetAsFrozenCore(source);
CopyCommon(sourceAnimation, /* isCurrentValueClone = */ false);
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.GetCurrentValueAsFrozenCore(Freezable)">Freezable.GetCurrentValueAsFrozenCore</see>.
/// </summary>
protected override void GetCurrentValueAsFrozenCore(Freezable source)
{
ByteAnimationUsingKeyFrames sourceAnimation = (ByteAnimationUsingKeyFrames) source;
base.GetCurrentValueAsFrozenCore(source);
CopyCommon(sourceAnimation, /* isCurrentValueClone = */ true);
}
/// <summary>
/// Helper used by the four Freezable clone methods to copy the resolved key times and
/// key frames. The Get*AsFrozenCore methods are implemented the same as the Clone*Core
/// methods; Get*AsFrozen at the top level will recursively Freeze so it's not done here.
/// </summary>
/// <param name="sourceAnimation"></param>
/// <param name="isCurrentValueClone"></param>
private void CopyCommon(ByteAnimationUsingKeyFrames sourceAnimation, bool isCurrentValueClone)
{
_areKeyTimesValid = sourceAnimation._areKeyTimesValid;
if ( _areKeyTimesValid
&& sourceAnimation._sortedResolvedKeyFrames != null)
{
// _sortedResolvedKeyFrames is an array of ResolvedKeyFrameEntry so the notion of CurrentValueClone doesn't apply
_sortedResolvedKeyFrames = (ResolvedKeyFrameEntry[])sourceAnimation._sortedResolvedKeyFrames.Clone();
}
if (sourceAnimation._keyFrames != null)
{
if (isCurrentValueClone)
{
_keyFrames = (ByteKeyFrameCollection)sourceAnimation._keyFrames.CloneCurrentValue();
}
else
{
_keyFrames = (ByteKeyFrameCollection)sourceAnimation._keyFrames.Clone();
}
OnFreezablePropertyChanged(null, _keyFrames);
}
}
#endregion // Freezable
#region IAddChild interface
/// <summary>
/// Adds a child object to this KeyFrameAnimation.
/// </summary>
/// <param name="child">
/// The child object to add.
/// </param>
/// <remarks>
/// A KeyFrameAnimation only accepts a KeyFrame of the proper type as
/// a child.
/// </remarks>
void IAddChild.AddChild(object child)
{
WritePreamble();
if (child == null)
{
throw new ArgumentNullException("child");
}
AddChild(child);
WritePostscript();
}
/// <summary>
/// Implemented to allow KeyFrames to be direct children
/// of KeyFrameAnimations in markup.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void AddChild(object child)
{
ByteKeyFrame keyFrame = child as ByteKeyFrame;
if (keyFrame != null)
{
KeyFrames.Add(keyFrame);
}
else
{
throw new ArgumentException(SR.Get(SRID.Animation_ChildMustBeKeyFrame), "child");
}
}
/// <summary>
/// Adds a text string as a child of this KeyFrameAnimation.
/// </summary>
/// <param name="childText">
/// The text to add.
/// </param>
/// <remarks>
/// A KeyFrameAnimation does not accept text as a child, so this method will
/// raise an InvalididOperationException unless a derived class has
/// overridden the behavior to add text.
/// </remarks>
/// <exception cref="ArgumentNullException">The childText parameter is
/// null.</exception>
void IAddChild.AddText(string childText)
{
if (childText == null)
{
throw new ArgumentNullException("childText");
}
AddText(childText);
}
/// <summary>
/// This method performs the core functionality of the AddText()
/// method on the IAddChild interface. For a KeyFrameAnimation this means
/// throwing and InvalidOperationException because it doesn't
/// support adding text.
/// </summary>
/// <remarks>
/// This method is the only core implementation. It does not call
/// WritePreamble() or WritePostscript(). It also doesn't throw an
/// ArgumentNullException if the childText parameter is null. These tasks
/// are performed by the interface implementation. Therefore, it's OK
/// for a derived class to override this method and call the base
/// class implementation only if they determine that it's the right
/// course of action. The derived class can rely on KeyFrameAnimation's
/// implementation of IAddChild.AddChild or implement their own
/// following the Freezable pattern since that would be a public
/// method.
/// </remarks>
/// <param name="childText">A string representing the child text that
/// should be added. If this is a KeyFrameAnimation an exception will be
/// thrown.</param>
/// <exception cref="InvalidOperationException">Timelines have no way
/// of adding text.</exception>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void AddText(string childText)
{
throw new InvalidOperationException(SR.Get(SRID.Animation_NoTextChildren));
}
#endregion
#region ByteAnimationBase
/// <summary>
/// Calculates the value this animation believes should be the current value for the property.
/// </summary>
/// <param name="defaultOriginValue">
/// This value is the suggested origin value provided to the animation
/// to be used if the animation does not have its own concept of a
/// start value. If this animation is the first in a composition chain
/// this value will be the snapshot value if one is available or the
/// base property value if it is not; otherise this value will be the
/// value returned by the previous animation in the chain with an
/// animationClock that is not Stopped.
/// </param>
/// <param name="defaultDestinationValue">
/// This value is the suggested destination value provided to the animation
/// to be used if the animation does not have its own concept of an
/// end value. This value will be the base value if the animation is
/// in the first composition layer of animations on a property;
/// otherwise this value will be the output value from the previous
/// composition layer of animations for the property.
/// </param>
/// <param name="animationClock">
/// This is the animationClock which can generate the CurrentTime or
/// CurrentProgress value to be used by the animation to generate its
/// output value.
/// </param>
/// <returns>
/// The value this animation believes should be the current value for the property.
/// </returns>
protected sealed override Byte GetCurrentValueCore(
Byte defaultOriginValue,
Byte defaultDestinationValue,
AnimationClock animationClock)
{
Debug.Assert(animationClock.CurrentState != ClockState.Stopped);
if (_keyFrames == null)
{
return defaultDestinationValue;
}
// We resolved our KeyTimes when we froze, but also got notified
// of the frozen state and therefore invalidated ourselves.
if (!_areKeyTimesValid)
{
ResolveKeyTimes();
}
if (_sortedResolvedKeyFrames == null)
{
return defaultDestinationValue;
}
TimeSpan currentTime = animationClock.CurrentTime.Value;
Int32 keyFrameCount = _sortedResolvedKeyFrames.Length;
Int32 maxKeyFrameIndex = keyFrameCount - 1;
Byte currentIterationValue;
Debug.Assert(maxKeyFrameIndex >= 0, "maxKeyFrameIndex is less than zero which means we don't actually have any key frames.");
Int32 currentResolvedKeyFrameIndex = 0;
// Skip all the key frames with key times lower than the current time.
// currentResolvedKeyFrameIndex will be greater than maxKeyFrameIndex
// if we are past the last key frame.
while ( currentResolvedKeyFrameIndex < keyFrameCount
&& currentTime > _sortedResolvedKeyFrames[currentResolvedKeyFrameIndex]._resolvedKeyTime)
{
currentResolvedKeyFrameIndex++;
}
// If there are multiple key frames at the same key time, be sure to go to the last one.
while ( currentResolvedKeyFrameIndex < maxKeyFrameIndex
&& currentTime == _sortedResolvedKeyFrames[currentResolvedKeyFrameIndex + 1]._resolvedKeyTime)
{
currentResolvedKeyFrameIndex++;
}
if (currentResolvedKeyFrameIndex == keyFrameCount)
{
// Past the last key frame.
currentIterationValue = GetResolvedKeyFrameValue(maxKeyFrameIndex);
}
else if (currentTime == _sortedResolvedKeyFrames[currentResolvedKeyFrameIndex]._resolvedKeyTime)
{
// Exactly on a key frame.
currentIterationValue = GetResolvedKeyFrameValue(currentResolvedKeyFrameIndex);
}
else
{
// Between two key frames.
Double currentSegmentProgress = 0.0;
Byte fromValue;
if (currentResolvedKeyFrameIndex == 0)
{
// The current key frame is the first key frame so we have
// some special rules for determining the fromValue and an
// optimized method of calculating the currentSegmentProgress.
// If we're additive we want the base value to be a zero value
// so that if there isn't a key frame at time 0.0, we'll use
// the zero value for the time 0.0 value and then add that
// later to the base value.
if (IsAdditive)
{
fromValue = AnimatedTypeHelpers.GetZeroValueByte(defaultOriginValue);
}
else
{
fromValue = defaultOriginValue;
}
// Current segment time divided by the segment duration.
// Note: the reason this works is that we know that we're in
// the first segment, so we can assume:
//
// currentTime.TotalMilliseconds = current segment time
// _sortedResolvedKeyFrames[0]._resolvedKeyTime.TotalMilliseconds = current segment duration
currentSegmentProgress = currentTime.TotalMilliseconds
/ _sortedResolvedKeyFrames[0]._resolvedKeyTime.TotalMilliseconds;
}
else
{
Int32 previousResolvedKeyFrameIndex = currentResolvedKeyFrameIndex - 1;
TimeSpan previousResolvedKeyTime = _sortedResolvedKeyFrames[previousResolvedKeyFrameIndex]._resolvedKeyTime;
fromValue = GetResolvedKeyFrameValue(previousResolvedKeyFrameIndex);
TimeSpan segmentCurrentTime = currentTime - previousResolvedKeyTime;
TimeSpan segmentDuration = _sortedResolvedKeyFrames[currentResolvedKeyFrameIndex]._resolvedKeyTime - previousResolvedKeyTime;
currentSegmentProgress = segmentCurrentTime.TotalMilliseconds
/ segmentDuration.TotalMilliseconds;
}
currentIterationValue = GetResolvedKeyFrame(currentResolvedKeyFrameIndex).InterpolateValue(fromValue, currentSegmentProgress);
}
// If we're cumulative, we need to multiply the final key frame
// value by the current repeat count and add this to the return
// value.
if (IsCumulative)
{
Double currentRepeat = (Double)(animationClock.CurrentIteration - 1);
if (currentRepeat > 0.0)
{
currentIterationValue = AnimatedTypeHelpers.AddByte(
currentIterationValue,
AnimatedTypeHelpers.ScaleByte(GetResolvedKeyFrameValue(maxKeyFrameIndex), currentRepeat));
}
}
// If we're additive we need to add the base value to the return value.
if (IsAdditive)
{
return AnimatedTypeHelpers.AddByte(defaultOriginValue, currentIterationValue);
}
return currentIterationValue;
}
/// <summary>
/// Provide a custom natural Duration when the Duration property is set to Automatic.
/// </summary>
/// <param name="clock">
/// The Clock whose natural duration is desired.
/// </param>
/// <returns>
/// If the last KeyFrame of this animation is a KeyTime, then this will
/// be used as the NaturalDuration; otherwise it will be one second.
/// </returns>
protected override sealed Duration GetNaturalDurationCore(Clock clock)
{
return new Duration(LargestTimeSpanKeyTime);
}
#endregion
#region IKeyFrameAnimation
/// <summary>
/// Returns the ByteKeyFrameCollection used by this KeyFrameByteAnimation.
/// </summary>
IList IKeyFrameAnimation.KeyFrames
{
get
{
return KeyFrames;
}
set
{
KeyFrames = (ByteKeyFrameCollection)value;
}
}
/// <summary>
/// Returns the ByteKeyFrameCollection used by this KeyFrameByteAnimation.
/// </summary>
public ByteKeyFrameCollection KeyFrames
{
get
{
ReadPreamble();
// The reason we don't just set _keyFrames to the empty collection
// in the first place is that null tells us that the user has not
// asked for the collection yet. The first time they ask for the
// collection and we're unfrozen, policy dictates that we give
// them a new unfrozen collection. All subsequent times they will
// get whatever collection is present, whether frozen or unfrozen.
if (_keyFrames == null)
{
if (this.IsFrozen)
{
_keyFrames = ByteKeyFrameCollection.Empty;
}
else
{
WritePreamble();
_keyFrames = new ByteKeyFrameCollection();
OnFreezablePropertyChanged(null, _keyFrames);
WritePostscript();
}
}
return _keyFrames;
}
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
WritePreamble();
if (value != _keyFrames)
{
OnFreezablePropertyChanged(_keyFrames, value);
_keyFrames = value;
WritePostscript();
}
}
}
/// <summary>
/// Returns true if we should serialize the KeyFrames, property for this Animation.
/// </summary>
/// <returns>True if we should serialize the KeyFrames property for this Animation; otherwise false.</returns>
[EditorBrowsable(EditorBrowsableState.Never)]
public bool ShouldSerializeKeyFrames()
{
ReadPreamble();
return _keyFrames != null
&& _keyFrames.Count > 0;
}
#endregion
#region Public Properties
/// <summary>
/// If this property is set to true, this animation will add its value
/// to the base value or the value of the previous animation in the
/// composition chain. Another way of saying this is that the units
/// specified in the animation are relative to the base value rather
/// than absolute units.
/// </summary>
/// <remarks>
/// In the case where the first key frame's resolved key time is not
/// 0.0 there is slightly different behavior between KeyFrameByteAnimations
/// with IsAdditive set and without. Animations with the property set to false
/// will behave as if there is a key frame at time 0.0 with the value of the
/// base value. Animations with the property set to true will behave as if
/// there is a key frame at time 0.0 with a zero value appropriate to the type
/// of the animation. These behaviors provide the results most commonly expected
/// and can be overridden by simply adding a key frame at time 0.0 with the preferred value.
/// </remarks>
public bool IsAdditive
{
get
{
return (bool)GetValue(IsAdditiveProperty);
}
set
{
SetValueInternal(IsAdditiveProperty, BooleanBoxes.Box(value));
}
}
/// <summary>
/// If this property is set to true, the value of this animation will
/// accumulate over repeat cycles. For example, if this is a point
/// animation and your key frames describe something approximating and
/// arc, setting this property to true will result in an animation that
/// would appear to bounce the point across the screen.
/// </summary>
/// <remarks>
/// This property works along with the IsAdditive property. Setting
/// this value to true has no effect unless IsAdditive is also set
/// to true.
/// </remarks>
public bool IsCumulative
{
get
{
return (bool)GetValue(IsCumulativeProperty);
}
set
{
SetValueInternal(IsCumulativeProperty, BooleanBoxes.Box(value));
}
}
#endregion
#region Private Methods
private struct KeyTimeBlock
{
public int BeginIndex;
public int EndIndex;
}
private Byte GetResolvedKeyFrameValue(Int32 resolvedKeyFrameIndex)
{
Debug.Assert(_areKeyTimesValid, "The key frames must be resolved and sorted before calling GetResolvedKeyFrameValue");
return GetResolvedKeyFrame(resolvedKeyFrameIndex).Value;
}
private ByteKeyFrame GetResolvedKeyFrame(Int32 resolvedKeyFrameIndex)
{
Debug.Assert(_areKeyTimesValid, "The key frames must be resolved and sorted before calling GetResolvedKeyFrame");
return _keyFrames[_sortedResolvedKeyFrames[resolvedKeyFrameIndex]._originalKeyFrameIndex];
}
/// <summary>
/// Returns the largest time span specified key time from all of the key frames.
/// If there are not time span key times a time span of one second is returned
/// to match the default natural duration of the From/To/By animations.
/// </summary>
private TimeSpan LargestTimeSpanKeyTime
{
get
{
bool hasTimeSpanKeyTime = false;
TimeSpan largestTimeSpanKeyTime = TimeSpan.Zero;
if (_keyFrames != null)
{
Int32 keyFrameCount = _keyFrames.Count;
for (int index = 0; index < keyFrameCount; index++)
{
KeyTime keyTime = _keyFrames[index].KeyTime;
if (keyTime.Type == KeyTimeType.TimeSpan)
{
hasTimeSpanKeyTime = true;
if (keyTime.TimeSpan > largestTimeSpanKeyTime)
{
largestTimeSpanKeyTime = keyTime.TimeSpan;
}
}
}
}
if (hasTimeSpanKeyTime)
{
return largestTimeSpanKeyTime;
}
else
{
return TimeSpan.FromSeconds(1.0);
}
}
}
private void ResolveKeyTimes()
{
Debug.Assert(!_areKeyTimesValid, "KeyFrameByteAnimaton.ResolveKeyTimes() shouldn't be called if the key times are already valid.");
int keyFrameCount = 0;
if (_keyFrames != null)
{
keyFrameCount = _keyFrames.Count;
}
if (keyFrameCount == 0)
{
_sortedResolvedKeyFrames = null;
_areKeyTimesValid = true;
return;
}
_sortedResolvedKeyFrames = new ResolvedKeyFrameEntry[keyFrameCount];
int index = 0;
// Initialize the _originalKeyFrameIndex.
for ( ; index < keyFrameCount; index++)
{
_sortedResolvedKeyFrames[index]._originalKeyFrameIndex = index;
}
// calculationDuration represents the time span we will use to resolve
// percent key times. This is defined as the value in the following
// precedence order:
// 1. The animation's duration, but only if it is a time span, not auto or forever.
// 2. The largest time span specified key time of all the key frames.
// 3. 1 second, to match the From/To/By animations.
TimeSpan calculationDuration = TimeSpan.Zero;
Duration duration = Duration;
if (duration.HasTimeSpan)
{
calculationDuration = duration.TimeSpan;
}
else
{
calculationDuration = LargestTimeSpanKeyTime;
}
int maxKeyFrameIndex = keyFrameCount - 1;
ArrayList unspecifiedBlocks = new ArrayList();
bool hasPacedKeyTimes = false;
//
// Pass 1: Resolve Percent and Time key times.
//
index = 0;
while (index < keyFrameCount)
{
KeyTime keyTime = _keyFrames[index].KeyTime;
switch (keyTime.Type)
{
case KeyTimeType.Percent:
_sortedResolvedKeyFrames[index]._resolvedKeyTime = TimeSpan.FromMilliseconds(
keyTime.Percent * calculationDuration.TotalMilliseconds);
index++;
break;
case KeyTimeType.TimeSpan:
_sortedResolvedKeyFrames[index]._resolvedKeyTime = keyTime.TimeSpan;
index++;
break;
case KeyTimeType.Paced:
case KeyTimeType.Uniform:
if (index == maxKeyFrameIndex)
{
// If the last key frame doesn't have a specific time
// associated with it its resolved key time will be
// set to the calculationDuration, which is the
// defined in the comments above where it is set.
// Reason: We only want extra time at the end of the
// key frames if the user specifically states that
// the last key frame ends before the animation ends.
_sortedResolvedKeyFrames[index]._resolvedKeyTime = calculationDuration;
index++;
}
else if ( index == 0
&& keyTime.Type == KeyTimeType.Paced)
{
// Note: It's important that this block come after
// the previous if block because of rule precendence.
// If the first key frame in a multi-frame key frame
// collection is paced, we set its resolved key time
// to 0.0 for performance reasons. If we didn't, the
// resolved key time list would be dependent on the
// base value which can change every animation frame
// in many cases.
_sortedResolvedKeyFrames[index]._resolvedKeyTime = TimeSpan.Zero;
index++;
}
else
{
if (keyTime.Type == KeyTimeType.Paced)
{
hasPacedKeyTimes = true;
}
KeyTimeBlock block = new KeyTimeBlock();
block.BeginIndex = index;
// NOTE: We don't want to go all the way up to the
// last frame because if it is Uniform or Paced its
// resolved key time will be set to the calculation
// duration using the logic above.
//
// This is why the logic is:
// ((++index) < maxKeyFrameIndex)
// instead of:
// ((++index) < keyFrameCount)
while ((++index) < maxKeyFrameIndex)
{
KeyTimeType type = _keyFrames[index].KeyTime.Type;
if ( type == KeyTimeType.Percent
|| type == KeyTimeType.TimeSpan)
{
break;
}
else if (type == KeyTimeType.Paced)
{
hasPacedKeyTimes = true;
}
}
Debug.Assert(index < keyFrameCount,
"The end index for a block of unspecified key frames is out of bounds.");
block.EndIndex = index;
unspecifiedBlocks.Add(block);
}
break;
}
}
//
// Pass 2: Resolve Uniform key times.
//
for (int j = 0; j < unspecifiedBlocks.Count; j++)
{
KeyTimeBlock block = (KeyTimeBlock)unspecifiedBlocks[j];
TimeSpan blockBeginTime = TimeSpan.Zero;
if (block.BeginIndex > 0)
{
blockBeginTime = _sortedResolvedKeyFrames[block.BeginIndex - 1]._resolvedKeyTime;
}
// The number of segments is equal to the number of key
// frames we're working on plus 1. Think about the case
// where we're working on a single key frame. There's a
// segment before it and a segment after it.
//
// Time known Uniform Time known
// ^ ^ ^
// | | |
// | (segment 1) | (segment 2) |
Int64 segmentCount = (block.EndIndex - block.BeginIndex) + 1;
TimeSpan uniformTimeStep = TimeSpan.FromTicks((_sortedResolvedKeyFrames[block.EndIndex]._resolvedKeyTime - blockBeginTime).Ticks / segmentCount);
index = block.BeginIndex;
TimeSpan resolvedTime = blockBeginTime + uniformTimeStep;
while (index < block.EndIndex)
{
_sortedResolvedKeyFrames[index]._resolvedKeyTime = resolvedTime;
resolvedTime += uniformTimeStep;
index++;
}
}
//
// Pass 3: Resolve Paced key times.
//
if (hasPacedKeyTimes)
{
ResolvePacedKeyTimes();
}
//
// Sort resolved key frame entries.
//
Array.Sort(_sortedResolvedKeyFrames);
_areKeyTimesValid = true;
return;
}
/// <summary>
/// This should only be called from ResolveKeyTimes and only at the
/// appropriate time.
/// </summary>
private void ResolvePacedKeyTimes()
{
Debug.Assert(_keyFrames != null && _keyFrames.Count > 2,
"Caller must guard against calling this method when there are insufficient keyframes.");
// If the first key frame is paced its key time has already
// been resolved, so we start at index 1.
int index = 1;
int maxKeyFrameIndex = _sortedResolvedKeyFrames.Length - 1;
do
{
if (_keyFrames[index].KeyTime.Type == KeyTimeType.Paced)
{
//
// We've found a paced key frame so this is the
// beginning of a paced block.
//
// The first paced key frame in this block.
int firstPacedBlockKeyFrameIndex = index;
// List of segment lengths for this paced block.
List<Double> segmentLengths = new List<Double>();
// The resolved key time for the key frame before this
// block which we'll use as our starting point.
TimeSpan prePacedBlockKeyTime = _sortedResolvedKeyFrames[index - 1]._resolvedKeyTime;
// The total of the segment lengths of the paced key
// frames in this block.
Double totalLength = 0.0;
// The key value of the previous key frame which will be
// used to determine the segment length of this key frame.
Byte prevKeyValue = _keyFrames[index - 1].Value;
do
{
Byte currentKeyValue = _keyFrames[index].Value;
// Determine the segment length for this key frame and
// add to the total length.
totalLength += AnimatedTypeHelpers.GetSegmentLengthByte(prevKeyValue, currentKeyValue);
// Temporarily store the distance into the total length
// that this key frame represents in the resolved
// key times array to be converted to a resolved key
// time outside of this loop.
segmentLengths.Add(totalLength);
// Prepare for the next iteration.
prevKeyValue = currentKeyValue;
index++;
}
while ( index < maxKeyFrameIndex
&& _keyFrames[index].KeyTime.Type == KeyTimeType.Paced);
// index is currently set to the index of the key frame
// after the last paced key frame. This will always
// be a valid index because we limit ourselves with
// maxKeyFrameIndex.
// We need to add the distance between the last paced key
// frame and the next key frame to get the total distance
// inside the key frame block.
totalLength += AnimatedTypeHelpers.GetSegmentLengthByte(prevKeyValue, _keyFrames[index].Value);
// Calculate the time available in the resolved key time space.
TimeSpan pacedBlockDuration = _sortedResolvedKeyFrames[index]._resolvedKeyTime - prePacedBlockKeyTime;
// Convert lengths in segmentLengths list to resolved
// key times for the paced key frames in this block.
for (int i = 0, currentKeyFrameIndex = firstPacedBlockKeyFrameIndex; i < segmentLengths.Count; i++, currentKeyFrameIndex++)
{
// The resolved key time for each key frame is:
//
// The key time of the key frame before this paced block
// + ((the percentage of the way through the total length)
// * the resolved key time space available for the block)
_sortedResolvedKeyFrames[currentKeyFrameIndex]._resolvedKeyTime = prePacedBlockKeyTime + TimeSpan.FromMilliseconds(
(segmentLengths[i] / totalLength) * pacedBlockDuration.TotalMilliseconds);
}
}
else
{
index++;
}
}
while (index < maxKeyFrameIndex);
}
#endregion
}
}
|
mind0n/hive
|
Cache/Libs/net46/wpf/src/Core/CSharp/System/Windows/Media/Animation/Generated/ByteAnimationUsingKeyFrames.cs
|
C#
|
mit
| 39,816 |
'use strict';
const Hoek = require('hoek');
exports.plugin = {
register: async (plugin, options) => {
plugin.ext('onPreResponse', (request, h) => {
try {
var internals = {
devEnv: (process.env.NODE_ENV === 'development'),
meta: options.meta,
credentials: request.auth.isAuthenticated ? request.auth.credentials : null
};
var response = request.response;
if (response.variety && response.variety === 'view') {
response.source.context = Hoek.merge(internals, request.response.source.context);
}
return h.continue;
} catch (error) {
throw error;
}
});
},
pkg: require('../package.json'),
name: 'context'
};
|
SystangoTechnologies/Hapiness
|
lib/context.js
|
JavaScript
|
mit
| 672 |
'use strict';
//Customers service used to communicate Customers REST endpoints
angular.module('customers')
.factory('Customers', ['$resource',
function($resource) {
return $resource('customers/:customerId', { customerId: '@_id'
}, {
update: {
method: 'PUT'
}
});
}
])
.factory('Notify', ['$rootScope', function($rootScope) {
var notify = {};
notify.sendMsg = function(msg, data) {
data = data || {};
$rootScope.$emit(msg, data);
console.log('message sent!');
};
notify.getMsg = function(msg, func, scope) {
var unbind = $rootScope.$on(msg, func);
if (scope) {
scope.$on('destroy', unbind);
}
};
return notify;
}
]);
|
armackey/spa_practice
|
public/modules/customers/services/customers.client.service.js
|
JavaScript
|
mit
| 724 |
/* some devices call home before accepting a wifi access point. Spoof those responses. */
var path = require('path');
exports.load = function(server, boatData, settings) {
var endpointMap = [
{'route': '/kindle-wifi/wifiredirect.html', 'responseFile': 'kindle.html'} ,
{'route': '/kindle-wifi/wifistub.html', 'responseFile': 'kindle.html'} //http://spectrum.s3.amazonaws.com
];
_.each(endpointMap, function(endpoint) {
server.get(endpoint.route, function(req, res) {
res.sendFile(path.join(__dirname + endpoint.responseFile));
});
});
};
|
HomegrownMarine/boat_computer
|
apps/wifi_allow/app.js
|
JavaScript
|
mit
| 603 |
class AlbumsController < ApplicationController
respond_to :html, :xml, :json
attr_reader :current_album_type, :author_name
load_and_authorize_resource
def index
@albums = Album.by_type params[:album_type]
respond_with(@albums)
end
def show
get_current_album_type
get_author_name
if @current_album_type.name.singularize == 'Picture'
@album_pictures = @album.pictures.paginate(:page => params[:page], :per_page => 12)
elsif @current_album_type.name.singularize == 'Video'
@album_videos = @album.videos.paginate(:page => params[:page], :per_page => 12)
end
respond_with(@album)
end
def new
@album.album_type_id = params[:album_type]
get_current_album_type
respond_with(@album)
end
def edit
get_current_album_type
respond_with(@album)
end
def create
@album.user_id = user_signed_in? ? current_user.id : 0
flash[:notice] = 'Album was successfully created.' if @album.save
get_current_album_type
respond_with(@album)
end
def update
@album.update_attributes(params[:album])
respond_with(@album)
end
def destroy
@album.destroy
flash[:notice] = 'Successfully destroyed album.'
redirect_to albums_path(:album_type => @album.album_type_id)
end
private
def get_current_album_type
@current_album_type = AlbumType.all.find { |album_type| album_type.id == @album.album_type_id }
end
def get_author_name
@author_name = (@album.user_id > 0) \
? User.find { |user| user.id == @album.user_id }.name \
: 'Anonymous'
end
end
|
quattro004/scratches
|
app/controllers/albums_controller.rb
|
Ruby
|
mit
| 1,594 |
// フォーマット
var koyomi = require('../..').create();
var format = koyomi.format.bind(koyomi);
var eq = require('assert').equal;
koyomi.startMonth = 1;
// 序数 (CC:経過日数)
eq(format(20150101, 'CC'), '1');
eq(format(20150101, 'CC>0'), '1st');
eq(format(20150102, 'CC>0'), '2nd');
eq(format(20150103, 'CC>0'), '3rd');
eq(format(20150104, 'CC>0'), '4th');
eq(format(20150105, 'CC>0'), '5th');
eq(format(20150106, 'CC>0'), '6th');
eq(format(20150107, 'CC>0'), '7th');
eq(format(20150108, 'CC>0'), '8th');
eq(format(20150109, 'CC>0'), '9th');
eq(format(20150110, 'CC>0'), '10th');
eq(format(20150111, 'CC>0'), '11th');
eq(format(20150112, 'CC>0'), '12th');
eq(format(20150113, 'CC>0'), '13th');
eq(format(20150114, 'CC>0'), '14th');
eq(format(20150115, 'CC>0'), '15th');
eq(format(20150116, 'CC>0'), '16th');
eq(format(20150117, 'CC>0'), '17th');
eq(format(20150118, 'CC>0'), '18th');
eq(format(20150119, 'CC>0'), '19th');
eq(format(20150120, 'CC>0'), '20th');
eq(format(20150121, 'CC>0'), '21st');
eq(format(20150122, 'CC>0'), '22nd');
eq(format(20150123, 'CC>0'), '23rd');
eq(format(20150124, 'CC>0'), '24th');
eq(format(20150125, 'CC>0'), '25th');
eq(format(20150126, 'CC>0'), '26th');
eq(format(20150127, 'CC>0'), '27th');
eq(format(20150128, 'CC>0'), '28th');
eq(format(20150129, 'CC>0'), '29th');
eq(format(20150130, 'CC>0'), '30th');
eq(format(20150131, 'CC>0'), '31st');
eq(format(20150201, 'CC>0'), '32nd');
eq(format(20150202, 'CC>0'), '33rd');
eq(format(20150203, 'CC>0'), '34th');
eq(format(20150204, 'CC>0'), '35th');
eq(format(20150205, 'CC>0'), '36th');
eq(format(20150206, 'CC>0'), '37th');
eq(format(20150207, 'CC>0'), '38th');
eq(format(20150208, 'CC>0'), '39th');
eq(format(20150209, 'CC>0'), '40th');
eq(format(20150210, 'CC>0'), '41st');
eq(format(20150211, 'CC>0'), '42nd');
eq(format(20150212, 'CC>0'), '43rd');
eq(format(20150213, 'CC>0'), '44th');
eq(format(20150214, 'CC>0'), '45th');
eq(format(20150215, 'CC>0'), '46th');
eq(format(20150216, 'CC>0'), '47th');
eq(format(20150217, 'CC>0'), '48th');
eq(format(20150218, 'CC>0'), '49th');
eq(format(20150219, 'CC>0'), '50th');
eq(format(20150220, 'CC>0'), '51st');
eq(format(20150221, 'CC>0'), '52nd');
eq(format(20150222, 'CC>0'), '53rd');
eq(format(20150223, 'CC>0'), '54th');
eq(format(20150224, 'CC>0'), '55th');
eq(format(20150225, 'CC>0'), '56th');
eq(format(20150226, 'CC>0'), '57th');
eq(format(20150227, 'CC>0'), '58th');
eq(format(20150228, 'CC>0'), '59th');
eq(format(20150301, 'CC>0'), '60th');
eq(format(20150302, 'CC>0'), '61st');
eq(format(20150303, 'CC>0'), '62nd');
eq(format(20150304, 'CC>0'), '63rd');
eq(format(20150305, 'CC>0'), '64th');
eq(format(20150306, 'CC>0'), '65th');
eq(format(20150307, 'CC>0'), '66th');
eq(format(20150308, 'CC>0'), '67th');
eq(format(20150309, 'CC>0'), '68th');
eq(format(20150310, 'CC>0'), '69th');
eq(format(20150311, 'CC>0'), '70th');
eq(format(20150312, 'CC>0'), '71st');
eq(format(20150313, 'CC>0'), '72nd');
eq(format(20150314, 'CC>0'), '73rd');
eq(format(20150315, 'CC>0'), '74th');
eq(format(20150316, 'CC>0'), '75th');
eq(format(20150317, 'CC>0'), '76th');
eq(format(20150318, 'CC>0'), '77th');
eq(format(20150319, 'CC>0'), '78th');
eq(format(20150320, 'CC>0'), '79th');
eq(format(20150321, 'CC>0'), '80th');
eq(format(20150322, 'CC>0'), '81st');
eq(format(20150323, 'CC>0'), '82nd');
eq(format(20150324, 'CC>0'), '83rd');
eq(format(20150325, 'CC>0'), '84th');
eq(format(20150326, 'CC>0'), '85th');
eq(format(20150327, 'CC>0'), '86th');
eq(format(20150328, 'CC>0'), '87th');
eq(format(20150329, 'CC>0'), '88th');
eq(format(20150330, 'CC>0'), '89th');
eq(format(20150331, 'CC>0'), '90th');
eq(format(20150401, 'CC>0'), '91st');
eq(format(20150402, 'CC>0'), '92nd');
eq(format(20150403, 'CC>0'), '93rd');
eq(format(20150404, 'CC>0'), '94th');
eq(format(20150405, 'CC>0'), '95th');
eq(format(20150406, 'CC>0'), '96th');
eq(format(20150407, 'CC>0'), '97th');
eq(format(20150408, 'CC>0'), '98th');
eq(format(20150409, 'CC>0'), '99th');
eq(format(20150410, 'CC>0'), '100th');
eq(format(20150411, 'CC>0'), '101st');
eq(format(20150412, 'CC>0'), '102nd');
eq(format(20150413, 'CC>0'), '103rd');
eq(format(20150414, 'CC>0'), '104th');
eq(format(20150415, 'CC>0'), '105th');
eq(format(20150416, 'CC>0'), '106th');
eq(format(20150417, 'CC>0'), '107th');
eq(format(20150418, 'CC>0'), '108th');
eq(format(20150419, 'CC>0'), '109th');
eq(format(20150420, 'CC>0'), '110th');
eq(format(20150421, 'CC>0'), '111th');
eq(format(20150422, 'CC>0'), '112th');
eq(format(20150423, 'CC>0'), '113th');
eq(format(20150424, 'CC>0'), '114th');
eq(format(20150425, 'CC>0'), '115th');
eq(format(20150426, 'CC>0'), '116th');
eq(format(20150427, 'CC>0'), '117th');
eq(format(20150428, 'CC>0'), '118th');
eq(format(20150429, 'CC>0'), '119th');
eq(format(20150430, 'CC>0'), '120th');
eq(format(20150501, 'CC>0'), '121st');
eq(format(20150502, 'CC>0'), '122nd');
eq(format(20150503, 'CC>0'), '123rd');
eq(format(20150504, 'CC>0'), '124th');
eq(format(20150505, 'CC>0'), '125th');
eq(format(20150506, 'CC>0'), '126th');
eq(format(20150507, 'CC>0'), '127th');
eq(format(20150508, 'CC>0'), '128th');
eq(format(20150509, 'CC>0'), '129th');
eq(format(20150510, 'CC>0'), '130th');
eq(format(20150511, 'CC>0'), '131st');
eq(format(20150512, 'CC>0'), '132nd');
eq(format(20150513, 'CC>0'), '133rd');
eq(format(20150514, 'CC>0'), '134th');
eq(format(20150515, 'CC>0'), '135th');
eq(format(20150516, 'CC>0'), '136th');
eq(format(20150517, 'CC>0'), '137th');
eq(format(20150518, 'CC>0'), '138th');
eq(format(20150519, 'CC>0'), '139th');
eq(format(20150520, 'CC>0'), '140th');
eq(format(20150521, 'CC>0'), '141st');
eq(format(20150522, 'CC>0'), '142nd');
eq(format(20150523, 'CC>0'), '143rd');
eq(format(20150524, 'CC>0'), '144th');
eq(format(20150525, 'CC>0'), '145th');
eq(format(20150526, 'CC>0'), '146th');
eq(format(20150527, 'CC>0'), '147th');
eq(format(20150528, 'CC>0'), '148th');
eq(format(20150529, 'CC>0'), '149th');
eq(format(20150530, 'CC>0'), '150th');
eq(format(20150531, 'CC>0'), '151st');
eq(format(20150601, 'CC>0'), '152nd');
eq(format(20150602, 'CC>0'), '153rd');
eq(format(20150603, 'CC>0'), '154th');
eq(format(20150604, 'CC>0'), '155th');
eq(format(20150605, 'CC>0'), '156th');
eq(format(20150606, 'CC>0'), '157th');
eq(format(20150607, 'CC>0'), '158th');
eq(format(20150608, 'CC>0'), '159th');
eq(format(20150609, 'CC>0'), '160th');
eq(format(20150610, 'CC>0'), '161st');
eq(format(20150611, 'CC>0'), '162nd');
eq(format(20150612, 'CC>0'), '163rd');
eq(format(20150613, 'CC>0'), '164th');
eq(format(20150614, 'CC>0'), '165th');
eq(format(20150615, 'CC>0'), '166th');
eq(format(20150616, 'CC>0'), '167th');
eq(format(20150617, 'CC>0'), '168th');
eq(format(20150618, 'CC>0'), '169th');
eq(format(20150619, 'CC>0'), '170th');
eq(format(20150620, 'CC>0'), '171st');
eq(format(20150621, 'CC>0'), '172nd');
eq(format(20150622, 'CC>0'), '173rd');
eq(format(20150623, 'CC>0'), '174th');
eq(format(20150624, 'CC>0'), '175th');
eq(format(20150625, 'CC>0'), '176th');
eq(format(20150626, 'CC>0'), '177th');
eq(format(20150627, 'CC>0'), '178th');
eq(format(20150628, 'CC>0'), '179th');
eq(format(20150629, 'CC>0'), '180th');
eq(format(20150630, 'CC>0'), '181st');
eq(format(20150701, 'CC>0'), '182nd');
eq(format(20150702, 'CC>0'), '183rd');
eq(format(20150703, 'CC>0'), '184th');
eq(format(20150704, 'CC>0'), '185th');
eq(format(20150705, 'CC>0'), '186th');
eq(format(20150706, 'CC>0'), '187th');
eq(format(20150707, 'CC>0'), '188th');
eq(format(20150708, 'CC>0'), '189th');
eq(format(20150709, 'CC>0'), '190th');
eq(format(20150710, 'CC>0'), '191st');
eq(format(20150711, 'CC>0'), '192nd');
eq(format(20150712, 'CC>0'), '193rd');
eq(format(20150713, 'CC>0'), '194th');
eq(format(20150714, 'CC>0'), '195th');
eq(format(20150715, 'CC>0'), '196th');
eq(format(20150716, 'CC>0'), '197th');
eq(format(20150717, 'CC>0'), '198th');
eq(format(20150718, 'CC>0'), '199th');
eq(format(20150719, 'CC>0'), '200th');
eq(format(20150720, 'CC>0'), '201st');
eq(format(20150721, 'CC>0'), '202nd');
eq(format(20150722, 'CC>0'), '203rd');
eq(format(20150723, 'CC>0'), '204th');
eq(format(20150724, 'CC>0'), '205th');
eq(format(20150725, 'CC>0'), '206th');
eq(format(20150726, 'CC>0'), '207th');
eq(format(20150727, 'CC>0'), '208th');
eq(format(20150728, 'CC>0'), '209th');
eq(format(20150729, 'CC>0'), '210th');
eq(format(20150730, 'CC>0'), '211th');
eq(format(20150731, 'CC>0'), '212th');
eq(format(20150801, 'CC>0'), '213th');
eq(format(20150802, 'CC>0'), '214th');
eq(format(20150803, 'CC>0'), '215th');
eq(format(20150804, 'CC>0'), '216th');
eq(format(20150805, 'CC>0'), '217th');
eq(format(20150806, 'CC>0'), '218th');
eq(format(20150807, 'CC>0'), '219th');
eq(format(20150808, 'CC>0'), '220th');
eq(format(20150809, 'CC>0'), '221st');
eq(format(20150810, 'CC>0'), '222nd');
eq(format(20150811, 'CC>0'), '223rd');
eq(format(20150812, 'CC>0'), '224th');
eq(format(20150813, 'CC>0'), '225th');
eq(format(20150814, 'CC>0'), '226th');
eq(format(20150815, 'CC>0'), '227th');
eq(format(20150816, 'CC>0'), '228th');
eq(format(20150817, 'CC>0'), '229th');
eq(format(20150818, 'CC>0'), '230th');
eq(format(20150819, 'CC>0'), '231st');
eq(format(20150820, 'CC>0'), '232nd');
eq(format(20150821, 'CC>0'), '233rd');
eq(format(20150822, 'CC>0'), '234th');
eq(format(20150823, 'CC>0'), '235th');
eq(format(20150824, 'CC>0'), '236th');
eq(format(20150825, 'CC>0'), '237th');
eq(format(20150826, 'CC>0'), '238th');
eq(format(20150827, 'CC>0'), '239th');
eq(format(20150828, 'CC>0'), '240th');
eq(format(20150829, 'CC>0'), '241st');
eq(format(20150830, 'CC>0'), '242nd');
eq(format(20150831, 'CC>0'), '243rd');
eq(format(20150901, 'CC>0'), '244th');
eq(format(20150902, 'CC>0'), '245th');
eq(format(20150903, 'CC>0'), '246th');
eq(format(20150904, 'CC>0'), '247th');
eq(format(20150905, 'CC>0'), '248th');
eq(format(20150906, 'CC>0'), '249th');
eq(format(20150907, 'CC>0'), '250th');
eq(format(20150908, 'CC>0'), '251st');
eq(format(20150909, 'CC>0'), '252nd');
eq(format(20150910, 'CC>0'), '253rd');
eq(format(20150911, 'CC>0'), '254th');
eq(format(20150912, 'CC>0'), '255th');
eq(format(20150913, 'CC>0'), '256th');
eq(format(20150914, 'CC>0'), '257th');
eq(format(20150915, 'CC>0'), '258th');
eq(format(20150916, 'CC>0'), '259th');
eq(format(20150917, 'CC>0'), '260th');
eq(format(20150918, 'CC>0'), '261st');
eq(format(20150919, 'CC>0'), '262nd');
eq(format(20150920, 'CC>0'), '263rd');
eq(format(20150921, 'CC>0'), '264th');
eq(format(20150922, 'CC>0'), '265th');
eq(format(20150923, 'CC>0'), '266th');
eq(format(20150924, 'CC>0'), '267th');
eq(format(20150925, 'CC>0'), '268th');
eq(format(20150926, 'CC>0'), '269th');
eq(format(20150927, 'CC>0'), '270th');
eq(format(20150928, 'CC>0'), '271st');
eq(format(20150929, 'CC>0'), '272nd');
eq(format(20150930, 'CC>0'), '273rd');
eq(format(20151001, 'CC>0'), '274th');
eq(format(20151002, 'CC>0'), '275th');
eq(format(20151003, 'CC>0'), '276th');
eq(format(20151004, 'CC>0'), '277th');
eq(format(20151005, 'CC>0'), '278th');
eq(format(20151006, 'CC>0'), '279th');
eq(format(20151007, 'CC>0'), '280th');
eq(format(20151008, 'CC>0'), '281st');
eq(format(20151009, 'CC>0'), '282nd');
eq(format(20151010, 'CC>0'), '283rd');
eq(format(20151011, 'CC>0'), '284th');
eq(format(20151012, 'CC>0'), '285th');
eq(format(20151013, 'CC>0'), '286th');
eq(format(20151014, 'CC>0'), '287th');
eq(format(20151015, 'CC>0'), '288th');
eq(format(20151016, 'CC>0'), '289th');
eq(format(20151017, 'CC>0'), '290th');
eq(format(20151018, 'CC>0'), '291st');
eq(format(20151019, 'CC>0'), '292nd');
eq(format(20151020, 'CC>0'), '293rd');
eq(format(20151021, 'CC>0'), '294th');
eq(format(20151022, 'CC>0'), '295th');
eq(format(20151023, 'CC>0'), '296th');
eq(format(20151024, 'CC>0'), '297th');
eq(format(20151025, 'CC>0'), '298th');
eq(format(20151026, 'CC>0'), '299th');
eq(format(20151027, 'CC>0'), '300th');
eq(format(20151028, 'CC>0'), '301st');
eq(format(20151029, 'CC>0'), '302nd');
eq(format(20151030, 'CC>0'), '303rd');
eq(format(20151031, 'CC>0'), '304th');
eq(format(20151101, 'CC>0'), '305th');
eq(format(20151102, 'CC>0'), '306th');
eq(format(20151103, 'CC>0'), '307th');
eq(format(20151104, 'CC>0'), '308th');
eq(format(20151105, 'CC>0'), '309th');
eq(format(20151106, 'CC>0'), '310th');
eq(format(20151107, 'CC>0'), '311th');
eq(format(20151108, 'CC>0'), '312th');
eq(format(20151109, 'CC>0'), '313th');
eq(format(20151110, 'CC>0'), '314th');
eq(format(20151111, 'CC>0'), '315th');
eq(format(20151112, 'CC>0'), '316th');
eq(format(20151113, 'CC>0'), '317th');
eq(format(20151114, 'CC>0'), '318th');
eq(format(20151115, 'CC>0'), '319th');
eq(format(20151116, 'CC>0'), '320th');
eq(format(20151117, 'CC>0'), '321st');
eq(format(20151118, 'CC>0'), '322nd');
eq(format(20151119, 'CC>0'), '323rd');
eq(format(20151120, 'CC>0'), '324th');
eq(format(20151121, 'CC>0'), '325th');
eq(format(20151122, 'CC>0'), '326th');
eq(format(20151123, 'CC>0'), '327th');
eq(format(20151124, 'CC>0'), '328th');
eq(format(20151125, 'CC>0'), '329th');
eq(format(20151126, 'CC>0'), '330th');
eq(format(20151127, 'CC>0'), '331st');
eq(format(20151128, 'CC>0'), '332nd');
eq(format(20151129, 'CC>0'), '333rd');
eq(format(20151130, 'CC>0'), '334th');
eq(format(20151201, 'CC>0'), '335th');
eq(format(20151202, 'CC>0'), '336th');
eq(format(20151203, 'CC>0'), '337th');
eq(format(20151204, 'CC>0'), '338th');
eq(format(20151205, 'CC>0'), '339th');
eq(format(20151206, 'CC>0'), '340th');
eq(format(20151207, 'CC>0'), '341st');
eq(format(20151208, 'CC>0'), '342nd');
eq(format(20151209, 'CC>0'), '343rd');
eq(format(20151210, 'CC>0'), '344th');
eq(format(20151211, 'CC>0'), '345th');
eq(format(20151212, 'CC>0'), '346th');
eq(format(20151213, 'CC>0'), '347th');
eq(format(20151214, 'CC>0'), '348th');
eq(format(20151215, 'CC>0'), '349th');
eq(format(20151216, 'CC>0'), '350th');
eq(format(20151217, 'CC>0'), '351st');
eq(format(20151218, 'CC>0'), '352nd');
eq(format(20151219, 'CC>0'), '353rd');
eq(format(20151220, 'CC>0'), '354th');
eq(format(20151221, 'CC>0'), '355th');
eq(format(20151222, 'CC>0'), '356th');
eq(format(20151223, 'CC>0'), '357th');
eq(format(20151224, 'CC>0'), '358th');
eq(format(20151225, 'CC>0'), '359th');
eq(format(20151226, 'CC>0'), '360th');
eq(format(20151227, 'CC>0'), '361st');
eq(format(20151228, 'CC>0'), '362nd');
eq(format(20151229, 'CC>0'), '363rd');
eq(format(20151230, 'CC>0'), '364th');
eq(format(20151231, 'CC>0'), '365th');
// 文字列の序数
eq(format(20150101, 'GG>0'), '平成');
eq(format(20000101, 'y>0'), '00th');
eq(format(20010101, 'y>0'), '01st');
|
yukik/koyomi
|
test/format/josu.js
|
JavaScript
|
mit
| 14,614 |
import { apiGet, apiPut, apiDelete } from 'utils/api'
import { flashError, flashSuccess } from 'utils/flash'
import { takeLatest, takeEvery, call, put, select } from 'redux-saga/effects'
import { filter, find, without, omit } from 'lodash'
import { filesUrlSelector } from 'ducks/app'
import { makeUploadsSelector } from 'ducks/uploads'
import { makeFiltersQuerySelector } from 'ducks/filters'
import { makeSelectedFileIdsSelector } from 'ducks/filePlacements'
// Constants
const GET_FILES = 'files/GET_FILES'
const GET_FILES_SUCCESS = 'files/GET_FILES_SUCCESS'
const UPLOADED_FILE = 'files/UPLOADED_FILE'
const THUMBNAIL_GENERATED = 'files/THUMBNAIL_GENERATED'
const DELETE_FILE = 'files/DELETE_FILE'
const DELETE_FILE_FAILURE = 'files/DELETE_FILE_FAILURE'
const UPDATE_FILE = 'files/UPDATE_FILE'
export const UPDATE_FILE_SUCCESS = 'files/UPDATE_FILE_SUCCESS'
export const UPDATE_FILE_FAILURE = 'files/UPDATE_FILE_FAILURE'
const UPDATED_FILES = 'files/UPDATED_FILES'
const REMOVED_FILES = 'files/REMOVED_FILES'
const CHANGE_FILES_PAGE = 'files/CHANGE_FILES_PAGE'
const MASS_SELECT = 'files/MASS_SELECT'
const MASS_DELETE = 'files/MASS_DELETE'
const MASS_CANCEL = 'files/MASS_CANCEL'
// Actions
export function getFiles (fileType, filesUrl, query = '') {
return { type: GET_FILES, fileType, filesUrl, query }
}
export function getFilesSuccess (fileType, records, meta) {
return { type: GET_FILES_SUCCESS, fileType, records, meta }
}
export function uploadedFile (fileType, file) {
return { type: UPLOADED_FILE, fileType, file }
}
export function thumbnailGenerated (fileType, temporaryUrl, url) {
return { type: THUMBNAIL_GENERATED, fileType, temporaryUrl, url }
}
export function updatedFiles (fileType, files) {
return { type: UPDATED_FILES, fileType, files }
}
export function updateFile (fileType, filesUrl, file, attributes) {
return { type: UPDATE_FILE, fileType, filesUrl, file, attributes }
}
export function deleteFile (fileType, filesUrl, file) {
return { type: DELETE_FILE, fileType, filesUrl, file }
}
export function deleteFileFailure (fileType, file) {
return { type: DELETE_FILE_FAILURE, fileType, file }
}
export function removedFiles (fileType, ids) {
return { type: REMOVED_FILES, fileType, ids }
}
export function updateFileSuccess (fileType, file, response) {
return { type: UPDATE_FILE_SUCCESS, fileType, file, response }
}
export function updateFileFailure (fileType, file) {
return { type: UPDATE_FILE_FAILURE, fileType, file }
}
export function changeFilesPage (fileType, filesUrl, page) {
return { type: CHANGE_FILES_PAGE, fileType, filesUrl, page }
}
export function massSelect (fileType, file, select) {
return { type: MASS_SELECT, fileType, file, select }
}
export function massDelete (fileType) {
return { type: MASS_DELETE, fileType }
}
export function massCancel (fileType) {
return { type: MASS_CANCEL, fileType }
}
// Sagas
function * getFilesPerform (action) {
try {
const filesUrl = `${action.filesUrl}?${action.query}`
const response = yield call(apiGet, filesUrl)
yield put(getFilesSuccess(action.fileType, response.data, response.meta))
} catch (e) {
flashError(e.message)
}
}
function * getFilesSaga () {
// takeLatest automatically cancels any saga task started previously if it's still running
yield takeLatest(GET_FILES, getFilesPerform)
}
function * updateFilePerform (action) {
try {
const { file, filesUrl, attributes } = action
const fullUrl = `${filesUrl}/${file.id}`
const data = {
file: {
id: file.id,
attributes
}
}
const response = yield call(apiPut, fullUrl, data)
yield put(updateFileSuccess(action.fileType, action.file, response.data))
} catch (e) {
flashError(e.message)
yield put(updateFileFailure(action.fileType, action.file))
}
}
function * updateFileSaga () {
yield takeEvery(UPDATE_FILE, updateFilePerform)
}
function * changeFilesPagePerform (action) {
try {
const filtersQuery = yield select(makeFiltersQuerySelector(action.fileType))
let query = `page=${action.page}`
if (filtersQuery) {
query = `${query}&${filtersQuery}`
}
yield put(getFiles(action.fileType, action.filesUrl, query))
} catch (e) {
flashError(e.message)
}
}
function * changeFilesPageSaga () {
yield takeLatest(CHANGE_FILES_PAGE, changeFilesPagePerform)
}
function * massDeletePerform (action) {
try {
const { massSelectedIds } = yield select(makeMassSelectedIdsSelector(action.fileType))
const filesUrl = yield select(filesUrlSelector)
const fullUrl = `${filesUrl}/mass_destroy?ids=${massSelectedIds.join(',')}`
const res = yield call(apiDelete, fullUrl)
if (res.error) {
flashError(res.error)
} else {
flashSuccess(res.data.message)
yield put(removedFiles(action.fileType, massSelectedIds))
yield put(massCancel(action.fileType))
}
} catch (e) {
flashError(e.message)
}
}
function * massDeleteSaga () {
yield takeLatest(MASS_DELETE, massDeletePerform)
}
function * deleteFilePerform (action) {
try {
const res = yield call(apiDelete, `${action.filesUrl}/${action.file.id}`)
if (res.error) {
flashError(res.error)
} else {
yield put(removedFiles(action.fileType, [action.file.id]))
}
} catch (e) {
flashError(e.message)
}
}
function * deleteFileSaga () {
yield takeLatest(DELETE_FILE, deleteFilePerform)
}
export const filesSagas = [
getFilesSaga,
updateFileSaga,
changeFilesPageSaga,
massDeleteSaga,
deleteFileSaga
]
// Selectors
export const makeFilesStatusSelector = (fileType) => (state) => {
return {
loading: state.files[fileType] && state.files[fileType].loading,
loaded: state.files[fileType] && state.files[fileType].loaded,
massSelecting: state.files[fileType].massSelectedIds.length > 0
}
}
export const makeFilesLoadedSelector = (fileType) => (state) => {
return state.files[fileType] && state.files[fileType].loaded
}
export const makeMassSelectedIdsSelector = (fileType) => (state) => {
const base = state.files[fileType] || defaultFilesKeyState
return {
massSelectedIds: base.massSelectedIds,
massSelectedIndestructibleIds: base.massSelectedIndestructibleIds
}
}
export const makeFilesSelector = (fileType) => (state) => {
const base = state.files[fileType] || defaultFilesKeyState
const selected = base.massSelectedIds
return base.records.map((file) => {
if (file.id && selected.indexOf(file.id) !== -1) {
return { ...file, massSelected: true }
} else {
return file
}
})
}
export const makeFilesForListSelector = (fileType) => (state) => {
const uploads = makeUploadsSelector(fileType)(state)
let files
if (uploads.uploadedIds.length) {
files = makeFilesSelector(fileType)(state).map((file) => {
if (uploads.uploadedIds.indexOf(file.id) === -1) {
return file
} else {
return { ...file, attributes: { ...file.attributes, freshlyUploaded: true } }
}
})
} else {
files = makeFilesSelector(fileType)(state)
}
return [
...Object.values(uploads.records).map((upload) => ({ ...upload, attributes: { ...upload.attributes, uploading: true } })),
...files
]
}
export const makeRawUnselectedFilesForListSelector = (fileType, selectedIds) => (state) => {
const all = makeFilesForListSelector(fileType)(state)
return filter(all, (file) => selectedIds.indexOf(String(file.id)) === -1)
}
export const makeUnselectedFilesForListSelector = (fileType) => (state) => {
const all = makeFilesForListSelector(fileType)(state)
const selectedIds = makeSelectedFileIdsSelector(fileType)(state)
return filter(all, (file) => selectedIds.indexOf(String(file.id)) === -1)
}
export const makeFilesPaginationSelector = (fileType) => (state) => {
const base = state.files[fileType] || defaultFilesKeyState
return base.pagination
}
export const makeFilesReactTypeSelector = (fileType) => (state) => {
const base = state.files[fileType] || defaultFilesKeyState
return base.reactType
}
export const makeFilesReactTypeIsImageSelector = (fileType) => (state) => {
return makeFilesReactTypeSelector(fileType)(state) === 'image'
}
// State
const defaultFilesKeyState = {
loading: false,
loaded: false,
records: [],
massSelectedIds: [],
massSelectedIndestructibleIds: [],
reactType: 'document',
pagination: {
page: null,
pages: null
}
}
const initialState = {}
// Reducer
function filesReducer (rawState = initialState, action) {
const state = rawState
if (action.fileType && !state[action.fileType]) {
state[action.fileType] = { ...defaultFilesKeyState }
}
switch (action.type) {
case GET_FILES:
return {
...state,
[action.fileType]: {
...state[action.fileType],
loading: true
}
}
case GET_FILES_SUCCESS:
return {
...state,
[action.fileType]: {
...state[action.fileType],
records: action.records,
loading: false,
loaded: true,
pagination: omit(action.meta, ['react_type']),
reactType: action.meta.react_type
}
}
case UPLOADED_FILE:
return {
...state,
[action.fileType]: {
...state[action.fileType],
records: [action.file, ...state[action.fileType].records]
}
}
case THUMBNAIL_GENERATED: {
return {
...state,
[action.fileType]: {
...state[action.fileType],
records: state[action.fileType].records.map((record) => {
if (record.attributes.thumb !== action.temporaryUrl) return record
return {
...record,
attributes: {
...record.attributes,
thumb: action.url
}
}
})
}
}
}
case UPDATE_FILE:
return {
...state,
[action.fileType]: {
...state[action.fileType],
records: state[action.fileType].records.map((record) => {
if (record.id === action.file.id) {
return {
...record,
attributes: {
...record.attributes,
...action.attributes,
updating: true
}
}
} else {
return record
}
})
}
}
case UPDATE_FILE_SUCCESS:
return {
...state,
[action.fileType]: {
...state[action.fileType],
records: state[action.fileType].records.map((record) => {
if (record.id === action.response.id) {
return action.response
} else {
return record
}
})
}
}
case UPDATE_FILE_FAILURE:
return {
...state,
[action.fileType]: {
...state[action.fileType],
records: state[action.fileType].records.map((record) => {
if (record.id === action.file.id) {
return { ...action.file }
} else {
return record
}
})
}
}
case UPDATED_FILES:
return {
...state,
[action.fileType]: {
...state[action.fileType],
records: state[action.fileType].records.map((record) => {
const found = find(action.files, { id: record.id })
return found || record
})
}
}
case MASS_SELECT: {
if (!action.file.id) return state
let massSelectedIds = state[action.fileType].massSelectedIds
let massSelectedIndestructibleIds = state[action.fileType].massSelectedIndestructibleIds
if (action.select) {
massSelectedIds = [...massSelectedIds, action.file.id]
if (action.file.attributes.file_placements_size) {
massSelectedIndestructibleIds = [...massSelectedIndestructibleIds, action.file.id]
}
} else {
massSelectedIds = without(massSelectedIds, action.file.id)
if (action.file.attributes.file_placements_size) {
massSelectedIndestructibleIds = without(massSelectedIndestructibleIds, action.file.id)
}
}
return {
...state,
[action.fileType]: {
...state[action.fileType],
massSelectedIds,
massSelectedIndestructibleIds
}
}
}
case MASS_CANCEL:
return {
...state,
[action.fileType]: {
...state[action.fileType],
massSelectedIds: []
}
}
case REMOVED_FILES: {
const originalLength = state[action.fileType].records.length
const records = state[action.fileType].records.filter((record) => action.ids.indexOf(record.id) === -1)
return {
...state,
[action.fileType]: {
...state[action.fileType],
records,
pagination: {
...state[action.fileType].pagination,
to: records.length,
count: state[action.fileType].pagination.count - (originalLength - records.length)
}
}
}
}
case DELETE_FILE:
return {
...state,
[action.fileType]: {
...state[action.fileType],
records: state[action.fileType].records.map((record) => {
if (record.id === action.file.id) {
return {
...record,
_destroying: true
}
} else {
return record
}
})
}
}
case DELETE_FILE_FAILURE:
return {
...state,
[action.fileType]: {
...state[action.fileType],
records: state[action.fileType].records.map((record) => {
if (record.id === action.file.id) {
return { ...action.file }
} else {
return record
}
})
}
}
default:
return state
}
}
export default filesReducer
|
sinfin/folio
|
react/src/ducks/files.js
|
JavaScript
|
mit
| 14,083 |
using ShiftCaptain.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Security;
namespace ShiftCaptain.Infrastructure
{
public static class Authentication
{
public static Boolean Login(EmailNPass user, ref String errorMessage)
{
errorMessage = "";
var db = new ShiftCaptainEntities();
var validUser = db.Users.FirstOrDefault(u => u.EmailAddress == user.EmailAddress);
if (validUser != null)
{
if (validUser.Locked && validUser.LastLogin.HasValue && (validUser.LastLogin.Value <= DateTime.Now.AddMinutes(-30)))
{
validUser.Locked = false;
validUser.NumTries = 0;
}
int numTries = 4;
Int32.TryParse(ConfigurationManager.AppSettings["NumTries"], out numTries);
if (validUser.NumTries++ > numTries)
{
validUser.Locked = true;
}
if (!validUser.Locked && validUser.Pass == user.Pass)
{
validUser.NumTries = 0;
if (validUser.IsActive)
{
var ticket = new FormsAuthenticationTicket(String.Format("{0}|{1}", validUser.Id, validUser.EmailAddress), true, 30);
var encr = FormsAuthentication.Encrypt(ticket);
//FormsAuthentication.SetAuthCookie("authCk", false);
SessionManager.UserId = validUser.Id;
SessionManager.token = encr;
SessionManager.GetVersion();
return true;
}
}
validUser.LastLogin = DateTime.Now;
db.Entry(validUser).State = EntityState.Modified;
db.SaveChanges();
if (validUser.Locked)
{
errorMessage = "Your account is locked. Please wait 30 minutes or contact the system administrator.";
return false;
}
}
errorMessage = "Email Address or Password is invalid.";
return false;
}
public static void LogOff()
{
SessionManager.Clear();
}
public static bool Authenticate(HttpContextBase ctx)
{
if (SessionManager.token != null)
{
var ticket = FormsAuthentication.Decrypt(SessionManager.token);
if (ticket != null && !ticket.Expired)
{
ctx.User = new GenericPrincipal(new FormsIdentity(ticket), new string[] { });
var nTicket = new FormsAuthenticationTicket(ticket.Name, true, 30);//Everytime you click a new page, clock restarts
SessionManager.token = FormsAuthentication.Encrypt(nTicket);
}
}
return ctx.User.Identity.IsAuthenticated;
}
}
}
|
adabadyitzaboy/ShiftCaptain
|
ShiftCaptain/Infrastructure/Authentication.cs
|
C#
|
mit
| 3,191 |
var self = module.exports;
self = (function(){
self.debug = true;
self.prefix = '/kaskade';
self.ssl = false;
/*{
key: {PEM},
cert: {PEM}
}*/
self.port = 80;
self.host = '0.0.0.0';
self.onConnectionClose = new Function();
self.redis = false;
/*{
host: {String},
port: {Number},
options: {Object}
}*/
self.init = function(cfg){
for(var c in cfg){
if(c in this)
this[c] = cfg[c];
}
};
})();
|
Aldlevine/Kaskade.js-node
|
lib/cfg.js
|
JavaScript
|
mit
| 577 |
# coding=utf-8
from setuptools import setup
from Cython.Build import cythonize
setup(
name="cyfib",
ext_modules=cythonize('cyfib.pyx', compiler_directives={'embedsignature': True}),
)
|
tleonhardt/Python_Interface_Cpp
|
cython/wrap_c/setup.py
|
Python
|
mit
| 193 |
package org.eggermont.hm.cluster;
import cern.colt.matrix.DoubleFactory1D;
import cern.colt.matrix.DoubleMatrix1D;
import cern.colt.matrix.DoubleMatrix2D;
public class ClusterFactory {
private final DoubleMatrix2D x;
private final DoubleMatrix1D blocks;
private final DoubleMatrix1D vMin;
private final DoubleMatrix1D vMax;
private final int ndof;
public ClusterFactory(int d, int nidx, int ndof) {
this.ndof = ndof;
this.blocks = DoubleFactory1D.dense.make(d * nidx);
this.x = blocks.like2D(nidx, d);
this.vMin = DoubleFactory1D.dense.make(d);
this.vMax = DoubleFactory1D.dense.make(d);
}
}
|
meggermo/hierarchical-matrices
|
src/main/java/org/eggermont/hm/cluster/ClusterFactory.java
|
Java
|
mit
| 669 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;
using SharpDeflate;
using vtortola.WebSockets;
using vtortola.WebSockets.Rfc6455;
namespace RohBot
{
public sealed class WebSocketServer<TClient> : IDisposable
where TClient : WebSocketClient, new()
{
private class ClientHandle : IDisposable
{
private Action _dispose;
public ClientHandle(Action dispose)
{
if (dispose == null)
throw new ArgumentNullException(nameof(dispose));
_dispose = dispose;
}
public void Dispose()
{
_dispose?.Invoke();
_dispose = null;
}
}
private CancellationTokenSource _cts;
private WebSocketListener _listener;
private object _clientsSync;
private List<TClient> _clients;
private IReadOnlyList<TClient> _clientsCache;
public WebSocketServer(IPEndPoint endpoint)
{
var options = new WebSocketListenerOptions
{
PingTimeout = TimeSpan.FromSeconds(30)
};
_cts = new CancellationTokenSource();
_listener = new WebSocketListener(endpoint, options);
_clientsSync = new object();
_clients = new List<TClient>();
var rfc6455 = new WebSocketFactoryRfc6455(_listener);
rfc6455.MessageExtensions.RegisterExtension(new WebSocketSharpDeflateExtension());
_listener.Standards.RegisterStandard(rfc6455);
_listener.Start();
ListenAsync();
}
public void Dispose()
{
_cts.Cancel();
_listener.Dispose();
}
public IReadOnlyList<TClient> Clients
{
get
{
lock (_clientsSync)
{
return _clientsCache ?? (_clientsCache = _clients.ToList().AsReadOnly());
}
}
}
private async void ListenAsync()
{
while (_listener.IsStarted)
{
WebSocket websocket;
try
{
websocket = await _listener.AcceptWebSocketAsync(_cts.Token).ConfigureAwait(false);
if (websocket == null)
continue;
}
catch (Exception e)
{
Program.Logger.Error("Failed to accept websocket connection", e);
continue;
}
var client = new TClient();
var clientHandle = new ClientHandle(() =>
{
lock (_clientsSync)
{
_clients.Remove(client);
_clientsCache = null;
}
});
client.Open(clientHandle, websocket, _cts.Token);
lock (_clientsSync)
{
_clients.Add(client);
_clientsCache = null;
}
}
}
}
}
|
Rohansi/RohBot
|
RohBot/WebSocketServer.cs
|
C#
|
mit
| 3,255 |
/* eslint-disable no-undef */
const cukeBtnSubmit = '//button[@data-cuke="save-item"]';
const cukeInpSize = '//input[@data-cuke="size"]';
const cukeInpTitle = '//input[@data-cuke="title"]';
const cukeInpContent = '//textarea[@data-cuke="content"]';
const cukeSize = '//x-cuke[@id="size"]';
const cukeTitle = '//x-cuke[@id="title"]';
const cukeContent = '//x-cuke[@id="content"]';
/*
const cukeHrefEdit = '//a[@data-cuke="edit-ite"]';
const cukeHrefDelete = '//a[@data-cuke="delete-item"]';
*/
const cukeInvalidSize = '//span[@class="help-block error-block"]';
let size = '';
let title = '';
let content = '';
module.exports = function () {
// Scenario: Create a new widget
// ------------------------------------------------------------------------
this.Given(/^I have opened the 'add widgets' page : "([^"]*)"$/, function (_url) {
browser.setViewportSize({ width: 1024, height: 480 });
browser.timeouts('implicit', 60000);
browser.timeouts('page load', 60000);
browser.url(_url);
server.call('_widgets.wipe');
});
this.When(/^I create a "([^"]*)" millimetre "([^"]*)" item with text "([^"]*)",$/,
function (_size, _title, _content) {
size = _size;
title = _title;
content = _content;
browser.waitForEnabled( cukeBtnSubmit );
browser.setValue(cukeInpTitle, title);
browser.setValue(cukeInpSize, size);
browser.setValue(cukeInpContent, content);
browser.click(cukeBtnSubmit);
});
this.Then(/^I see a new record with the same title, size and contents\.$/, function () {
expect(browser.getText(cukeSize)).toEqual(size + ' millimetres.');
expect(browser.getText(cukeTitle)).toEqual(title);
expect(browser.getText(cukeContent)).toEqual(content);
});
// =======================================================================
// Scenario: Verify field validation
// ------------------------------------------------------------------------
this.Given(/^I have opened the widgets list page : "([^"]*)"$/, function (_url) {
browser.setViewportSize({ width: 1024, height: 480 });
browser.timeoutsImplicitWait(1000);
browser.url(_url);
});
/*
let link = '';
this.Given(/^I choose to edit the "([^"]*)" item,$/, function (_widget) {
link = '//a[@data-cuke="' + _widget + '"]';
browser.waitForExist( link );
browser.click(link);
browser.waitForEnabled( cukeHrefEdit );
browser.click(cukeHrefEdit);
});
*/
this.When(/^I set 'Size' to "([^"]*)"$/, function (_size) {
browser.setValue(cukeInpSize, _size);
});
this.Then(/^I see the size validation hint "([^"]*)"\.$/, function (_message) {
expect(browser.getText(cukeInvalidSize)).toEqual(_message);
});
// =======================================================================
// Scenario: Fail to delete widget
// ------------------------------------------------------------------------
let widget = '';
this.Given(/^I choose to view the "([^"]*)" item,$/, function (_widget) {
widget = _widget;
const cukeHrefWidget = `//a[@data-cuke="${widget}"]`;
browser.waitForEnabled( cukeHrefWidget );
browser.click( cukeHrefWidget );
});
/*
let href = null;
this.When(/^I decide to delete the item,$/, function () {
href = cukeHrefDelete;
browser.waitForExist( href );
});
this.Then(/^I see it is disabled\.$/, function () {
expect(browser.isEnabled( href )).toBe(true);
});
*/
// =======================================================================
// Scenario: Unable to update widget
// ------------------------------------------------------------------------
/*
this.When(/^I attempt to edit the item,$/, function () {
href = cukeHrefEdit;
browser.waitForExist( href );
});
*/
// =======================================================================
// Scenario: Prohibited from add and from update
// ------------------------------------------------------------------------
this.Given(/^I have opened the widgets editor page : "([^"]*)"$/, function (_url) {
browser.setViewportSize({ width: 1024, height: 480 });
browser.timeouts('implicit', 60000);
browser.timeouts('page load', 60000);
browser.url(_url);
});
/*
this.Then(/^I see the warning "([^"]*)"$/, function (_warning) {
expect(_warning).toEqual(browser.getText(cukeWarning));
});
*/
// =======================================================================
// Scenario: Hide widget
// ------------------------------------------------------------------------
/*
this.Given(/^I have elected to "([^"]*)" the "([^"]*)" item\.$/, function (_cmd, _widget) {
link = '//a[@data-cuke="' + _widget + '"]';
browser.waitForEnabled( link );
browser.click(link);
let cukeHrefCmd = '//a[@data-cuke="' + _cmd + '-widget"]';
browser.waitForEnabled( cukeHrefCmd );
browser.click( cukeHrefCmd );
});
*/
/*
this.Then(/^I no longer see that widget record\.$/, function () {
browser.waitForEnabled( cukeWidgetsList );
let item = browser.elements(link);
expect(item.value.length).toEqual(0);
});
*/
};
|
warehouseman/meteor-mantra-kickstarter
|
.pkgs/mmks_widget/.e2e_tests/features/widgets/step_defs.js
|
JavaScript
|
mit
| 5,126 |
<!DOCTYPE html>
<?php
include("initial-header.php");
include("config.php");
include('swift/lib/swift_required.php');
$error = "";
if($_SERVER["REQUEST_METHOD"] == "POST") {
// username and password sent from form
$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
$myusername = mysqli_real_escape_string($db,$_POST['username']);
$mypassword = mysqli_real_escape_string($db,$_POST['password']);
$sql = "SELECT email_id, Password, salt FROM login WHERE email_id='$myusername' ";
$result = mysqli_query($db,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$count = mysqli_num_rows($result);
// If email ID exists in the login table
if($count == 1) {
$salt = $row["salt"];
$password_hash = $row["Password"];
$myhash = hash('sha512', $mypassword . $salt);
//If the password is correct
if($password_hash == $myhash){
$_SESSION['login_user'] = $myusername;
$random = rand(100000,999999);
$sql2 = "UPDATE login SET otp=". $random ." WHERE User_id='". $myusername. "'";
$querry = mysqli_query($db,$sql2);
$to = $myusername;
$subject = 'Dual Authentication for Gamify';
$body = 'Greetings. Your one time password is: '.$random;
$headers = 'From: Gamify <gamify101@gmail.com>' . "\r\n" .
'Reply-To: Gamify <gamify101@gmail.com>' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$result = mail($to, $subject, $body, $headers);
header('Location: duo_auth.php');
}
else{
$error = "Your Login Name or Password is invalid";
}
}else {
$error = "Your Login Name or Password is invalid";
}
}
?>
<div class="page-content container">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="login-wrapper">
<div class="box">
<div class="content-wrap">
<h6>Sign In</h6>
<form action = "" method = "post">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-envelope"></i></span>
<input class="form-control" type="text" name = "username" placeholder="User Name" autofocus required>
</div>
<br>
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-key"></i></span>
<input class="form-control" type="password" name = "password" placeholder="Password" required>
</div>
<div class="already">
<span><?php if (isset($error)) echo $error ?></span>
</div>
<div class="action">
<input type = "submit" class="btn btn-primary btn-block signup" value = " Login "/>
</div>
</form>
<br><br>
<p><h4><a href="fg_pwd.php">Forgot Password?</a></h4></p><br>
<h4><p>Don't have an account?<a href="email_id_verification.php"> Register now!</a></p></h4>
</div>
</div>
</div>
</div>
<?php include('initial-footer.php'); ?>
</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://code.jquery.com/jquery.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="bootstrap/js/bootstrap.min.js"></script>
<script src="js/custom.js"></script>
</body>
</html>
|
prash1987/GamifyWebsite
|
login.php
|
PHP
|
mit
| 3,756 |
package net.spy.digg.parsers;
import java.io.IOException;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import net.spy.digg.Story;
/**
* Parse a stories response.
*/
public class StoriesParser extends TimePagedItemParser<Story> {
@Override
protected String getRootElementName() {
return "stories";
}
@Override
protected void handleDocument(Document doc)
throws SAXException, IOException {
parseCommonFields(doc);
final NodeList nl=doc.getElementsByTagName("story");
for(int i=0; i<nl.getLength(); i++) {
addItem(new StoryImpl(nl.item(i)));
}
}
}
|
dustin/java-digg
|
src/main/java/net/spy/digg/parsers/StoriesParser.java
|
Java
|
mit
| 621 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("OptimalizationFun")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("OptimalizationFun")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("8497300e-6541-4c7b-a1cd-592c2f61773d")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
mswietlicki/OptimalizationFun
|
OptimalizationFun/Properties/AssemblyInfo.cs
|
C#
|
mit
| 1,410 |
require "../test_helper"
require "rorschart/data/rorschart_data"
module Rorschart
class TestPivotSeries < Minitest::Unit::TestCase
def test_pivot
# Given
data = [
{"collector_tstamp"=> Date.parse("2013-11-02"), "series" => "A", "count"=> 1},
{"collector_tstamp"=> Date.parse("2013-11-02"), "series" => "B", "count"=> 2},
{"collector_tstamp"=> Date.parse("2013-11-02"), "series" => "C", "count"=> 3},
{"collector_tstamp"=> Date.parse("2013-11-02"), "series" => "D", "count"=> 4},
{"collector_tstamp"=> Date.parse("2013-12-01"), "series" => "A", "count"=> 5},
{"collector_tstamp"=> Date.parse("2013-12-01"), "series" => "B", "count"=> 6},
{"collector_tstamp"=> Date.parse("2013-12-01"), "series" => "D", "count"=> 7}
]
# When
pivot_series = PivotSeries.new(data)
# assert
expected_cols = [
{:type=>"date", :label=>"collector_tstamp"},
{:type=>"number", :label=>"A"},
{:type=>"number", :label=>"B"},
{:type=>"number", :label=>"C"},
{:type=>"number", :label=>"D"}
]
expected_rows = [
[Date.parse("2013-11-02"), 1, 2, 3, 4],
[Date.parse("2013-12-01"), 5, 6, nil, 7]
]
assert_equal expected_cols, pivot_series.cols
assert_equal expected_rows, pivot_series.rows
end
def test_pivot_with_sum_column
# Given
data = [
{"collector_tstamp"=> Date.parse("2013-11-02"), "series" => "A", "count"=> 1},
{"collector_tstamp"=> Date.parse("2013-11-02"), "series" => "B", "count"=> 2},
{"collector_tstamp"=> Date.parse("2013-11-02"), "series" => "C", "count"=> 3},
{"collector_tstamp"=> Date.parse("2013-11-02"), "series" => "D", "count"=> 4},
{"collector_tstamp"=> Date.parse("2013-12-01"), "series" => "A", "count"=> nil},
{"collector_tstamp"=> Date.parse("2013-12-01"), "series" => "B", "count"=> 6},
{"collector_tstamp"=> Date.parse("2013-12-01"), "series" => "D", "count"=> 7}
]
# When
pivot_series = PivotSeries.new(data, add_total_column: true)
# assert
expected_cols = [
{:type=>"date", :label=>"collector_tstamp"},
{:type=>"number", :label=>"Total"},
{:type=>"number", :label=>"A"},
{:type=>"number", :label=>"B"},
{:type=>"number", :label=>"C"},
{:type=>"number", :label=>"D"}
]
expected_rows = [
[Date.parse("2013-11-02"), 10, 1, 2, 3, 4],
[Date.parse("2013-12-01"), 13, nil, 6, nil, 7]
]
assert_equal expected_cols, pivot_series.cols
assert_equal expected_rows, pivot_series.rows
end
def test_pivot_with_empty_data
# Given
data = []
# When
pivot_series = PivotSeries.new(data)
# assert
expected_cols = []
expected_rows = []
assert_equal expected_cols, pivot_series.cols
assert_equal expected_rows, pivot_series.rows
end
end
end
|
viadeo/rorschart
|
test/data/pivot_series_test.rb
|
Ruby
|
mit
| 3,811 |
package de.thomas.dreja.ec.musicquiz.gui.dialog;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import de.thomas.dreja.ec.musicquiz.R;
import de.thomas.dreja.ec.musicquiz.ctrl.PlaylistResolver.SortOrder;
public class SortOrderSelectionDialog extends DialogFragment {
private SortOrderSelectionListener listener;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
String[] items = new String[SortOrder.values().length];
for(int i=0; i<items.length; i++) {
items[i] = SortOrder.values()[i].getName(getResources());
}
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.sort_by)
.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
listener.onSortOrderSelected(SortOrder.values()[which]);
}
});
return builder.create();
}
public interface SortOrderSelectionListener {
public void onSortOrderSelected(SortOrder order);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// Verify that the host activity implements the callback interface
try {
// Instantiate the NoticeDialogListener so we can send events to the host
listener = (SortOrderSelectionListener) activity;
} catch (ClassCastException e) {
// The activity doesn't implement the interface, throw exception
throw new ClassCastException(activity.toString()
+ " must implement SortOrderSelectionListener");
}
}
}
|
Nanobot5770/DasMusikQuiz
|
src/de/thomas/dreja/ec/musicquiz/gui/dialog/SortOrderSelectionDialog.java
|
Java
|
mit
| 1,823 |
# cooper document with one key example
class RevisionedObject
include Cooper::Document
revision_field :key, type: String
end
describe 'Updating documents' do
let(:object) do
RevisionedObject.new
end
it 'works like Mongoid::Document' do
object.key = 'value0'
object.save
object.update_attributes(key: 'value1')
expect(object.key).to eq 'value1'
end
end
|
floum/cooper
|
features/updating_documents_spec.rb
|
Ruby
|
mit
| 386 |
<?php
namespace BackendBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class DefaultControllerTest extends WebTestCase
{
public function testIndex()
{
$client = static::createClient();
$crawler = $client->request('GET', '/');
$this->assertContains('Hello World', $client->getResponse()->getContent());
}
}
|
haciel/sistema_comtable
|
tests/BackendBundle/Controller/DefaultControllerTest.php
|
PHP
|
mit
| 394 |
using System;
using System.Net;
using Microsoft.Extensions.Logging;
namespace CakesNoteProxy
{
public static class NoteProxyConfigure
{
public static ILoggerFactory LoggerFactory;
public static class NoteApi
{
public static string SiteFqdn { get; private set; }
public static string UserId { get; private set; }
public static bool IsIntro { get; private set; }
static NoteApi()
{
SiteFqdn = "https://note.mu";
UserId = "info";
IsIntro = true;
}
public static void SetGlobal(string noteSiteFqdn)
{
if ( noteSiteFqdn!=null)
SiteFqdn = noteSiteFqdn;
}
public static void SetMyNote(string noteUserId, bool isIntro)
{
if (noteUserId != null)
UserId = noteUserId;
IsIntro = isIntro;
}
public static readonly string ApiRoot = "/api/v1";
}
public static class NoteCache
{
public static int CachedItemsCountHardLimit = 50;
public static TimeSpan MonitoringThreadInterval = TimeSpan.FromSeconds(12);
public static TimeSpan CacheLifecycleTimeSpan = TimeSpan.FromSeconds(720);
public static double CacheLifecycleSpeculativeExecutionRate = 0.8;
}
}
}
|
SiroccoHub/CakesNoteProxy
|
src/CakesNoteProxy/NoteProxyConfigure.cs
|
C#
|
mit
| 1,514 |
module HealthSeven::V2_5
class Rq1 < ::HealthSeven::Segment
# Anticipated Price
attribute :anticipated_price, St, position: "RQ1.1"
# Manufacturer Identifier
attribute :manufacturer_identifier, Ce, position: "RQ1.2"
# Manufacturer's Catalog
attribute :manufacturer_s_catalog, St, position: "RQ1.3"
# Vendor ID
attribute :vendor_id, Ce, position: "RQ1.4"
# Vendor Catalog
attribute :vendor_catalog, St, position: "RQ1.5"
# Taxable
attribute :taxable, Id, position: "RQ1.6"
# Substitute Allowed
attribute :substitute_allowed, Id, position: "RQ1.7"
end
end
|
niquola/health_seven
|
lib/health_seven/2.5/segments/rq1.rb
|
Ruby
|
mit
| 581 |
using System;
using Lunt.IO;
namespace Lunt
{
/// <summary>
/// Represent a dependency to an asset.
/// </summary>
public sealed class AssetDependency
{
private readonly FilePath _path;
private readonly long _fileSize;
private readonly string _checksum;
/// <summary>
/// Gets the path of the dependency.
/// </summary>
/// <value>The path of the dependency.</value>
public FilePath Path
{
get { return _path; }
}
/// <summary>
/// Gets the file size of the dependency.
/// </summary>
/// <value>The file size of the dependency.</value>
public long FileSize
{
get { return _fileSize; }
}
/// <summary>
/// Gets the checksum of the dependency.
/// </summary>
/// <value>The checksum of the dependency.</value>
public string Checksum
{
get { return _checksum; }
}
/// <summary>
/// Initializes a new instance of the <see cref="AssetDependency" /> class.
/// </summary>
/// <param name="path">The path.</param>
/// <param name="fileSize">The file size.</param>
/// <param name="checksum">The checksum.</param>
public AssetDependency(FilePath path, long fileSize, string checksum)
{
if (path == null)
{
throw new ArgumentNullException("path");
}
if (checksum == null)
{
throw new ArgumentNullException("checksum");
}
_path = path;
_fileSize = fileSize;
_checksum = checksum;
}
}
}
|
lunt/lunt
|
src/Lunt/AssetDependency.cs
|
C#
|
mit
| 1,748 |
#include "ofQuickTimeGrabber.h"
#include "ofUtils.h"
#if !defined(TARGET_LINUX) && !defined(MAC_OS_X_VERSION_10_7)
//---------------------------------
#ifdef OF_VIDEO_CAPTURE_QUICKTIME
//---------------------------------
//--------------------------------------------------------------
static ComponentResult frameIsGrabbedProc(SGChannel sgChan, short nBufferNum, Boolean *pbDone, long lRefCon);
static ComponentResult frameIsGrabbedProc(SGChannel sgChan, short nBufferNum, Boolean *pbDone, long lRefCon){
ComponentResult err = SGGrabFrameComplete( sgChan, nBufferNum, pbDone );
bool * havePixChanged = (bool *)lRefCon;
*havePixChanged = true;
return err;
}
//---------------------------------
#endif
//---------------------------------
//--------------------------------------------------------------------
ofQuickTimeGrabber::ofQuickTimeGrabber(){
//---------------------------------
#ifdef OF_VIDEO_CAPTURE_QUICKTIME
//---------------------------------
initializeQuicktime();
bSgInited = false;
gSeqGrabber = nullptr;
offscreenGWorldPixels = nullptr;
//---------------------------------
#endif
//---------------------------------
// common
bIsFrameNew = false;
bVerbose = false;
bGrabberInited = false;
bChooseDevice = false;
deviceID = 0;
//width = 320; // default setting
//height = 240; // default setting
//pixels = nullptr;
attemptFramerate = -1;
}
//--------------------------------------------------------------------
ofQuickTimeGrabber::~ofQuickTimeGrabber(){
close();
//---------------------------------
#ifdef OF_VIDEO_CAPTURE_QUICKTIME
//---------------------------------
if (offscreenGWorldPixels != nullptr){
delete[] offscreenGWorldPixels;
offscreenGWorldPixels = nullptr;
}
//---------------------------------
#endif
//---------------------------------
}
//--------------------------------------------------------------------
void ofQuickTimeGrabber::setVerbose(bool bTalkToMe){
bVerbose = bTalkToMe;
}
//--------------------------------------------------------------------
void ofQuickTimeGrabber::setDeviceID(int _deviceID){
deviceID = _deviceID;
bChooseDevice = true;
}
//--------------------------------------------------------------------
void ofQuickTimeGrabber::setDesiredFrameRate(int framerate){
attemptFramerate = framerate;
}
//---------------------------------------------------------------------------
bool ofQuickTimeGrabber::setPixelFormat(ofPixelFormat pixelFormat){
//note as we only support RGB we are just confirming that this pixel format is supported
if( pixelFormat == OF_PIXELS_RGB ){
return true;
}
ofLogWarning("ofQuickTimeGrabber") << "setPixelFormat(): requested pixel format " << pixelFormat << " not supported";
return false;
}
//---------------------------------------------------------------------------
ofPixelFormat ofQuickTimeGrabber::getPixelFormat() const {
//note if you support more than one pixel format you will need to return a ofPixelFormat variable.
return OF_PIXELS_RGB;
}
//--------------------------------------------------------------------
bool ofQuickTimeGrabber::setup(int w, int h){
//---------------------------------
#ifdef OF_VIDEO_CAPTURE_QUICKTIME
//---------------------------------
//---------------------------------- 1 - open the sequence grabber
if( !qtInitSeqGrabber() ){
ofLogError("ofQuickTimeGrabber") << "initGrabber(): unable to initialize the seq grabber";
return false;
}
//---------------------------------- 2 - set the dimensions
//width = w;
//height = h;
MacSetRect(&videoRect, 0, 0, w, h);
//---------------------------------- 3 - buffer allocation
// Create a buffer big enough to hold the video data,
// make sure the pointer is 32-byte aligned.
// also the rgb image that people will grab
offscreenGWorldPixels = (unsigned char*)malloc(4 * w * h + 32);
pixels.allocate(w, h, OF_IMAGE_COLOR);
#if defined(TARGET_OSX) && defined(__BIG_ENDIAN__)
QTNewGWorldFromPtr (&(videogworld), k32ARGBPixelFormat, &(videoRect), nullptr, nullptr, 0, (offscreenGWorldPixels), 4 * w);
#else
QTNewGWorldFromPtr (&(videogworld), k24RGBPixelFormat, &(videoRect), nullptr, nullptr, 0, (pixels.getPixels()), 3 * w);
#endif
LockPixels(GetGWorldPixMap(videogworld));
SetGWorld (videogworld, nullptr);
SGSetGWorld(gSeqGrabber, videogworld, nil);
//---------------------------------- 4 - device selection
bool didWeChooseADevice = bChooseDevice;
bool deviceIsSelected = false;
//if we have a device selected then try first to setup
//that device
if(didWeChooseADevice){
deviceIsSelected = qtSelectDevice(deviceID, true);
if(!deviceIsSelected && bVerbose)
ofLogError("ofQuickTimeGrabber") << "initGrabber(): unable to open device[" << deviceID << "], will attempt other devices";
}
//if we couldn't select our required device
//or we aren't specifiying a device to setup
//then lets try to setup ANY device!
if(deviceIsSelected == false){
//lets list available devices
listDevices();
setDeviceID(0);
deviceIsSelected = qtSelectDevice(deviceID, false);
}
//if we still haven't been able to setup a device
//we should error and stop!
if( deviceIsSelected == false){
goto bail;
}
//---------------------------------- 5 - final initialization steps
OSStatus err;
err = SGSetChannelUsage(gVideoChannel,seqGrabPreview);
if ( err != noErr ) goto bail;
//----------------- callback method for notifying new frame
err = SGSetChannelRefCon(gVideoChannel, (long)&bHavePixelsChanged );
if(!err) {
VideoBottles vb;
/* get the current bottlenecks */
vb.procCount = 9;
err = SGGetVideoBottlenecks(gVideoChannel, &vb);
if (!err) {
myGrabCompleteProc = NewSGGrabCompleteBottleUPP(frameIsGrabbedProc);
vb.grabCompleteProc = myGrabCompleteProc;
/* add our GrabFrameComplete function */
err = SGSetVideoBottlenecks(gVideoChannel, &vb);
}
}
err = SGSetChannelBounds(gVideoChannel, &videoRect);
if ( err != noErr ) goto bail;
err = SGPrepare(gSeqGrabber, true, false); //theo swapped so preview is true and capture is false
if ( err != noErr ) goto bail;
err = SGStartPreview(gSeqGrabber);
if ( err != noErr ) goto bail;
bGrabberInited = true;
loadSettings();
if( attemptFramerate >= 0 ){
err = SGSetFrameRate(gVideoChannel, IntToFixed(attemptFramerate) );
if ( err != noErr ){
ofLogError("ofQuickTimeGrabber") << "initGrabber: couldn't setting framerate to " << attemptFramerate << ": OSStatus " << err;
}
}
ofLogNotice("ofQuickTimeGrabber") << " inited grabbed ";
ofLogNotice("ofQuickTimeGrabber") << "-------------------------------------";
// we are done
return true;
//--------------------- (bail) something's wrong -----
bail:
ofLogError("ofQuickTimeGrabber") << "***** ofQuickTimeGrabber error *****";
ofLogError("ofQuickTimeGrabber") << "------------------------------------";
//if we don't close this - it messes up the next device!
if(bSgInited) qtCloseSeqGrabber();
bGrabberInited = false;
return false;
//---------------------------------
#else
//---------------------------------
return false;
//---------------------------------
#endif
//---------------------------------
}
//--------------------------------------------------------------------
bool ofQuickTimeGrabber::isInitialized() const{
return bGrabberInited;
}
//--------------------------------------------------------------------
vector<ofVideoDevice> ofQuickTimeGrabber::listDevices() const{
vector <ofVideoDevice> devices;
//---------------------------------
#ifdef OF_VIDEO_CAPTURE_QUICKTIME
//---------------------------------
bool bNeedToInitGrabberFirst = false;
if (!bSgInited) bNeedToInitGrabberFirst = true;
//if we need to initialize the grabbing component then do it
if( bNeedToInitGrabberFirst ){
if( !qtInitSeqGrabber() ){
return devices;
}
}
ofLogNotice("ofQuickTimeGrabber") << "-------------------------------------";
/*
//input selection stuff (ie multiple webcams)
//from http://developer.apple.com/samplecode/SGDevices/listing13.html
//and originally http://lists.apple.com/archives/QuickTime-API/2008/Jan/msg00178.html
*/
SGDeviceList deviceList;
SGGetChannelDeviceList (gVideoChannel, sgDeviceListIncludeInputs, &deviceList);
unsigned char pascalName[64];
unsigned char pascalNameInput[64];
//this is our new way of enumerating devices
//quicktime can have multiple capture 'inputs' on the same capture 'device'
//ie the USB Video Class Video 'device' - can have multiple usb webcams attached on what QT calls 'inputs'
//The isight for example will show up as:
//USB Video Class Video - Built-in iSight ('input' 1 of the USB Video Class Video 'device')
//Where as another webcam also plugged whill show up as
//USB Video Class Video - Philips SPC 1000NC Webcam ('input' 2 of the USB Video Class Video 'device')
//this means our the device ID we use for selection has to count both capture 'devices' and their 'inputs'
//this needs to be the same in our init grabber method so that we select the device we ask for
int deviceCount = 0;
ofLogNotice("ofQuickTimeGrabber") << "listing available capture devices";
for(int i = 0 ; i < (*deviceList)->count ; ++i)
{
SGDeviceName nameRec;
nameRec = (*deviceList)->entry[i];
SGDeviceInputList deviceInputList = nameRec.inputs;
int numInputs = 0;
if( deviceInputList ) numInputs = ((*deviceInputList)->count);
memcpy(pascalName, (*deviceList)->entry[i].name, sizeof(char) * 64);
//this means we can use the capture method
if(nameRec.flags != sgDeviceNameFlagDeviceUnavailable){
//if we have a capture 'device' (qt's word not mine - I would prefer 'system' ) that is ready to be used
//we go through its inputs to list all physical devices - as there could be more than one!
for(int j = 0; j < numInputs; j++){
//if our 'device' has inputs we get their names here
if( deviceInputList ){
SGDeviceInputName inputNameRec = (*deviceInputList)->entry[j];
memcpy(pascalNameInput, inputNameRec.name, sizeof(char) * 64);
}
ofLogNotice() << "device [" << deviceCount << "] " << p2cstr(pascalName) << " - " << p2cstr(pascalNameInput);
ofVideoDevice vd;
vd.id = deviceCount;
vd.deviceName = p2cstr(pascalName);
vd.bAvailable = true;
devices.push_back(vd);
//we count this way as we need to be able to distinguish multiple inputs as devices
deviceCount++;
}
}else{
ofLogNotice("ofQuickTimeGrabber") << "(unavailable) device [" << deviceCount << "] " << p2cstr(pascalName);
ofVideoDevice vd;
vd.id = deviceCount;
vd.deviceName = p2cstr(pascalName);
vd.bAvailable = false;
devices.push_back(vd);
deviceCount++;
}
}
ofLogNotice("ofQuickTimeGrabber") << "-------------------------------------";
//if we initialized the grabbing component then close it
if( bNeedToInitGrabberFirst ){
qtCloseSeqGrabber();
}
//---------------------------------
#endif
//---------------------------------
return devices;
}
//--------------------------------------------------------------------
void ofQuickTimeGrabber::update(){
//---------------------------------
#ifdef OF_VIDEO_CAPTURE_QUICKTIME
//---------------------------------
if (bGrabberInited == true){
SGIdle(gSeqGrabber);
// set the top pixel alpha = 0, so we can know if it
// was a new frame or not..
// or else we will process way more than necessary
// (ie opengl is running at 60fps +, capture at 30fps)
if (bHavePixelsChanged){
#if defined(TARGET_OSX) && defined(__BIG_ENDIAN__)
convertPixels(offscreenGWorldPixels, pixels.getPixels(), width, height);
#endif
}
}
// newness test for quicktime:
if (bGrabberInited == true){
bIsFrameNew = false;
if (bHavePixelsChanged == true){
bIsFrameNew = true;
bHavePixelsChanged = false;
}
}
//---------------------------------
#endif
//---------------------------------
}
//---------------------------------------------------------------------------
ofPixels& ofQuickTimeGrabber::getPixels(){
return pixels;
}
//---------------------------------------------------------------------------
const ofPixels& ofQuickTimeGrabber::getPixels() const {
return pixels;
}
//---------------------------------------------------------------------------
bool ofQuickTimeGrabber::isFrameNew() const {
return bIsFrameNew;
}
//--------------------------------------------------------------------
float ofQuickTimeGrabber::getWidth() const {
return pixels.getWidth();
}
//--------------------------------------------------------------------
float ofQuickTimeGrabber::getHeight() const {
return pixels.getHeight();
}
//--------------------------------------------------------------------
void ofQuickTimeGrabber::clearMemory(){
pixels.clear();
}
//--------------------------------------------------------------------
void ofQuickTimeGrabber::close(){
//---------------------------------
#ifdef OF_VIDEO_CAPTURE_QUICKTIME
//---------------------------------
qtCloseSeqGrabber();
DisposeSGGrabCompleteBottleUPP(myGrabCompleteProc);
//---------------------------------
#endif
//---------------------------------
clearMemory();
}
//--------------------------------------------------------------------
void ofQuickTimeGrabber::videoSettings(void){
//---------------------------------
#ifdef OF_VIDEO_CAPTURE_QUICKTIME
//---------------------------------
Rect curBounds, curVideoRect;
ComponentResult err;
// Get our current state
err = SGGetChannelBounds (gVideoChannel, &curBounds);
if (err != noErr){
ofLogError("ofQuickTimeGrabber") << "videoSettings(): couldn't get get channel bounds: ComponentResult " << err;
return;
}
err = SGGetVideoRect (gVideoChannel, &curVideoRect);
if (err != noErr){
ofLogError("ofQuickTimeGrabber") << "videoSettings(): couldn't get video rect: ComponentResult " << err;
return;
}
// Pause
err = SGPause (gSeqGrabber, true);
if (err != noErr){
ofLogError("ofQuickTimeGrabber") << "videoSettings(): couldn't set pause: ComponentResult " << err;
return;
}
#ifdef TARGET_OSX
//load any saved camera settings from file
loadSettings();
static SGModalFilterUPP gSeqGrabberModalFilterUPP = NewSGModalFilterUPP(SeqGrabberModalFilterUPP);
ComponentResult result = SGSettingsDialog(gSeqGrabber, gVideoChannel, 0, nil, 0, gSeqGrabberModalFilterUPP, nil);
if (result != noErr){
ofLogError("ofQuickTimeGrabber") << "videoSettings(): settings dialog error: ComponentResult " << err;
return;
}
//save any changed settings to file
saveSettings();
#else
SGSettingsDialog(gSeqGrabber, gVideoChannel, 0, nil, seqGrabSettingsPreviewOnly, nullptr, 0);
#endif
SGSetChannelBounds(gVideoChannel, &videoRect);
SGPause (gSeqGrabber, false);
//---------------------------------
#endif
//---------------------------------
}
//--------------------------------------------------------------------
#ifdef TARGET_OSX
//--------------------------------------------------------------------
//---------------------------------------------------------------------
bool ofQuickTimeGrabber::saveSettings(){
if (bGrabberInited != true) return false;
ComponentResult err;
UserData mySGVideoSettings = nullptr;
// get the SGChannel settings cofigured by the user
err = SGGetChannelSettings(gSeqGrabber, gVideoChannel, &mySGVideoSettings, 0);
if ( err != noErr ){
ofLogError("ofQuickTimeGrabber") << "saveSettings(): couldn't get camera settings: ComponentResult " << err;
return false;
}
string pref = "ofVideoSettings-"+deviceName;
CFStringRef cameraString = CFStringCreateWithCString(kCFAllocatorDefault,pref.c_str(),kCFStringEncodingMacRoman);
//get the settings using the key "ofVideoSettings-the name of the device"
SaveSettingsPreference( cameraString, mySGVideoSettings);
DisposeUserData(mySGVideoSettings);
return true;
}
//---------------------------------------------------------------------
bool ofQuickTimeGrabber::loadSettings(){
if (bGrabberInited != true || deviceName.length() == 0) return false;
ComponentResult err;
UserData mySGVideoSettings = nullptr;
// get the settings using the key "ofVideoSettings-the name of the device"
string pref = "ofVideoSettings-"+deviceName;
CFStringRef cameraString = CFStringCreateWithCString(kCFAllocatorDefault,pref.c_str(),kCFStringEncodingMacRoman);
GetSettingsPreference(cameraString, &mySGVideoSettings);
if (mySGVideoSettings){
Rect curBounds, curVideoRect;
//we need to make sure the dimensions don't get effected
//by our preferences
// Get our current state
err = SGGetChannelBounds (gVideoChannel, &curBounds);
if (err != noErr){
ofLogError("ofQuickTimeGrabber") << "loadSettings(): couldn't set channel bounds: ComponentResult " << err;
}
err = SGGetVideoRect (gVideoChannel, &curVideoRect);
if (err != noErr){
ofLogError("ofQuickTimeGrabber") << "loadSettings(): couldn't set video rect: ComponentResult " << err;
}
// use the saved settings preference to configure the SGChannel
err = SGSetChannelSettings(gSeqGrabber, gVideoChannel, mySGVideoSettings, 0);
if ( err != noErr ) {
ofLogError("ofQuickTimeGrabber") << "loadSettings(): couldn't set channel settings: ComponentResult " << err;
return false;
}
DisposeUserData(mySGVideoSettings);
// Pause
err = SGPause (gSeqGrabber, true);
if (err != noErr){
ofLogError("ofQuickTimeGrabber") << "loadSettings(): couldn't set pause: ComponentResult " << err;
}
SGSetChannelBounds(gVideoChannel, &videoRect);
SGPause (gSeqGrabber, false);
}else{
ofLogWarning("ofQuickTimeGrabber") << "loadSettings(): no camera settings to load";
return false;
}
return true;
}
//------------------------------------------------------
bool ofQuickTimeGrabber::qtInitSeqGrabber(){
if (bSgInited != true){
OSErr err = noErr;
ComponentDescription theDesc;
Component sgCompID;
// this crashes when we get to
// SGNewChannel
// we get -9405 as error code for the channel
// -----------------------------------------
// gSeqGrabber = OpenDefaultComponent(SeqGrabComponentType, 0);
// this seems to work instead (got it from hackTV)
// -----------------------------------------
theDesc.componentType = SeqGrabComponentType;
theDesc.componentSubType = nullptr;
theDesc.componentManufacturer = 'appl';
theDesc.componentFlags = nullptr;
theDesc.componentFlagsMask = nullptr;
sgCompID = FindNextComponent (nullptr, &theDesc);
// -----------------------------------------
if (sgCompID == nullptr){
ofLogError("ofQuickTimeGrabber") << "qtInitSeqGrabber(): findNextComponent did not return a valid component";
return false;
}
gSeqGrabber = OpenComponent(sgCompID);
err = GetMoviesError();
if (gSeqGrabber == nullptr || err) {
ofLogError("ofQuickTimeGrabber") << "qtInitSeqGrabber(): couldn't get default sequence grabber component: OSErr " << err;
return false;
}
err = SGInitialize(gSeqGrabber);
if (err != noErr) {
ofLogError("ofQuickTimeGrabber") << "qtInitSeqGrabber(): can't initialize sequence grabber component: OSErr " << err;
return false;
}
err = SGSetDataRef(gSeqGrabber, 0, 0, seqGrabDontMakeMovie);
if (err != noErr) {
ofLogError("ofQuickTimeGrabber") << "qtInitSeqGrabber(): can't set the destination data reference: OSErr " << err;
return false;
}
// windows crashes w/ out gworld, make a dummy for now...
// this took a long time to figure out.
err = SGSetGWorld(gSeqGrabber, 0, 0);
if (err != noErr) {
ofLogError("ofQuickTimeGrabber") << "qtInitSeqGrabber(): setting up the gworld: OSErr " << err;
return false;
}
err = SGNewChannel(gSeqGrabber, VideoMediaType, &(gVideoChannel));
if (err != noErr) {
ofLogError("ofQuickTimeGrabber") << "qtInitSeqGrabber(): couldn't create a new channel: OSErr " << err;
ofLogError("ofQuickTimeGrabber") << "qtInitSeqGrabber(): check if you have any qt capable cameras attached";
return false;
}
bSgInited = true;
return true;
}
return false;
}
//--------------------------------------------------------------------
bool ofQuickTimeGrabber::qtCloseSeqGrabber(){
if (gSeqGrabber != nullptr){
SGStop (gSeqGrabber);
CloseComponent (gSeqGrabber);
gSeqGrabber = nullptr;
bSgInited = false;
return true;
}
return false;
}
//--------------------------------------------------------------------
bool ofQuickTimeGrabber::qtSelectDevice(int deviceNumber, bool didWeChooseADevice){
//note - check for memory freeing possibly needed for the all SGGetChannelDeviceList mac stuff
// also see notes in listDevices() regarding new enunemeration method.
//Generate a device list and enumerate
//all devices availble to the channel
SGDeviceList deviceList;
SGGetChannelDeviceList(gVideoChannel, sgDeviceListIncludeInputs, &deviceList);
unsigned char pascalName[64];
unsigned char pascalNameInput[64];
int numDevices = (*deviceList)->count;
if(numDevices == 0){
ofLogError("ofQuickTimeGrabber") << "no capture devices found";
return false;
}
int deviceCount = 0;
for(int i = 0 ; i < numDevices; ++i)
{
SGDeviceName nameRec;
nameRec = (*deviceList)->entry[i];
SGDeviceInputList deviceInputList = nameRec.inputs;
int numInputs = 0;
if( deviceInputList ) numInputs = ((*deviceInputList)->count);
memcpy(pascalName, (*deviceList)->entry[i].name, sizeof(char) * 64);
memset(pascalNameInput, 0, sizeof(char)*64);
//this means we can use the capture method
if(nameRec.flags != sgDeviceNameFlagDeviceUnavailable){
//if we have a capture 'device' (qt's word not mine - I would prefer 'system' ) that is ready to be used
//we go through its inputs to list all physical devices - as there could be more than one!
for(int j = 0; j < numInputs; j++){
//if our 'device' has inputs we get their names here
if( deviceInputList ){
SGDeviceInputName inputNameRec = (*deviceInputList)->entry[j];
memcpy(pascalNameInput, inputNameRec.name, sizeof(char) * 64);
}
//if the device number matches we try and setup the device
//if we didn't specifiy a device then we will try all devices till one works!
if( deviceCount == deviceNumber || !didWeChooseADevice ){
ofLogNotice("ofQuickTimeGrabber") << "attempting to open device [" << deviceCount << "] "
<< p2cstr(pascalName) << " - " << p2cstr(pascalNameInput);
OSErr err1 = SGSetChannelDevice(gVideoChannel, pascalName);
OSErr err2 = SGSetChannelDeviceInput(gVideoChannel, j);
int successLevel = 0;
//if there were no errors then we have opened the device without issue
if ( err1 == noErr && err2 == noErr){
successLevel = 2;
}
//parameter errors are not fatal so we will try and open but will caution the user
else if ( (err1 == paramErr || err1 == noErr) && (err2 == noErr || err2 == paramErr) ){
successLevel = 1;
}
//the device is opened!
if ( successLevel > 0 ){
deviceName = (char *)p2cstr(pascalName);
deviceName += "-";
deviceName += (char *)p2cstr(pascalNameInput);
if(successLevel == 2){
ofLogNotice("ofQuickTimeGrabber") << "device " << deviceName << " opened successfully";
}
else{
ofLogWarning("ofQuickTimeGrabber") << "device " << deviceName << " opened with some paramater errors, should be fine though!";
}
//no need to keep searching - return that we have opened a device!
return true;
}else{
//if we selected a device in particular but failed we want to go through the whole list again - starting from 0 and try any device.
//so we return false - and try one more time without a preference
if( didWeChooseADevice ){
ofLogWarning("ofQuickTimeGrabber") << "problems setting device [" << deviceNumber << "] "
<< p2cstr(pascalName) << " - " << p2cstr(pascalNameInput) << " *****";
return false;
}else{
ofLogWarning("ofQuickTimeGrabber") << "unable to open device, trying next device";
}
}
}
//we count this way as we need to be able to distinguish multiple inputs as devices
deviceCount++;
}
}else{
//ofLogError("ofQuickTimeGrabber") << "(unavailable) device [" << deviceCount << "] " << p2cstr(pascalName);
deviceCount++;
}
}
return false;
}
//---------------------------------
#endif
//---------------------------------
#endif
|
murataka9/iOSinOF-NativeGUISample
|
of_v0.9.3_ios_release/libs/openFrameworks/video/ofQuickTimeGrabber.cpp
|
C++
|
mit
| 25,185 |
# frozen_string_literal: true
require 'spec_helper'
describe 'logging' do
it "should have a logger" do
expect(Dummy).to respond_to(:logger)
end
it "should be able to log debug methods" do
expect(Dummy.logger).to respond_to(:debug)
end
it "should be settable" do
expect(Dummy).to respond_to(:logger=)
log = double
Dummy.logger = log
expect(Dummy.logger).to eq(log)
end
end
|
controlshift/vertebrae
|
spec/logger_spec.rb
|
Ruby
|
mit
| 412 |
// Copyright (c) 2015-2018 William W. Fisher (at gmail dot com)
// This file is distributed under the MIT License.
#include "ofp/tablestatus.h"
#include "ofp/writable.h"
using namespace ofp;
bool TableStatus::validateInput(Validation *context) const {
size_t length = context->length();
if (length < sizeof(TableStatus) + sizeof(TableDesc)) {
log_debug("TableStatus too small", length);
return false;
}
size_t remainingLength = length - sizeof(TableStatus);
context->setLengthRemaining(remainingLength);
// FIXME: make sure there is only one table?
return table().validateInput(context);
}
UInt32 TableStatusBuilder::send(Writable *channel) {
UInt8 version = channel->version();
UInt32 xid = channel->nextXid();
UInt16 msgLen = UInt16_narrow_cast(sizeof(msg_) + table_.writeSize(channel));
msg_.header_.setVersion(version);
msg_.header_.setLength(msgLen);
msg_.header_.setXid(xid);
channel->write(&msg_, sizeof(msg_));
table_.write(channel);
channel->flush();
return xid;
}
|
byllyfish/oftr
|
src/ofp/tablestatus.cpp
|
C++
|
mit
| 1,028 |
require 'delegate'
module Bizflow
module BusinessModel
class SimpleWrapper < SimpleDelegator
def self.wrap(item)
new item
end
def self.wraps(items)
res = items.map do |item|
new item
end
res
end
end
end
end
|
sljuka/bizflow
|
lib/bizflow/business_model/simple_wrapper.rb
|
Ruby
|
mit
| 294 |
class Solution {
public int solution(int[] A) {
int[] temArray = new int[A.length + 2];
for (int i = 0; i < A.length; i++) {
temArray[A[i]] = 1;
}
for (int i = 1; i < temArray.length + 1; i++) {
if(temArray[i] == 0){
return i;
}
}
return A[A.length - 1] + 1;
}
}
|
majusko/codility
|
PermMissingElem.java
|
Java
|
mit
| 392 |
function EditMovieCtrl(MovieService,$stateParams) {
// ViewModel
const edit = this;
edit.title = 'Edit Movies' + $stateParams.id;
edit.back = function(){
window.history.back()
}
edit.checker = function(bool){
if(bool=='true')
return true;
if(bool=='false')
return false;
}
edit.click = function(bool,key){
edit.data[key] = !bool
}
MovieService.getID($stateParams.id).then(function(results){
if(results.status===404)
edit.data.movies='not found'
edit.data = results
})
// MovieService.get().then(function(results){
// edit.movies = results
// })
edit.processForm = function(){
MovieService.put(edit.data).then(function(res){
console.log(res)
})
}
}
EditMovieCtrl.$inject=['MovieService','$stateParams']
export default {
name: 'EditMovieCtrl',
fn: EditMovieCtrl
};
|
johndoechang888/popcorn
|
fe/app/js/controllers/EditMovieCtrl.js
|
JavaScript
|
mit
| 882 |
/**
* @fileoverview Rule to require or disallow line breaks inside braces.
* @author Toru Nagashima
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
let astUtils = require("../ast-utils");
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
// Schema objects.
let OPTION_VALUE = {
oneOf: [
{
enum: ["always", "never"]
},
{
type: "object",
properties: {
multiline: {
type: "boolean"
},
minProperties: {
type: "integer",
minimum: 0
}
},
additionalProperties: false,
minProperties: 1
}
]
};
/**
* Normalizes a given option value.
*
* @param {string|Object|undefined} value - An option value to parse.
* @returns {{multiline: boolean, minProperties: number}} Normalized option object.
*/
function normalizeOptionValue(value) {
let multiline = false;
let minProperties = Number.POSITIVE_INFINITY;
if (value) {
if (value === "always") {
minProperties = 0;
} else if (value === "never") {
minProperties = Number.POSITIVE_INFINITY;
} else {
multiline = Boolean(value.multiline);
minProperties = value.minProperties || Number.POSITIVE_INFINITY;
}
} else {
multiline = true;
}
return {multiline: multiline, minProperties: minProperties};
}
/**
* Normalizes a given option value.
*
* @param {string|Object|undefined} options - An option value to parse.
* @returns {{ObjectExpression: {multiline: boolean, minProperties: number}, ObjectPattern: {multiline: boolean, minProperties: number}}} Normalized option object.
*/
function normalizeOptions(options) {
if (options && (options.ObjectExpression || options.ObjectPattern)) {
return {
ObjectExpression: normalizeOptionValue(options.ObjectExpression),
ObjectPattern: normalizeOptionValue(options.ObjectPattern)
};
}
let value = normalizeOptionValue(options);
return {ObjectExpression: value, ObjectPattern: value};
}
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
module.exports = {
meta: {
docs: {
description: "enforce consistent line breaks inside braces",
category: "Stylistic Issues",
recommended: false
},
fixable: "whitespace",
schema: [
{
oneOf: [
OPTION_VALUE,
{
type: "object",
properties: {
ObjectExpression: OPTION_VALUE,
ObjectPattern: OPTION_VALUE
},
additionalProperties: false,
minProperties: 1
}
]
}
]
},
create: function(context) {
let sourceCode = context.getSourceCode();
let normalizedOptions = normalizeOptions(context.options[0]);
/**
* Reports a given node if it violated this rule.
*
* @param {ASTNode} node - A node to check. This is an ObjectExpression node or an ObjectPattern node.
* @param {{multiline: boolean, minProperties: number}} options - An option object.
* @returns {void}
*/
function check(node) {
let options = normalizedOptions[node.type];
let openBrace = sourceCode.getFirstToken(node);
let closeBrace = sourceCode.getLastToken(node);
let first = sourceCode.getTokenOrCommentAfter(openBrace);
let last = sourceCode.getTokenOrCommentBefore(closeBrace);
let needsLinebreaks = (
node.properties.length >= options.minProperties ||
(
options.multiline &&
node.properties.length > 0 &&
first.loc.start.line !== last.loc.end.line
)
);
/*
* Use tokens or comments to check multiline or not.
* But use only tokens to check whether line breaks are needed.
* This allows:
* var obj = { // eslint-disable-line foo
* a: 1
* }
*/
first = sourceCode.getTokenAfter(openBrace);
last = sourceCode.getTokenBefore(closeBrace);
if (needsLinebreaks) {
if (astUtils.isTokenOnSameLine(openBrace, first)) {
context.report({
message: "Expected a line break after this opening brace.",
node: node,
loc: openBrace.loc.start,
fix: function(fixer) {
return fixer.insertTextAfter(openBrace, "\n");
}
});
}
if (astUtils.isTokenOnSameLine(last, closeBrace)) {
context.report({
message: "Expected a line break before this closing brace.",
node: node,
loc: closeBrace.loc.start,
fix: function(fixer) {
return fixer.insertTextBefore(closeBrace, "\n");
}
});
}
} else {
if (!astUtils.isTokenOnSameLine(openBrace, first)) {
context.report({
message: "Unexpected line break after this opening brace.",
node: node,
loc: openBrace.loc.start,
fix: function(fixer) {
return fixer.removeRange([
openBrace.range[1],
first.range[0]
]);
}
});
}
if (!astUtils.isTokenOnSameLine(last, closeBrace)) {
context.report({
message: "Unexpected line break before this closing brace.",
node: node,
loc: closeBrace.loc.start,
fix: function(fixer) {
return fixer.removeRange([
last.range[1],
closeBrace.range[0]
]);
}
});
}
}
}
return {
ObjectExpression: check,
ObjectPattern: check
};
}
};
|
lauracurley/2016-08-ps-react
|
node_modules/eslint/lib/rules/object-curly-newline.js
|
JavaScript
|
mit
| 7,202 |
import random, math
import gimp_be
#from gimp_be.utils.quick import qL
from gimp_be.image.layer import editLayerMask
from effects import mirror
import numpy as np
import UndrawnTurtle as turtle
def brushSize(size=-1):
""""
Set brush size
"""
image = gimp_be.gimp.image_list()[0]
drawable = gimp_be.pdb.gimp_image_active_drawable(image)
if size < 1:
size = random.randrange(2, ((image.height + image.width) / 8))
gimp_be.pdb.gimp_context_set_brush_size(size)
# Set brush opacity
def brushOpacity(op=-1):
if op == -1:
op = random.randrange(15, 100)
gimp_be.pdb.gimp_brushes_set_opacity(op)
return op
# Set random brush color no parameters set random
def brushColor(r1=-1, g1=-1, b1=-1, r2=-1, g2=-1, b2=-1):
if not r1 == -1:
gimp_be.pdb.gimp_context_set_foreground((r1, g1, b1))
if not r2 == -1:
gimp_be.pdb.gimp_context_set_background((r2, g2, b2))
elif r1 == -1:
r1 = random.randrange(0, 255)
g1 = random.randrange(0, 255)
b1 = random.randrange(0, 255)
r2 = random.randrange(0, 255)
g2 = random.randrange(0, 255)
b2 = random.randrange(0, 255)
gimp_be.pdb.gimp_context_set_foreground((r1, g1, b1))
gimp_be.pdb.gimp_context_set_background((r2, g2, b2))
return (r1, g1, b1, r2, g2, b2)
#set gray scale color
def grayColor(gray_color):
gimp_be.pdb.gimp_context_set_foreground((gray_color, gray_color, gray_color))
# Set random brush
def randomBrush():
num_brushes, brush_list = gimp_be.pdb.gimp_brushes_get_list('')
brush_pick = brush_list[random.randrange(0, len(brush_list))]
gimp_be.pdb.gimp_brushes_set_brush(brush_pick)
return brush_pick
# Set random brush dynamics
def randomDynamics():
dynamics_pick = random.choice(gimp_be.pdb.gimp_dynamics_get_list('')[1])
gimp_be.pdb.gimp_context_set_dynamics(dynamics_pick)
return dynamics_pick
def qL():
# quick new layer
gimp_be.addNewLayer()
image = gimp_be.gimp.image_list()[0]
drawable = gimp_be.pdb.gimp_image_active_drawable(image)
gimp_be.pdb.gimp_edit_fill(drawable, 1)
def drawLine(points):
image = gimp_be.gimp.image_list()[0]
drawable = gimp_be.pdb.gimp_image_active_drawable(image)
gimp_be.pdb.gimp_paintbrush_default(drawable, len(points), points)
def drawSpiral(n=140, angle=61, step=10, center=[]):
coord=[]
nt=turtle.Turtle()
if center == []:
image = gimp_be.gimp.image_list()[0]
center=[image.width/2,image.height/2]
for step in range(n):
coord.append(int(nt.position()[0]*10)+center[0])
coord.append(int(nt.position()[1]*10)+center[1])
nt.forward(step)
nt.left(angle)
coord.append(int(nt.position()[0]*10)+center[0])
coord.append(int(nt.position()[1]*10)+center[1])
drawLine(coord)
def drawRays(rays=32, rayLength=100, centerX=0, centerY=0):
""""
draw N rays from center in active drawable with current brush
"""
image = gimp_be.gimp.image_list()[0]
drawable = gimp_be.pdb.gimp_image_active_drawable(image)
if centerX == 0:
centerX = image.width/2
if centerY == 0:
centerY = image.height/2
ray_gap = int(360.0/rays)
for ray in range(0,rays):
ctrlPoints = centerX, centerY, centerX + rayLength * math.sin(math.radians(ray*ray_gap)), centerY + rayLength * math.cos(math.radians(ray*ray_gap))
drawLine(ctrlPoints)
def drawRandomRays(rays=32, length=100, centerX=0, centerY=0,noise=0.3):
image = gimp_be.gimp.image_list()[0]
drawable = gimp_be.pdb.gimp_image_active_drawable(image)
if centerX == 0:
centerX = image.width/2
if centerY == 0:
centerY = image.height/2
ray_gap = 360.0/rays
for ray in range(0,rays):
rayLength=random.choice(range(int(length-length*noise),int(length+length*noise)))
random_angle=random.choice(np.arange(0.0,360.0,0.01))
ctrlPoints = [ centerX, centerY, centerX + int(rayLength * math.sin(math.radians(random_angle))), int(centerY + rayLength * math.cos(math.radians(random_angle)))]
drawLine(ctrlPoints)
def spikeBallStack(depth=20, layer_mode=6, flatten=0):
for x in range(1,depth):
image = gimp_be.gimp.image_list()[0]
drawable = gimp_be.pdb.gimp_image_active_drawable(image)
qL()
gimp_be.pdb.gimp_layer_set_mode(gimp_be.pdb.gimp_image_get_active_layer(image), layer_mode)
drawRandomRays(rays=random.choice([32,64,128,4]), length=(image.height/2-image.height/12), centerX=image.width/2, centerY=image.height/2,noise=random.choice([0.3,0.1,0.8]))
if flatten:
if not x%flatten:
gimp_be.pdb.gimp_image_flatten(image)
def randomStrokes(num = 4, opt = 1):
"""
Draw random strokes of random size and random position
"""
image = gimp_be.gimp.image_list()[0]
drawable = gimp_be.pdb.gimp_image_active_drawable(image)
r = random.randrange
for loopNum in range(0, num):
if opt == 1:
brushSize(35)
drawLine(ctrlPoints)
# draw random color bars, opt 3 uses random blend
def drawBars(barNum=10, opt=3):
image = gimp_be.gimp.image_list()[0]
drawable = gimp_be.pdb.gimp_image_active_drawable(image)
barWidth =image.width/ barNum
barLeft = 0
color = -1
for loopNum in range(0, barNum):
gimp_be.pdb.gimp_image_select_rectangle(image, 2, barLeft, 0, barWidth, image.height)
barLeft = barLeft + barWidth
if opt == 3:
randomBlend()
elif opt == 2:
color = brushColor()
gimp_be.pdb.gimp_edit_bucket_fill_full(drawable, 0, 0, 100, 0, 1, 0, gimp_be.SELECT_CRITERION_COMPOSITE, 0, 0)
else:
gimp_be.pdb.gimp_edit_bucket_fill_full(drawable, 0, 0, 100, 0, 1, 0, gimp_be.SELECT_CRITERION_COMPOSITE, 0, 0)
gimp_be.pdb.gimp_selection_none(image)
return (barNum, opt, color)
# draw carbon nano tube
def drawCNT():
image = gimp_be.gimp.image_list()[0]
drawable = gimp_be.pdb.gimp_image_active_drawable(image)
drawSinWave(1, 4, image.height * .42, 0, image.height / 2)
gimp_be.pdb.gimp_paintbrush(drawable, 0, 4, (0, (image.height - 80),image.width, (image.height - 80)), 0, 0)
gimp_be.pdb.gimp_paintbrush(drawable, 0, 4, (0, 80,image.width, 80), 0, 0)
# draw sine wave
def drawSinWave(bar_space=32, bar_length=-1, mag=70, x_offset=-1, y_offset=-1):
image = gimp_be.gimp.image_list()[0]
if y_offset == -1:
y_offset = image.height/2
if x_offset == -1:
x_offset = 0
if bar_length == -1:
bar_length = image.height/6
steps = image.width / bar_space
x = 0
for cStep in range(0, steps):
x = cStep * bar_space + x_offset
y = int(round(math.sin(x) * mag) + y_offset)
ctrlPoints = x, int(y - round(bar_length / 2)), x, int(y + round(bar_length / 2))
drawLine(ctrlPoints)
# draw sine wave
def drawSinWaveDouble(barSpace, barLen, mag):
image = gimp_be.gimp.image_list()[0]
steps =image.width/ barSpace
x = 0
for cStep in range(1, steps):
x = cStep * barSpace
y = int(abs(round(math.sin(x) * mag + image.height / 2)))
ctrlPoints = x, int(y - round(barLen / 2)), x, int(y + round(barLen / 2))
drawLine(ctrlPoints)
# draw a single brush point
def drawBrush(x1, y1):
image = gimp_be.gimp.image_list()[0]
drawable = gimp_be.pdb.gimp_image_active_drawable(image)
ctrlPoints = (x1, y1, x1, y1)
drawLine(ctrlPoints)
# draw multiple brush points
def drawMultiBrush(brush_strokes=24):
image = gimp_be.gimp.image_list()[0]
grid_width=image.width/int(math.sqrt(brush_strokes))
grid_height=image.height/int(math.sqrt(brush_strokes))
coord_x=0
coord_y = 0
for i in range(0, int(math.sqrt(brush_strokes))):
coord_x = coord_x + grid_width
for x in range(0, int(math.sqrt(brush_strokes))):
coord_y = coord_y + grid_height
drawBrush(coord_x, coord_y)
coord_y = 0
#draw grid of dots, this is for remainder mapping, this incomplete and temp. ####====DONT FORGET
def dotGrid():
image = gimp_be.gimp.image_list()[0]
drawable = gimp_be.pdb.gimp_image_active_drawable(image)
for i in range(10,image.width-10,20):
for x in range(10, image.height-10,20):
grayColor(abs(i^3-x^3)%256)
drawBrush(i+10,x+10)
# draws random dots, opt does random color
def randomCircleFill(num=20, size=100, opt=3, sq=1):
image = gimp_be.gimp.image_list()[0]
drawable = gimp_be.pdb.gimp_image_active_drawable(image)
for loopNum in range(0, num):
cirPar = [random.randrange(0,image.width), random.randrange(0, image.height), random.randrange(10, size),
random.randrange(10, size)]
if opt % 2 == 0:
brushColor()
if sq:
gimp_be.pdb.gimp_ellipse_select(image, cirPar[0], cirPar[1], cirPar[2], cirPar[2], 2, 1, 0, 0)
else:
gimp_be.pdb.gimp_ellipse_select(image, cirPar[0], cirPar[1], cirPar[2], cirPar[3], 2, 1, 0, 0)
if opt % 3 == 3:
randomBlend()
else:
gimp_be.pdb.gimp_edit_bucket_fill_full(drawable, 0, 0, 100, 0, 1, 0, gimp_be.SELECT_CRITERION_COMPOSITE, 0, 0)
gimp_be.pdb.gimp_selection_none(image)
def randomRectFill(num=20, size=100, opt=3, sq=0):
# draws square, opt does random color
image = gimp_be.gimp.image_list()[0]
drawable = gimp_be.pdb.gimp_image_active_drawable(image)
selectMode = 2
if opt % 5 == 0:
selectMode = 0
for loopNum in range(0, num):
if opt % 2 == 0:
brushColor()
rectPar = [random.randrange(0,image.width), random.randrange(0, image.height), random.randrange(10, size),
random.randrange(10, size)]
if sq:
gimp_be.pdb.gimp_image_select_rectangle(image, 2, rectPar[0], rectPar[1], rectPar[2], rectPar[2])
else:
gimp_be.pdb.gimp_image_select_rectangle(image, 2, rectPar[0], rectPar[1], rectPar[2], rectPar[3])
if opt % 3 == 0:
randomBlend()
else:
gimp_be.pdb.gimp_edit_bucket_fill_full(drawable, 0, 0, 100, 0, 1, 0, gimp_be.SELECT_CRITERION_COMPOSITE, 0, 0)
gimp_be.pdb.gimp_selection_none(image)
def randomBlend():
# Random Blend tool test
blend_mode = 0
paint_mode = 0
gradient_type = random.randrange(0, 10)
opacity = random.randrange(20, 100)
offset = 0
repeat = random.randrange(0, 2)
reverse = 0
supersample = 0
max_depth = random.randrange(1, 9)
threshold = 0
threshold = random.randrange(0, 1)
dither = 0
image = gimp_be.gimp.image_list()[0]
drawable = gimp_be.pdb.gimp_image_active_drawable(image)
brushColor()
x1 = random.randrange(0,image.width)
y1 = random.randrange(0, image.height)
x2 = random.randrange(0,image.width)
y2 = random.randrange(0, image.height)
gimp_be.pdb.gimp_blend(drawable, blend_mode, paint_mode, gradient_type, opacity, offset, repeat, reverse, supersample, max_depth, threshold, dither, x1, y1, x2, y2)
def randomPoints(num=12):
d = []
for x in range(num):
d.append(choice(range(boarder,image.width-boarder)))
d.append(choice(range(boarder,image.height-boarder)))
return d
def drawInkBlot(option=''):
image=gimp_be.gimp.image_list()[0]
layer=gimp_be.pdb.gimp_image_get_active_layer(image)
if 'trippy' in option:
layer_copy = gimp_be.pdb.gimp_layer_copy(layer, 0)
gimp_be.pdb.gimp_image_add_layer(image, layer_copy,1)
randomBlend()
mask = gimp_be.pdb.gimp_layer_create_mask(layer,5)
gimp_be.pdb.gimp_image_add_layer_mask(image, layer,mask)
editLayerMask(1)
randomCircleFill(num=15,size=800)
brushColor(255,255,255)
randomCircleFill(num=50,size=100)
randomCircleFill(num=5,size=300)
brushColor(0)
randomCircleFill(num=20,size=600)
randomCircleFill(num=50,size=400)
randomCircleFill(num=100,size=100)
brushColor(255,255,255)
randomCircleFill(num=50,size=100)
brushColor(0)
drawable = gimp_be.pdb.gimp_image_active_drawable(image)
brushSize()
strokes=[random.randrange(0,image.width/2),random.randrange(0,image.height),random.randrange(0,image.width/2),random.randrange(0,image.height)]
gimp_be.pdb.gimp_smudge(drawable, random.choice([1,5,10,50,100]), len(strokes), strokes)
brushSize()
strokes=[random.randrange(0,image.width/2),random.randrange(0,image.height),random.randrange(0,image.width/2),random.randrange(0,image.height)]
gimp_be.pdb.gimp_smudge(drawable, random.choice([1,5,10,50,100]), len(strokes), strokes)
mirror('h')
if 'trippy' in option and random.choice([0,1]):
drawable = gimp_be.pdb.gimp_image_active_drawable(image)
gimp_be.pdb.gimp_invert(drawable)
editLayerMask(0)
def inkBlotStack(depth=16,layer_mode=6, flatten=0):
for x in range(1,depth):
image = gimp_be.gimp.image_list()[0]
drawable = gimp_be.pdb.gimp_image_active_drawable(image)
qL()
gimp_be.pdb.gimp_layer_set_mode(gimp_be.pdb.gimp_image_get_active_layer(image), layer_mode)
drawInkBlot()
if flatten:
if not x%flatten:
flatten()
def gridCenters(grid=[]):
if grid==[]:
grid=[4,3]
image = gimp_be.gimp.image_list()[0]
row_width = image.width/(grid[0])
columb_height = image.height/(grid[1])
tile_centers = []
for row in range(0,grid[0]):
for columb in range(0,grid[1]):
tile_centers.append([row_width*row+row_width/2,columb_height*columb+columb_height/2])
return tile_centers
def tile(grid=[],option="mibd",irregularity=0.3):
image=gimp_be.gimp.image_list()[0]
layer=gimp_be.pdb.gimp_image_get_active_layer(image)
if grid==[]:
if image.height == image.width:
grid=[4,4]
elif image.height < image.width:
grid=[3,4]
else:
grid=[4,3]
if "m" in option:
mask = gimp_be.pdb.gimp_layer_create_mask(layer,0)
gimp_be.pdb.gimp_image_add_layer_mask(image, layer,mask)
editLayerMask(1)
drawable = gimp_be.pdb.gimp_image_active_drawable(image)
grid_spacing = image.width/grid[0]
tile_centers=gridCenters(grid)
if irregularity > 0.0:
i_tiles=[]
for tile in tile_centers:
tile[0]=tile[0]+random.randrange((-1*int(grid_spacing*irregularity)),int(grid_spacing*irregularity))
tile[1]=tile[1]+random.randrange((-1*int(grid_spacing*irregularity)),int(grid_spacing*irregularity))
i_tiles.append(tile)
tile_centers=i_tiles
if "b" in option:
randomBrush()
if "d" in option:
randomDynamics()
brushSize(grid_spacing)
brushColor(0,0,0)
for tile in tile_centers:
if "m" in option:
editLayerMask(1)
if irregularity == 0:
gimp_be.pdb.gimp_paintbrush_default(drawable, len(tile), tile)
elif random.randrange(50.0*irregularity)+random.randrange(50.0*irregularity)>50.0:
randomDynamics()
else:
gimp_be.pdb.gimp_paintbrush_default(drawable, len(tile), tile)
if "g" in option:
gimp_be.pdb.plug_in_gauss(image, drawable, 20.0, 20.0, 0)
if "w" in option:
gimp_be.pdb.plug_in_whirl_pinch(image, drawable, 90, 0.0, 1.0)
if "i" in option:
gimp_be.pdb.gimp_invert(drawable)
if "m" in option:
editLayerMask(0)
def drawAkuTree(branches=6,tree_height=0, position=0):
image = gimp_be.gimp.image_list()[0]
drawable = gimp_be.pdb.gimp_image_active_drawable(image)
if position==0:
position=[]
position.append(random.randrange(image.width))
position.append(random.randrange(4*tree_height/3, 3*image.height/4))
if tree_height == 0:
tree_height=random.randrange(position[1]/3, position[1]-position[1]/25)
print 'position:' + str(position)
#draw trunk
trunk=[position[0],position[1],position[0],position[1]-tree_height]
trunk_size=tree_height/40+3
print str(trunk)
print 'tree_height: ' + str(tree_height)
print 'trunk size: ' + str(trunk_size)
brushSize(trunk_size)
drawLine(trunk)
for node in range(branches):
node_base=[position[0],position[1]-((node*tree_height+1)/branches+tree_height/25+random.randrange(-1*tree_height/12,tree_height/12))]
base_length=tree_height/25
node_end=[]
if node%2==0:
node_end=[node_base[0]+base_length/2,node_base[1]-base_length/2]
brushSize(2*trunk_size/3)
drawLine([node_base[0],node_base[1],node_end[0],node_end[1]])
brushSize(trunk_size/3)
drawLine([node_end[0],node_end[1],node_end[0],node_end[1]-tree_height/12-(tree_height/48)])
else:
node_end=[node_base[0]-base_length/2,node_base[1]-base_length/2]
brushSize(2*trunk_size/3)
drawLine([node_base[0],node_base[1],node_end[0],node_end[1]])
brushSize(trunk_size/3)
drawLine([node_end[0],node_end[1],node_end[0],node_end[1]-(tree_height/12)])
def drawAkuForest(num=25):
for x in range(num):
drawAkuTree()
# draw a tree
def drawTree(x1=-1, y1=-1, angle=270, depth=9, recursiondepth=0):
image = gimp_be.gimp.image_list()[0]
drawable = gimp_be.pdb.gimp_image_active_drawable(image)
if x1 == -1:
x1 = image.width/2
if y1 == -1:
y1 = image.height/2
x2 = x1 + int(math.cos(math.radians(angle)) * depth * 10.0)
y2 = y1 + int(math.sin(math.radians(angle)) * depth * 10.0)
ctrlPoints = (x1, y1, x2, y2)
if recursiondepth <= 2:
brushColor(87, 53, 12)
elif depth == 1:
brushColor(152, 90, 17)
elif depth <= 3:
brushColor(7, 145, 2)
brushSize(depth * 4 + 5)
gimp_be.pdb.gimp_paintbrush_default(drawable, len(ctrlPoints), ctrlPoints)
if depth > 0:
drawTree(x2, y2, angle - 20, depth - 1, recursiondepth + 1)
drawTree(x2, y2, angle + 20, depth - 1, recursiondepth + 1)
# draw a tree with 3 branches per node
def drawTriTree(x1=-1, y1=-1, angle=270, depth=6, recursiondepth=0, size=10):
image = gimp_be.gimp.image_list()[0]
drawable = gimp_be.pdb.gimp_image_active_drawable(image)
if x1 == -1:
x1 = image.width/2
if y1 == -1:
y1 = image.height/2
if depth:
x2 = x1 + int(math.cos(math.radians(angle)) * depth * size) + random.randrange(-12, 12)
y2 = y1 + int(math.sin(math.radians(angle)) * depth * size) + random.randrange(-12, 12)
ctrlPoints = (x1, y1, x2, y2)
brushSize(depth + int(size/10))
brushColor()
gimp_be.pdb.gimp_paintbrush_default(drawable, len(ctrlPoints), ctrlPoints)
drawTriTree(x2, y2, angle - 30, depth - 1, recursiondepth + 1,size)
drawTriTree(x2, y2, angle, depth - 1, recursiondepth + 1,size)
drawTriTree(x2, y2, angle + 30, depth - 1, recursiondepth + 1,size)
# draw random color tri-tree
def drawColorTriTree(x1=-1, y1=-1, angle=270, depth=9, recursiondepth=0):
image = gimp_be.gimp.image_list()[0]
drawable = gimp_be.pdb.gimp_image_active_drawable(image)
if x1 == -1:
x1 = image.width/2
if y1 == -1:
y1 = image.height/2
brushSize(depth + 1)
if depth:
x2 = x1 + int(math.cos(math.radians(angle)) * depth * 10.0) + random.randrange(-12, 12)
y2 = y1 + int(math.sin(math.radians(angle)) * depth * 10.0) + random.randrange(-12, 12)
ctrlPoints = (x1, y1, x2, y2)
gimp_be.pdb.gimp_paintbrush_default(drawable, len(ctrlPoints), ctrlPoints)
drawColorTriTree(x2, y2, angle - 20 + random.choice(-10, -5, 0, 5, 10), depth - 1, recursiondepth + 1)
drawColorTriTree(x2, y2, angle + random.choice(-10, -5, 0, 5, 10), depth - 1, recursiondepth + 1)
drawColorTriTree(x2, y2, angle + 20 + random.choice(-10, -5, 0, 5, 10), depth - 1, recursiondepth + 1)
# draw a tree
def drawOddTree(x1=-1, y1=-1, angle=270, depth=9, recursiondepth=0):
image = gimp_be.gimp.image_list()[0]
drawable = gimp_be.pdb.gimp_image_active_drawable(image)
if x1 == -1:
x1 = image.width/2
if y1 == -1:
y1 = image.height/2
brushSize((depth * 8 + 30))
if depth:
x2 = x1 + int(math.cos(math.radians(angle)) * depth * 10.0)
y2 = y1 + int(math.sin(math.radians(angle)) * depth * 10.0)
ctrlPoints = (x1, y1, x2, y2)
gimp_be.pdb.gimp_paintbrush_default(drawable, len(ctrlPoints), ctrlPoints)
if not random.randrange(0, 23) == 23:
drawTree(x2, y2, angle - 20, depth - 1, recursiondepth + 1)
if depth % 2 == 0:
drawTree(x2, y2, angle + 20, depth - 1, recursiondepth + 1)
if (depth + 1) % 4 == 0:
drawTree(x2, y2, angle + 20, depth - 1, recursiondepth + 1)
if depth == 5:
drawTree(x2, y2, angle - 45, depth - 1, recursiondepth + 1)
drawTree(x2, y2, angle + 45, depth - 1, recursiondepth + 1)
# draw a tree
def drawForestTree(x1=-1, y1=-1, angle=270, depth=7, size=10, recursiondepth=0):
image = gimp_be.gimp.image_list()[0]
drawable = gimp_be.pdb.gimp_image_active_drawable(image)
if x1 == -1:
x1 = image.width/2
if y1 == -1:
y1 = image.height/2
if depth:
x2 = x1 + int(math.cos(math.radians(angle)) * depth * 10.0)
y2 = y1 + int(math.sin(math.radians(angle)) * depth * 10.0)
ctrlPoints = (x1, y1, x2, y2)
brushSize(depth * depth * (int(size / ((image.height - y1)) / image.height)) + 4)
gimp_be.pdb.gimp_paintbrush_default(drawable, len(ctrlPoints), ctrlPoints)
if not random.randrange(0, 23) == 23:
drawForestTree(x2, y2, angle - 20, depth - 1, size, recursiondepth + 1)
if random.randrange(0, 23) == 23:
drawForestTree(x2, y2, angle - random.randrange(-30, 30), depth - 1, size, recursiondepth + 1)
drawForestTree(x2, y2, angle - random.randrange(-30, 30), depth - 1, size, recursiondepth + 1)
drawForestTree(x2, y2, angle - random.randrange(-30, 30), depth - 1, size, recursiondepth + 1)
else:
drawForestTree(x2, y2, angle - random.randrange(15, 50), depth - 1, size, recursiondepth + 1)
if depth % 2 == 0:
drawForestTree(x2, y2, angle + 20, depth - 1, size, recursiondepth + 1)
if (depth + 1) % 4 == 0:
drawForestTree(x2, y2, angle + 20, depth - 1, size, recursiondepth + 1)
if depth == 5:
drawForestTree(x2, y2, angle - 45, depth - 1, size, recursiondepth + 1)
drawForestTree(x2, y2, angle + 45, depth - 1, size, recursiondepth + 1)
# draw a series of trees with a y position based on depth
def drawForest(trees, options):
image = gimp_be.gimp.image_list()[0]
for tree in range(0, trees):
y1 = 2 * (image.height / 3) + random.randrange(-1 * (image.height / 5), image.height / 5)
x1 = random.randrange(image.width / 20, 19 * (image.width / 20))
angle = random.randrange(250, 290)
size = (y1 / (2.0 * (image.height / 3.0) + (image.height / 5.0))) + 4
depth = random.randrange(3, 7)
drawForestTree(x1, y1, angle, depth, size)
#draws polygon of N sides at a x-y location
def drawPolygon(sides=5,size=300,x_pos=0,y_pos=0, angle_offset=0):
image = gimp_be.gimp.image_list()[0]
drawable = gimp_be.pdb.gimp_image_active_drawable(image)
if y_pos==0:
y_pos=image.height/2
if x_pos==0:
x_pos=image.width/2
degree_between_points=360/sides
points_list=[]
for x in range(0,sides+1):
point_degree=degree_between_points*x+angle_offset
points_list.append(int(round(math.sin(math.radians(point_degree))*size))+x_pos)
points_list.append(int(round(math.cos(math.radians(point_degree))*size))+y_pos)
fade_out=0
method=0
gradient_length=0
gimp_be.pdb.gimp_paintbrush(drawable, fade_out, len(points_list), points_list, method, gradient_length)
#draw a grid of polygons of N sides
def drawPolygonGrid(size=60,sides=3, angle_offset=0):
image = gimp_be.gimp.image_list()[0]
drawable = gimp_be.pdb.gimp_image_active_drawable(image)
if sides%2 == 1 or sides>4:
for y in range(0-image.height/10,image.height+image.height/10, size):
x_loop=0
for x in range(0-image.width/10, image.width+image.width/10, size):
if x_loop%2==1:
drawPolygon(sides,size-size/2,x-(size/2),y,360/sides)
else:
drawPolygon(sides,size-size/2,x,y,0)
x_loop=x_loop+1
else:
for x in range(0-image.height/10,image.height+image.height/10, size):
for y in range(0-image.width/10, image.width+image.width/10, size):
drawPolygon(sides,size/3,x,y,0)
degree_between_points=360/sides
points_list=[]
for x in range(0,sides+1):
point_degree=math.radians(degree_between_points*x+angle_offset)
points_list.append(int(round(math.sin(point_degree)*size)))
points_list.append(int(round(math.cos(point_degree)*size)))
fade_out=0
method=0
gradient_length=0
gimp_be.pdb.gimp_paintbrush(drawable, fade_out, len(points_list), points_list, method, gradient_length)
def drawFrygon(sides=5,size=300,x_pos=0,y_pos=0, angle_offset=0):
image = gimp_be.gimp.image_list()[0]
drawable = gimp_be.pdb.gimp_image_active_drawable(image)
if y_pos==0:
y_pos=image.height/2
if x_pos==0:
x_pos=image.width/2
degree_between_points=360/sides
points_list=[]
for x in range(0,sides+1):
point_degree=degree_between_points*x+angle_offset
points_list.append(int(round(math.sin(point_degree)*size))+y_pos)
points_list.append(int(round(math.cos(point_degree)*size))+x_pos)
fade_out=0
method=0
gradient_length=0
gimp_be.pdb.gimp_paintbrush(drawable, fade_out, len(points_list), points_list, method, gradient_length)
def drawFrygonGrid(size=120,sides=13):
global height, width
if sides%2 == 1:
for x in range(0,height,size):
x_deep=0
for y in range(0, width,size):
if x_deep%2==1:
drawFrygon(sides,size,x,y-(size/2),0)
else:
drawFrygon(sides,size,x,y,0)
x_deep=x_deep+1
else:
for x in range(0,height, size):
for y in range(0, width, size):
drawFrygon(sides,size,x,y,0)
|
J216/gimp_be
|
gimp_be/draw/draw.py
|
Python
|
mit
| 26,770 |
import {Option} from "./option";
export class HelpOption extends Option {
/**
*
*/
constructor() {
super();
this.shortName = 'h';
this.longName = 'help';
this.argument = '';
}
}
|
scipper/angularjs-cli
|
src/angularjs-cli/options/help.option.ts
|
TypeScript
|
mit
| 210 |
import * as React from 'react';
import { createIcon } from '../Icon';
export const ShieldIcon = createIcon(
<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" />,
'ShieldIcon'
);
|
keystonejs/keystone
|
design-system/packages/icons/src/icons/ShieldIcon.tsx
|
TypeScript
|
mit
| 186 |
"use strict";
var GLOBAL_MOUNT_POINT_MAX = Math.pow(2, 53);
var util = {
uuid: function(){
return Math.ceil(Math.random() * GLOBAL_MOUNT_POINT_MAX);
}
};
module.exports = util;
|
Ovaldi/node-cqrs
|
src/util.js
|
JavaScript
|
mit
| 194 |
<?php
namespace ToyLang\Core\Lexer;
use ToyLang\Core\Lexer\Token\Token;
use ToyLang\Core\Lexer\Token\TokenType;
interface Lexer
{
/**
* @param TokenType $tokenType
* @return $this
*/
public function addTokenType(TokenType $tokenType);
/**
* @param TokenType[] $tokenTypes
* @return $this
*/
public function addTokenTypes($tokenTypes);
/**
* @param $input
* @return Token[]
*/
public function tokenize($input);
}
|
estelsmith/toy-language
|
src/Core/Lexer/Lexer.php
|
PHP
|
mit
| 486 |
require 'test_helper'
class CustomerQuestionshipTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
|
chinxianjun/autorepair
|
test/unit/customer_questionship_test.rb
|
Ruby
|
mit
| 134 |
/**
* @author Mat Groves http://matgroves.com/ @Doormat23
*/
/**
* A DisplayObjectContainer represents a collection of display objects.
* It is the base class of all display objects that act as a container for other objects.
*
* @class DisplayObjectContainer
* @extends DisplayObject
* @constructor
*/
PIXI.DisplayObjectContainer = function()
{
PIXI.DisplayObject.call( this );
/**
* [read-only] The of children of this container.
*
* @property children
* @type Array<DisplayObject>
* @readOnly
*/
this.children = [];
}
// constructor
PIXI.DisplayObjectContainer.prototype = Object.create( PIXI.DisplayObject.prototype );
PIXI.DisplayObjectContainer.prototype.constructor = PIXI.DisplayObjectContainer;
/**
* Adds a child to the container.
*
* @method addChild
* @param child {DisplayObject} The DisplayObject to add to the container
*/
PIXI.DisplayObjectContainer.prototype.addChild = function(child)
{
if(child.parent != undefined)
{
//// COULD BE THIS???
child.parent.removeChild(child);
// return;
}
child.parent = this;
this.children.push(child);
// update the stage refference..
if(this.stage)
{
var tmpChild = child;
do
{
if(tmpChild.interactive)this.stage.dirty = true;
tmpChild.stage = this.stage;
tmpChild = tmpChild._iNext;
}
while(tmpChild)
}
// LINKED LIST //
// modify the list..
var childFirst = child.first
var childLast = child.last;
var nextObject;
var previousObject;
// this could be wrong if there is a filter??
if(this._filters || this._mask)
{
previousObject = this.last._iPrev;
}
else
{
previousObject = this.last;
}
nextObject = previousObject._iNext;
// always true in this case
// need to make sure the parents last is updated too
var updateLast = this;
var prevLast = previousObject;
while(updateLast)
{
if(updateLast.last == prevLast)
{
updateLast.last = child.last;
}
updateLast = updateLast.parent;
}
if(nextObject)
{
nextObject._iPrev = childLast;
childLast._iNext = nextObject;
}
childFirst._iPrev = previousObject;
previousObject._iNext = childFirst;
// need to remove any render groups..
if(this.__renderGroup)
{
// being used by a renderTexture.. if it exists then it must be from a render texture;
if(child.__renderGroup)child.__renderGroup.removeDisplayObjectAndChildren(child);
// add them to the new render group..
this.__renderGroup.addDisplayObjectAndChildren(child);
}
}
/**
* Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown
*
* @method addChildAt
* @param child {DisplayObject} The child to add
* @param index {Number} The index to place the child in
*/
PIXI.DisplayObjectContainer.prototype.addChildAt = function(child, index)
{
if(index >= 0 && index <= this.children.length)
{
if(child.parent != undefined)
{
child.parent.removeChild(child);
}
child.parent = this;
if(this.stage)
{
var tmpChild = child;
do
{
if(tmpChild.interactive)this.stage.dirty = true;
tmpChild.stage = this.stage;
tmpChild = tmpChild._iNext;
}
while(tmpChild)
}
// modify the list..
var childFirst = child.first;
var childLast = child.last;
var nextObject;
var previousObject;
if(index == this.children.length)
{
previousObject = this.last;
var updateLast = this;
var prevLast = this.last;
while(updateLast)
{
if(updateLast.last == prevLast)
{
updateLast.last = child.last;
}
updateLast = updateLast.parent;
}
}
else if(index == 0)
{
previousObject = this;
}
else
{
previousObject = this.children[index-1].last;
}
nextObject = previousObject._iNext;
// always true in this case
if(nextObject)
{
nextObject._iPrev = childLast;
childLast._iNext = nextObject;
}
childFirst._iPrev = previousObject;
previousObject._iNext = childFirst;
this.children.splice(index, 0, child);
// need to remove any render groups..
if(this.__renderGroup)
{
// being used by a renderTexture.. if it exists then it must be from a render texture;
if(child.__renderGroup)child.__renderGroup.removeDisplayObjectAndChildren(child);
// add them to the new render group..
this.__renderGroup.addDisplayObjectAndChildren(child);
}
}
else
{
throw new Error(child + " The index "+ index +" supplied is out of bounds " + this.children.length);
}
}
/**
* [NYI] Swaps the depth of 2 displayObjects
*
* @method swapChildren
* @param child {DisplayObject}
* @param child2 {DisplayObject}
* @private
*/
PIXI.DisplayObjectContainer.prototype.swapChildren = function(child, child2)
{
if(child === child2) {
return;
}
var index1 = this.children.indexOf(child);
var index2 = this.children.indexOf(child2);
if(index1 < 0 || index2 < 0) {
throw new Error("swapChildren: Both the supplied DisplayObjects must be a child of the caller.");
}
this.removeChild(child);
this.removeChild(child2);
if(index1 < index2)
{
this.addChildAt(child2, index1);
this.addChildAt(child, index2);
}
else
{
this.addChildAt(child, index2);
this.addChildAt(child2, index1);
}
}
/**
* Returns the Child at the specified index
*
* @method getChildAt
* @param index {Number} The index to get the child from
*/
PIXI.DisplayObjectContainer.prototype.getChildAt = function(index)
{
if(index >= 0 && index < this.children.length)
{
return this.children[index];
}
else
{
throw new Error(child + " Both the supplied DisplayObjects must be a child of the caller " + this);
}
}
/**
* Removes a child from the container.
*
* @method removeChild
* @param child {DisplayObject} The DisplayObject to remove
*/
PIXI.DisplayObjectContainer.prototype.removeChild = function(child)
{
var index = this.children.indexOf( child );
if ( index !== -1 )
{
// unlink //
// modify the list..
var childFirst = child.first;
var childLast = child.last;
var nextObject = childLast._iNext;
var previousObject = childFirst._iPrev;
if(nextObject)nextObject._iPrev = previousObject;
previousObject._iNext = nextObject;
if(this.last == childLast)
{
var tempLast = childFirst._iPrev;
// need to make sure the parents last is updated too
var updateLast = this;
while(updateLast.last == childLast)
{
updateLast.last = tempLast;
updateLast = updateLast.parent;
if(!updateLast)break;
}
}
childLast._iNext = null;
childFirst._iPrev = null;
// update the stage reference..
if(this.stage)
{
var tmpChild = child;
do
{
if(tmpChild.interactive)this.stage.dirty = true;
tmpChild.stage = null;
tmpChild = tmpChild._iNext;
}
while(tmpChild)
}
// webGL trim
if(child.__renderGroup)
{
child.__renderGroup.removeDisplayObjectAndChildren(child);
}
child.parent = undefined;
this.children.splice( index, 1 );
}
else
{
throw new Error(child + " The supplied DisplayObject must be a child of the caller " + this);
}
}
/*
* Updates the container's children's transform for rendering
*
* @method updateTransform
* @private
*/
PIXI.DisplayObjectContainer.prototype.updateTransform = function()
{
if(!this.visible)return;
PIXI.DisplayObject.prototype.updateTransform.call( this );
for(var i=0,j=this.children.length; i<j; i++)
{
this.children[i].updateTransform();
}
}
|
MKelm/pixi.js
|
src/pixi/display/DisplayObjectContainer.js
|
JavaScript
|
mit
| 7,407 |
function ga() {}
var _gaq = []
|
NonLogicalDev/ucsd_cat125
|
client/scripts/ga.js
|
JavaScript
|
mit
| 31 |
export { default } from 'ember-stripe-elements/components/stripe-card';
|
code-corps/ember-stripe-elements
|
app/components/stripe-card.js
|
JavaScript
|
mit
| 72 |
<?php
return [
/**
*--------------------------------------------------------------------------
* Default Broadcaster
*--------------------------------------------------------------------------
*
* This option controls the default broadcaster that will be used by the
* framework when an event needs to be broadcast. You may set this to
* any of the connections defined in the "connections" array below.
*
* Supported: "pusher", "redis", "log", "null"
*
*/
'default' => env('BROADCAST_DRIVER', 'null'),
/**
*--------------------------------------------------------------------------
* Broadcast Connections
*--------------------------------------------------------------------------
*
* Here you may define all of the broadcast connections that will be used
* to broadcast events to other systems or over websockets. Samples of
* each available type of connection are provided inside this array.
*
*/
'connections' => [
'pusher' => [
'driver' => 'pusher',
'key' => env('PUSHER_APP_KEY'),
'secret' => env('PUSHER_APP_SECRET'),
'app_id' => env('PUSHER_APP_ID'),
'options' => [
'cluster' => env('PUSHER_APP_CLUSTER'),
'encrypted' => true,
],
],
'redis' => [
'driver' => 'redis',
'connection' => 'default',
],
'log' => [
'driver' => 'log',
],
'null' => [
'driver' => 'null',
],
],
];
|
lioneil/pluma
|
config/broadcasting.php
|
PHP
|
mit
| 1,626 |
#include "binary_buffer.hpp"
#include <iterator>
#include <algorithm>
#include <sstream>
#include <boost/endian/conversion.hpp>
using boost::endian::native_to_big;
using boost::endian::big_to_native;
namespace {
using aria::byte;
template <typename P>
void append_bytes_to_vector(std::vector<byte> & vec, P primitive)
{
auto * begin = reinterpret_cast<byte *>(&primitive);
auto * end = begin + sizeof(primitive);
std::copy(begin, end, std::back_inserter(vec));
}
template <typename P>
P read_primitive_and_advance(const byte * buffer, size_t size, size_t & offset, const std::string & name)
{
size_t stride = sizeof(P);
if (offset + stride <= size) {
auto i = reinterpret_cast<const P *>(buffer + offset);
offset += stride;
return big_to_native(*i);
} else {
throw aria::internal::buffer_error("Insufficient bytes available to read " + name + ".");
}
}
}
aria::internal::buffer_error::buffer_error(const char *what)
: std::runtime_error(what)
{
}
aria::internal::buffer_error::buffer_error(const std::string &what)
: std::runtime_error(what)
{
}
void aria::internal::binary_buffer_writer::write_uint8(uint8_t i)
{
_bytes.push_back(static_cast<byte>(i));
}
void aria::internal::binary_buffer_writer::write_uint16(uint16_t i)
{
append_bytes_to_vector(_bytes, native_to_big(i));
}
void aria::internal::binary_buffer_writer::write_uint32(uint32_t i)
{
append_bytes_to_vector(_bytes, native_to_big(i));
}
void aria::internal::binary_buffer_writer::write_uint64(uint64_t i)
{
append_bytes_to_vector(_bytes, native_to_big(i));
}
void aria::internal::binary_buffer_writer::write_string(const std::string &str)
{
write_uint32(str.size());
for (auto c : str) {
_bytes.push_back(static_cast<byte>(c));
}
}
void aria::internal::binary_buffer_writer::write_bytes(const std::vector<aria::byte> &bytes)
{
write_uint32(bytes.size());
std::copy(bytes.begin(), bytes.end(), std::back_inserter(_bytes));
}
std::vector<aria::byte> aria::internal::binary_buffer_writer::take_buffer()
{
std::vector<byte> buffer;
_bytes.swap(buffer);
return buffer;
}
aria::internal::binary_buffer_reader::binary_buffer_reader(const std::vector<byte> * buffer)
: _buffer_start(buffer->data()), _buffer_size(buffer->size()), _offset(0)
{
}
uint8_t aria::internal::binary_buffer_reader::read_uint8()
{
return read_primitive_and_advance<uint8_t>(_buffer_start, _buffer_size, _offset, "uint8");
}
uint16_t aria::internal::binary_buffer_reader::read_uint16()
{
return read_primitive_and_advance<uint16_t>(_buffer_start, _buffer_size, _offset, "uint16");
}
uint32_t aria::internal::binary_buffer_reader::read_uint32()
{
return read_primitive_and_advance<uint32_t>(_buffer_start, _buffer_size, _offset, "uint32");
}
uint64_t aria::internal::binary_buffer_reader::read_uint64()
{
return read_primitive_and_advance<uint64_t>(_buffer_start, _buffer_size, _offset, "uint64");
}
std::string aria::internal::binary_buffer_reader::read_string()
{
uint32_t size;
try {
size = read_uint32();
} catch (buffer_error) {
throw buffer_error("Insufficient bytes available to read string size.");
}
if (_offset + size <= _buffer_size) {
auto data = reinterpret_cast<const char *>(_buffer_start + _offset);
_offset += size;
return std::string(data, size);;
} else {
assert(_offset <= _buffer_size);
auto available = _buffer_size - _offset;
std::stringstream ss;
ss << "Expected " << size << " bytes of string data, but only " << available
<< " available bytes in buffer.";
throw buffer_error(ss.str());
}
}
std::vector<byte> aria::internal::binary_buffer_reader::read_bytes()
{
uint32_t size;
try {
size = read_uint32();
} catch (buffer_error) {
throw buffer_error("Insufficient bytes available to read data size.");
}
if (_offset + size <= _buffer_size) {
auto data = _buffer_start + _offset;
_offset += size;
return std::vector<byte>(data, data + size);
} else {
assert(_offset <= _buffer_size);
auto available = _buffer_size - _offset;
std::stringstream ss;
ss << "Expected " << size << " bytes of data, but only " << available
<< " available bytes in buffer.";
throw buffer_error(ss.str());
}
}
|
Andlon/aria
|
src/util/binary_buffer.cpp
|
C++
|
mit
| 4,531 |
version https://git-lfs.github.com/spec/v1
oid sha256:a2aca9cd81f31f3e9e83559fdcfa84d3ee900090ee4baeb2bae129e9d06473eb
size 1264
|
yogeshsaroya/new-cdnjs
|
ajax/libs/foundation/5.4.1/js/foundation/foundation.equalizer.min.js
|
JavaScript
|
mit
| 129 |
const exec = require('child_process').exec
const path = require('path')
const fs = require('fs')
const execPath = process.execPath
const binPath = path.dirname(execPath)
const dep = path.join(execPath, '../../lib/node_modules/dep')
const repository = 'https://github.com/depjs/dep.git'
const bin = path.join(dep, 'bin/dep.js')
process.stdout.write(
'exec: git' + [' clone', repository, dep].join(' ') + '\n'
)
exec('git clone ' + repository + ' ' + dep, (e) => {
if (e) throw e
process.stdout.write('link: ' + bin + '\n')
process.stdout.write(' => ' + path.join(binPath, 'dep') + '\n')
fs.symlink(bin, path.join(binPath, 'dep'), (e) => {
if (e) throw e
})
})
|
depjs/dep
|
scripts/install.js
|
JavaScript
|
mit
| 676 |
using MongoDB.Driver;
namespace AspNet.Identity.MongoDB
{
public class IndexChecks
{
public static void EnsureUniqueIndexOnUserName<TUser>(IMongoCollection<TUser> users)
where TUser : IdentityUser
{
var userName = Builders<TUser>.IndexKeys.Ascending(t => t.UserName);
var unique = new CreateIndexOptions {Unique = true};
users.Indexes.CreateOneAsync(userName, unique);
}
public static void EnsureUniqueIndexOnRoleName<TRole>(IMongoCollection<TRole> roles)
where TRole : IdentityRole
{
var roleName = Builders<TRole>.IndexKeys.Ascending(t => t.Name);
var unique = new CreateIndexOptions {Unique = true};
roles.Indexes.CreateOneAsync(roleName, unique);
}
public static void EnsureUniqueIndexOnEmail<TUser>(IMongoCollection<TUser> users)
where TUser : IdentityUser
{
var email = Builders<TUser>.IndexKeys.Ascending(t => t.Email);
var unique = new CreateIndexOptions {Unique = true};
users.Indexes.CreateOneAsync(email, unique);
}
}
}
|
winterdouglas/aspnet-identity-mongo
|
src/AspNet.Identity.MongoDB/IndexChecks.cs
|
C#
|
mit
| 993 |
class SystemModule < ActiveRecord::Base
attr_accessible :name
def self.CUSTOMER
readonly.find_by_name("Customer")
end
def self.USER
readonly.find_by_name("User")
end
def self.CONTACT
readonly.find_by_name("Contact")
end
end
|
woese/guara-crm
|
app/models/system_module.rb
|
Ruby
|
mit
| 262 |
package org.aikodi.chameleon.support.statement;
import org.aikodi.chameleon.core.declaration.Declaration;
import org.aikodi.chameleon.core.element.ElementImpl;
import org.aikodi.chameleon.core.lookup.DeclarationSelector;
import org.aikodi.chameleon.core.lookup.LookupContext;
import org.aikodi.chameleon.core.lookup.LookupException;
import org.aikodi.chameleon.core.lookup.SelectionResult;
import org.aikodi.chameleon.core.validation.Valid;
import org.aikodi.chameleon.core.validation.Verification;
import org.aikodi.chameleon.oo.statement.ExceptionSource;
import org.aikodi.chameleon.oo.statement.Statement;
import org.aikodi.chameleon.util.association.Multi;
import java.util.Collections;
import java.util.List;
/**
* A list of statement expressions as used in the initialization clause of a for
* statement. It contains a list of statement expressions.
*
* @author Marko van Dooren
*/
public class StatementExprList extends ElementImpl implements ForInit, ExceptionSource {
public StatementExprList() {
}
/**
* STATEMENT EXPRESSIONS
*/
private Multi<StatementExpression> _statementExpressions = new Multi<StatementExpression>(this);
public void addStatement(StatementExpression statement) {
add(_statementExpressions, statement);
}
public void removeStatement(StatementExpression statement) {
remove(_statementExpressions, statement);
}
public List<StatementExpression> statements() {
return _statementExpressions.getOtherEnds();
}
@Override
public StatementExprList cloneSelf() {
return new StatementExprList();
}
public int getIndexOf(Statement statement) {
return statements().indexOf(statement) + 1;
}
public int getNbStatements() {
return statements().size();
}
@Override
public List<? extends Declaration> locallyDeclaredDeclarations() throws LookupException {
return declarations();
}
@Override
public List<? extends Declaration> declarations() throws LookupException {
return Collections.EMPTY_LIST;
}
@Override
public LookupContext localContext() throws LookupException {
return language().lookupFactory().createLocalLookupStrategy(this);
}
@Override
public <D extends Declaration> List<? extends SelectionResult<D>> declarations(DeclarationSelector<D> selector)
throws LookupException {
return Collections.emptyList();
}
@Override
public Verification verifySelf() {
return Valid.create();
}
}
|
markovandooren/chameleon
|
src/org/aikodi/chameleon/support/statement/StatementExprList.java
|
Java
|
mit
| 2,449 |
"use strict";
ace.define("ace/snippets/matlab", ["require", "exports", "module"], function (e, t, n) {
"use strict";
t.snippetText = undefined, t.scope = "matlab";
});
|
IonicaBizau/arc-assembler
|
clients/ace-builds/src-min-noconflict/snippets/matlab.js
|
JavaScript
|
mit
| 172 |
(function(){
/**
* PubSub implementation (fast)
*/
var PubSub = function PubSub( defaultScope ){
if (!(this instanceof PubSub)){
return new PubSub( defaultScope );
}
this._topics = {};
this.defaultScope = defaultScope || this;
};
PubSub.prototype = {
/**
* Subscribe a callback (or callbacks) to a topic (topics).
*
* @param {String|Object} topic The topic name, or a config with key/value pairs of { topic: callbackFn, ... }
* @param {Function} fn The callback function (if not using Object as previous argument)
* @param {Object} scope (optional) The scope to bind callback to
* @param {Number} priority (optional) The priority of the callback (higher = earlier)
* @return {this}
*/
subscribe: function( topic, fn, scope, priority ){
var listeners = this._topics[ topic ] || (this._topics[ topic ] = [])
,orig = fn
,idx
;
// check if we're subscribing to multiple topics
// with an object
if ( Physics.util.isObject( topic ) ){
for ( var t in topic ){
this.subscribe( t, topic[ t ], fn, scope );
}
return this;
}
if ( Physics.util.isObject( scope ) ){
fn = Physics.util.bind( fn, scope );
fn._bindfn_ = orig;
} else if (!priority) {
priority = scope;
}
fn._priority_ = priority;
idx = Physics.util.sortedIndex( listeners, fn, '_priority_' );
listeners.splice( idx, 0, fn );
return this;
},
/**
* Unsubscribe function from topic
* @param {String} topic Topic name
* @param {Function} fn The original callback function
* @return {this}
*/
unsubscribe: function( topic, fn ){
var listeners = this._topics[ topic ]
,listn
;
if (!listeners){
return this;
}
for ( var i = 0, l = listeners.length; i < l; i++ ){
listn = listeners[ i ];
if ( listn._bindfn_ === fn || listn === fn ){
listeners.splice(i, 1);
break;
}
}
return this;
},
/**
* Publish data to a topic
* @param {Object|String} data
* @param {Object} scope The scope to be included in the data argument passed to callbacks
* @return {this}
*/
publish: function( data, scope ){
if (typeof data !== 'object'){
data = { topic: data };
}
var topic = data.topic
,listeners = this._topics[ topic ]
,l = listeners && listeners.length
;
if ( !topic ){
throw 'Error: No topic specified in call to world.publish()';
}
if ( !l ){
return this;
}
data.scope = data.scope || this.defaultScope;
while ( l-- ){
data.handler = listeners[ l ];
data.handler( data );
}
return this;
}
};
Physics.util.pubsub = PubSub;
})();
|
lejoying/ibrainstroms
|
web/PhysicsJS/src/util/pubsub.js
|
JavaScript
|
mit
| 3,581 |
function fixPosition() {
console.log($(window).scrollTop());
// if its anywhee but at the very top of the screen, fix it
if ($(window).scrollTop() >= headerHeight) { // magic number offset that just feels right to prevent the 'bounce'
// if (headPosition.top > 0){
$('body').addClass('js-fix-positions');
}
// otherwise, make sure its not fixed
else {
$('body').removeClass('js-fix-positions');
}
};
//Generate the weight guide meter with JS as its pretty useless without it, without some server side intervention
function createBasketWeightGuide(){
// create the element for the guide
$('.af__basket__weight-guide--label').after('<div class="js-af__weight-guide__wrapper"></div>');
$('.js-af__weight-guide__wrapper').append('<div class="js-af__weight-guide__meter"></div>');
$('.af__product__add-to-basket').submit(function(e){
e.preventDefault();
//var $multiplier=
weightGuideListener();
})
}
function weightGuideListener(){
var $bar = $('.js-af__weight-guide__meter');
//Didnt work as expected, so used this for speed: http://stackoverflow.com/questions/12945352/change-width-on-click-using-jquery
var $percentage = (100 * parseFloat($bar.css('width')) / parseFloat($bar.parent().css('width')) +10 + '%');
$bar.css("width", $percentage);
var $message = $('.af__basket__weight-guide--cta');
currentWidth=parseInt($percentage);
console.log(currentWidth);
// cannot use switch for less than
if (currentWidth <= 21 ){
$message.text('Plenty of room');
}
else if (currentWidth <= 45){
$bar.css('background-color', '#ee0');
}
else if (currentWidth <= 65){
$bar.css('background-color', '#c1ea39');
$message.text('Getting there...')
}
else if (currentWidth <= 80){
$message.text('Room for a little one?');
}
else if (currentWidth <= 89){
$message.text('Almost full!');
}
else if (currentWidth >= 95 && currentWidth <= 99){
$message.text('Lookin\' good!');
}
else if (currentWidth <= 99.9){
$bar.css('background-color', '#3ece38');
}
else {
$bar.css('background-color', '#d00');
$bar.css("width", "100%");
$message.text('(Delivery band 2 logic)');
}
}
function selectOnFocus(){
$('.af__product__add-to-basket input').focus(function(){
this.select();
})
};
$(document).ready(function(){
headerHeight=$('.af__header').outerHeight(); // icnludes padding and margins
scrollIntervalID = setInterval(fixPosition, 16); // = 60 FPS
createBasketWeightGuide();
selectOnFocus();
});
|
brtdesign/brtdesign.github.io
|
work/af-december2016/assets/js/_default.js
|
JavaScript
|
mit
| 2,769 |