code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
/****************************************************************************
Copyright (c) 2010 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#ifndef __AUTORELEASEPOOL_H__
#define __AUTORELEASEPOOL_H__
#include "CCObject.h"
#include "CCArray.h"
NS_CC_BEGIN
/**
* @addtogroup base_nodes
* @{
*/
class CC_DLL AutoreleasePool : public Object
{
/**
* The underlying array of object managed by the pool.
*
* Although Array retains the object once when an object is added, proper
* Object::release() is called outside the array to make sure that the pool
* does not affect the managed object's reference count. So an object can
* be destructed properly by calling Object::release() even if the object
* is in the pool.
*/
Array *_managedObjectArray;
public:
AutoreleasePool();
~AutoreleasePool();
/**
* Add a given object to this pool.
*
* The same object may be added several times to the same pool; When the
* pool is destructed, the object's Object::release() method will be called
* for each time it was added.
*
* @param object The object to add to the pool.
*/
void addObject(Object *object);
/**
* Remove a given object from this pool.
*
* @param object The object to be removed from the pool.
*/
void removeObject(Object *object);
/**
* Clear the autorelease pool.
*
* Object::release() will be called for each time the managed object is
* added to the pool.
*/
void clear();
};
class CC_DLL PoolManager
{
Array *_releasePoolStack;
AutoreleasePool *_curReleasePool;
AutoreleasePool *getCurReleasePool();
public:
static PoolManager* sharedPoolManager();
static void purgePoolManager();
PoolManager();
~PoolManager();
/**
* Clear all the AutoreleasePool on the pool stack.
*/
void finalize();
/**
* Push a new AutoreleasePool to the pool stack.
*/
void push();
/**
* Pop one AutoreleasePool from the pool stack.
*
* This method will ensure that there is at least one AutoreleasePool on
* the stack.
*
* The AutoreleasePool being poped is destructed.
*/
void pop();
/**
* Remove a given object from the current autorelease pool.
*
* @param object The object to be removed.
*
* @see AutoreleasePool::removeObject
*/
void removeObject(Object *object);
/**
* Add a given object to the current autorelease pool.
*
* @param object The object to add.
*
* @see AutoreleasePool::addObject
*/
void addObject(Object *object);
friend class AutoreleasePool;
};
// end of base_nodes group
/// @}
NS_CC_END
#endif //__AUTORELEASEPOOL_H__
|
qq2588258/floweers
|
libs/cocos2dx/cocoa/CCAutoreleasePool.h
|
C
|
mit
| 3,918 |
const fixtures = require('../../fixtures')
const largeCapitalOpportunity = require('../../../../sandbox/fixtures/v4/investment/large-capital-opportunity-complete.json')
const selectors = require('../../../../selectors')
const {
assertKeyValueTable,
assertBreadcrumbs,
} = require('../../support/assertions')
const {
interactions,
companies,
investments,
} = require('../../../../../src/lib/urls')
const {
interaction: { withReferral: interactionWithReferral },
} = fixtures
describe('Interaction details', () => {
context('Past draft interaction', () => {
const params = {}
before(() => {
params.companyId = fixtures.company.venusLtd.id
params.interactionId = fixtures.interaction.draftPastMeeting.id
cy.visit(
`/companies/${params.companyId}/interactions/${params.interactionId}`
)
})
it('should render breadcrumbs', () => {
assertBreadcrumbs({
Home: '/',
Companies: companies.index(),
Interaction: null,
})
})
it('should render the heading', () => {
cy.get(selectors.localHeader().heading).should(
'have.text',
fixtures.interaction.draftPastMeeting.subject
)
})
it('should render the details', () => {
assertKeyValueTable('interactionDetails', {
Company: {
href: `/companies/${fixtures.company.venusLtd.id}`,
name: fixtures.company.venusLtd.name,
},
'Contact(s)': {
href: '/contacts/71906039-858e-47ba-8016-f3c80da69ace',
name: 'Theodore Schaden|6e4b048d-5bb5-4868-9455-aa712f4ceffd',
},
'Date of interaction': '20 May 2019',
'Adviser(s)': 'Brendan Smith, Aberdeen City Council',
})
})
it('should render the "Complete interaction" button', () => {
cy.get(
selectors.interaction.details.interaction.actions.completeInteraction(
params
)
).should('be.visible')
cy.get(
selectors.interaction.details.interaction.actions.completeInteraction(
params
)
).should('have.text', 'Complete interaction')
})
it('should not render the "Edit interaction" button', () => {
cy.get(
selectors.interaction.details.interaction.actions.editInteraction(
params
)
).should('not.exist')
})
it('should not render the "Why can I not complete this interaction?" details summary', () => {
cy.get(
selectors.interaction.details.interaction.whyCanINotComplete
).should('not.exist')
})
})
context('Future draft interaction', () => {
const params = {}
before(() => {
params.companyId = fixtures.company.venusLtd.id
params.interactionId = fixtures.interaction.draftFutureMeeting.id
cy.visit(
`/companies/${params.companyId}/interactions/${params.interactionId}`
)
})
it('should render breadcrumbs', () => {
assertBreadcrumbs({
Home: '/',
Companies: companies.index(),
Interaction: null,
})
})
it('should render the heading', () => {
cy.get(selectors.localHeader().heading).should(
'have.text',
fixtures.interaction.draftFutureMeeting.subject
)
})
it('should render the details', () => {
assertKeyValueTable('interactionDetails', {
Company: {
href: `/companies/${fixtures.company.venusLtd.id}`,
name: fixtures.company.venusLtd.name,
},
'Contact(s)': {
href: '/contacts/71906039-858e-47ba-8016-f3c80da69ace',
name: 'Theodore Schaden|6e4b048d-5bb5-4868-9455-aa712f4ceffd',
},
'Date of interaction': '20 May 2030',
'Adviser(s)': 'Brendan Smith, Aberdeen City Council',
})
})
it('should not render the "Complete interaction" button', () => {
cy.get(
selectors.interaction.details.interaction.actions.completeInteraction(
params
)
).should('not.exist')
})
it('should not render the "Edit interaction" button', () => {
cy.get(
selectors.interaction.details.interaction.actions.editInteraction(
params
)
).should('not.exist')
})
it('should render the "Why can I not complete this interaction?" details summary', () => {
cy.get(
selectors.interaction.details.interaction.whyCanINotComplete
).should('be.visible')
})
})
context('Cancelled interaction', () => {
const params = {}
before(() => {
params.companyId = fixtures.company.venusLtd.id
params.interactionId = fixtures.interaction.cancelledMeeting.id
cy.visit(
`/companies/${params.companyId}/interactions/${params.interactionId}`
)
})
it('should render breadcrumbs', () => {
assertBreadcrumbs({
Home: '/',
Companies: companies.index(),
Interaction: null,
})
})
it('should render the heading', () => {
cy.get(selectors.localHeader().heading).should(
'have.text',
fixtures.interaction.cancelledMeeting.subject
)
})
it('should render the details', () => {
assertKeyValueTable('interactionDetails', {
Company: {
href: `/companies/${fixtures.company.venusLtd.id}`,
name: fixtures.company.venusLtd.name,
},
'Contact(s)': {
href: '/contacts/e2eee6cd-acf6-454a-a4a8-f6c8fa604fde',
name: 'Tyson Morar',
},
'Date of interaction': '11 June 2019',
'Adviser(s)': 'Brendan Smith, Digital Data Hub - Live Service',
})
})
it('should not render the "Complete interaction" button', () => {
cy.get(
selectors.interaction.details.interaction.actions.completeInteraction(
params
)
).should('not.exist')
})
it('should not render the "Edit interaction" button', () => {
cy.get(
selectors.interaction.details.interaction.actions.editInteraction(
params
)
).should('not.exist')
})
it('should not render the "Why can I not complete this interaction?" details summary', () => {
cy.get(
selectors.interaction.details.interaction.whyCanINotComplete
).should('not.exist')
})
})
context('Complete service delivery with documents', () => {
const params = {}
before(() => {
params.companyId = fixtures.company.venusLtd.id
params.interactionId = fixtures.interaction.withLink.id
cy.visit(
`/companies/${params.companyId}/interactions/${params.interactionId}`
)
})
it('should render breadcrumbs', () => {
assertBreadcrumbs({
Home: '/',
Companies: companies.index(),
'Service delivery': null,
})
})
it('should render the heading', () => {
cy.get(selectors.localHeader().heading).should(
'have.text',
fixtures.interaction.withLink.subject
)
})
it('should render the details', () => {
assertKeyValueTable('interactionDetails', {
Company: {
href: `/companies/${fixtures.company.venusLtd.id}`,
name: fixtures.company.venusLtd.name,
},
'Contact(s)': {
href: '/contacts/9b1138ab-ec7b-497f-b8c3-27fed21694ef',
name: 'Johnny Cakeman',
},
Service: 'Events - UK Based',
Notes: 'This is a dummy service delivery for testing',
'Date of service delivery': '5 September 2017',
'Adviser(s)': '',
Event: {
href: '/events/bda12a57-433c-4a0c-a7ce-5ebd080e09e8',
name: 'Grand exhibition',
},
Documents: 'View files and documents (will open another website)',
})
})
it('should not render the "Complete interaction" button', () => {
const completeInteraction =
selectors.interaction.details.interaction.actions.completeInteraction(
params
)
cy.get(completeInteraction).should('not.exist')
})
it('should render the "Edit interaction" button', () => {
const editInteraction =
selectors.interaction.details.interaction.actions.editInteraction(
params
)
cy.get(editInteraction).should('be.visible')
cy.get(editInteraction).should('have.text', 'Edit service delivery')
})
it('should not render the "Why can I not complete this interaction?" details summary', () => {
cy.get(
selectors.interaction.details.interaction.whyCanINotComplete
).should('not.exist')
})
})
context('Complete investment project interaction without documents', () => {
const params = {}
before(() => {
params.companyId = fixtures.company.venusLtd.id
params.interactionId = fixtures.interaction.withNoLink.id
cy.visit(
`/companies/${params.companyId}/interactions/${params.interactionId}`
)
})
it('should render breadcrumbs', () => {
assertBreadcrumbs({
Home: '/',
Companies: companies.index(),
Interaction: null,
})
})
it('should render the heading', () => {
cy.get(selectors.localHeader().heading).should(
'have.text',
fixtures.interaction.withNoLink.subject
)
})
it('should render the details', () => {
assertKeyValueTable('interactionDetails', {
Company: {
href: `/companies/${fixtures.company.venusLtd.id}`,
name: fixtures.company.venusLtd.name,
},
'Contact(s)': {
href: `/contacts/${fixtures.contact.deanCox.id}`,
name: fixtures.contact.deanCox.name,
},
Service: 'UKEF - EFA Advice',
Notes: 'This is a dummy interaction for testing',
'Date of interaction': '5 June 2017',
'Adviser(s)': '',
'Investment project': {
href: `/investments/projects/${fixtures.investment.newHotelFdi.id}`,
name: fixtures.investment.newHotelFdi.name,
},
'Communication channel': 'Email/Website',
})
})
it('should not render the "Complete interaction" button', () => {
const completeInteraction =
selectors.interaction.details.interaction.actions.completeInteraction(
params
)
cy.get(completeInteraction).should('not.exist')
})
it('should render the "Edit interaction" button', () => {
const editInteraction =
selectors.interaction.details.interaction.actions.editInteraction(
params
)
cy.get(editInteraction).should('be.visible')
cy.get(editInteraction).should('have.text', 'Edit interaction')
})
it('should not render the "Why can I not complete this interaction?" details summary', () => {
cy.get(
selectors.interaction.details.interaction.whyCanINotComplete
).should('not.exist')
})
})
context('When an interaction is created from a referral', () => {
it('should display the linked referral on the interaction detail page', () => {
cy.visit(interactions.detail(interactionWithReferral.id))
cy.contains('This interaction is linked to a referral').should(
'be.visible'
)
cy.get('table')
.eq(1)
.should('contain', 'Subject')
.and('contain', interactionWithReferral.company_referral.subject)
.and('contain', 'Sent on')
.and('contain', '14 Feb 2020')
.and('contain', 'By')
.and(
'contain',
interactionWithReferral.company_referral.created_by.name
)
.and('contain', 'To')
.and('contain', interactionWithReferral.company_referral.recipient.name)
})
it('should take you to the referral details page when you click on the subject', () => {
cy.contains(interactionWithReferral.company_referral.subject).click()
cy.url().should(
'contain',
companies.referrals.details(
interactionWithReferral.companies[0].id,
interactionWithReferral.company_referral.id
)
)
})
})
context(
'An interaction with investment theme and large capital opportunity',
() => {
before(() => {
cy.visit(
interactions.detail(fixtures.interaction.withInvestmentTheme.id)
)
})
it('should render the details', () => {
assertKeyValueTable('interactionDetails', {
Company: {
href: `/companies/${fixtures.company.venusLtd.id}`,
name: fixtures.company.venusLtd.name,
},
'Contact(s)': {
href: '/contacts/952232d2-1d25-4c3a-bcac-2f3a30a94da9',
name: 'Dean Cox',
},
Service: 'Providing Investment Advice & Information',
Notes: 'This is a dummy interaction for testing',
'Date of interaction': '5 June 2017',
'Adviser(s)': 'DIT Staff, Digital Data Hub - Live Service',
'Communication channel': 'Email/Website',
'Related large capital opportunity': {
href: investments.opportunities.details(largeCapitalOpportunity.id),
name: largeCapitalOpportunity.name,
},
})
})
}
)
})
|
uktrade/data-hub-fe-beta2
|
test/functional/cypress/specs/interaction/details-spec.js
|
JavaScript
|
mit
| 13,217 |
{% extends "base.html" %}
<!--
Template file: application.html
URL: /application/[application_type]
Title: Projects with application [application_type]
Description: Displays a list of Project Identifiers for a given application type
-->
{% block stuff %}
<div class="container-fluid">
<h2 id="page_title">Projects with application <em>{{ application }}</em></h2><br>
<ul id="project_list">
</div>
<script>
$.getJSON("/api/v1/application/{{ application }}", function(data) {
$.each(data, function(k, project) {
$("#project_list").append('<li><a class="text-decoration-none" href="/projects/' + project + '">' + project + '</a></li>')
})
})
</script>
{% end %}
|
remiolsen/status
|
run_dir/design/application.html
|
HTML
|
mit
| 675 |
// WARNING - AUTOGENERATED - DO NOT EDIT
//
// Generated using `sharpie urho`
//
// RibbonTrail.cs
//
// Copyright 2015 Xamarin Inc. All rights reserved.
using System;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using Urho.Urho2D;
using Urho.Gui;
using Urho.Resources;
using Urho.IO;
using Urho.Navigation;
using Urho.Network;
namespace Urho
{
/// <summary>
/// Drawable component that creates a tail.
/// </summary>
public unsafe partial class RibbonTrail : Drawable
{
unsafe partial void OnRibbonTrailCreated ();
[Preserve]
public RibbonTrail (IntPtr handle) : base (handle)
{
OnRibbonTrailCreated ();
}
[Preserve]
protected RibbonTrail (UrhoObjectFlag emptyFlag) : base (emptyFlag)
{
OnRibbonTrailCreated ();
}
[DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)]
internal static extern int RibbonTrail_GetType (IntPtr handle);
private StringHash UrhoGetType ()
{
Runtime.ValidateRefCounted (this);
return new StringHash (RibbonTrail_GetType (handle));
}
[DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)]
internal static extern IntPtr RibbonTrail_GetTypeName (IntPtr handle);
private string GetTypeName ()
{
Runtime.ValidateRefCounted (this);
return Marshal.PtrToStringAnsi (RibbonTrail_GetTypeName (handle));
}
[DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)]
internal static extern int RibbonTrail_GetTypeStatic ();
private static StringHash GetTypeStatic ()
{
Runtime.Validate (typeof(RibbonTrail));
return new StringHash (RibbonTrail_GetTypeStatic ());
}
[DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)]
internal static extern IntPtr RibbonTrail_GetTypeNameStatic ();
private static string GetTypeNameStatic ()
{
Runtime.Validate (typeof(RibbonTrail));
return Marshal.PtrToStringAnsi (RibbonTrail_GetTypeNameStatic ());
}
[Preserve]
public RibbonTrail () : this (Application.CurrentContext)
{
}
[DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)]
internal static extern IntPtr RibbonTrail_RibbonTrail (IntPtr context);
[Preserve]
public RibbonTrail (Context context) : base (UrhoObjectFlag.Empty)
{
Runtime.Validate (typeof(RibbonTrail));
handle = RibbonTrail_RibbonTrail ((object)context == null ? IntPtr.Zero : context.Handle);
Runtime.RegisterObject (this);
OnRibbonTrailCreated ();
}
[DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)]
internal static extern void RibbonTrail_RegisterObject (IntPtr context);
/// <summary>
/// Register object factory.
/// </summary>
public new static void RegisterObject (Context context)
{
Runtime.Validate (typeof(RibbonTrail));
RibbonTrail_RegisterObject ((object)context == null ? IntPtr.Zero : context.Handle);
}
[DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)]
internal static extern void RibbonTrail_OnSetEnabled (IntPtr handle);
/// <summary>
/// Handle enabled/disabled state change.
/// </summary>
public override void OnSetEnabled ()
{
Runtime.ValidateRefCounted (this);
RibbonTrail_OnSetEnabled (handle);
}
[DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)]
internal static extern UpdateGeometryType RibbonTrail_GetUpdateGeometryType (IntPtr handle);
/// <summary>
/// Return whether a geometry update is necessary, and if it can happen in a worker thread.
/// </summary>
private UpdateGeometryType GetUpdateGeometryType ()
{
Runtime.ValidateRefCounted (this);
return RibbonTrail_GetUpdateGeometryType (handle);
}
[DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)]
internal static extern void RibbonTrail_SetMaterial (IntPtr handle, IntPtr material);
/// <summary>
/// Set material.
/// </summary>
private void SetMaterial (Material material)
{
Runtime.ValidateRefCounted (this);
RibbonTrail_SetMaterial (handle, (object)material == null ? IntPtr.Zero : material.Handle);
}
[DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)]
internal static extern void RibbonTrail_SetVertexDistance (IntPtr handle, float length);
/// <summary>
/// Set distance between points.
/// </summary>
private void SetVertexDistance (float length)
{
Runtime.ValidateRefCounted (this);
RibbonTrail_SetVertexDistance (handle, length);
}
[DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)]
internal static extern void RibbonTrail_SetWidth (IntPtr handle, float width);
/// <summary>
/// Set width of the tail. Only works for face camera trail type.
/// </summary>
private void SetWidth (float width)
{
Runtime.ValidateRefCounted (this);
RibbonTrail_SetWidth (handle, width);
}
[DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)]
internal static extern void RibbonTrail_SetStartColor (IntPtr handle, ref Urho.Color color);
/// <summary>
/// Set vertex blended color for start of trail.
/// </summary>
private void SetStartColor (Urho.Color color)
{
Runtime.ValidateRefCounted (this);
RibbonTrail_SetStartColor (handle, ref color);
}
[DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)]
internal static extern void RibbonTrail_SetEndColor (IntPtr handle, ref Urho.Color color);
/// <summary>
/// Set vertex blended scale for end of trail.
/// </summary>
private void SetEndColor (Urho.Color color)
{
Runtime.ValidateRefCounted (this);
RibbonTrail_SetEndColor (handle, ref color);
}
[DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)]
internal static extern void RibbonTrail_SetStartScale (IntPtr handle, float startScale);
/// <summary>
/// Set vertex blended color for start of trail.
/// </summary>
private void SetStartScale (float startScale)
{
Runtime.ValidateRefCounted (this);
RibbonTrail_SetStartScale (handle, startScale);
}
[DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)]
internal static extern void RibbonTrail_SetEndScale (IntPtr handle, float endScale);
/// <summary>
/// Set vertex blended scale for end of trail.
/// </summary>
private void SetEndScale (float endScale)
{
Runtime.ValidateRefCounted (this);
RibbonTrail_SetEndScale (handle, endScale);
}
[DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)]
internal static extern void RibbonTrail_SetTrailType (IntPtr handle, TrailType type);
/// <summary>
/// Set how the trail behave.
/// </summary>
private void SetTrailType (TrailType type)
{
Runtime.ValidateRefCounted (this);
RibbonTrail_SetTrailType (handle, type);
}
[DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)]
internal static extern void RibbonTrail_SetSorted (IntPtr handle, bool enable);
/// <summary>
/// Set whether tails are sorted by distance. Default false.
/// </summary>
private void SetSorted (bool enable)
{
Runtime.ValidateRefCounted (this);
RibbonTrail_SetSorted (handle, enable);
}
[DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)]
internal static extern void RibbonTrail_SetLifetime (IntPtr handle, float time);
/// <summary>
/// Set tail time to live.
/// </summary>
private void SetLifetime (float time)
{
Runtime.ValidateRefCounted (this);
RibbonTrail_SetLifetime (handle, time);
}
[DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)]
internal static extern void RibbonTrail_SetEmitting (IntPtr handle, bool emitting);
/// <summary>
/// Set whether trail should be emitting.
/// </summary>
private void SetEmitting (bool emitting)
{
Runtime.ValidateRefCounted (this);
RibbonTrail_SetEmitting (handle, emitting);
}
[DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)]
internal static extern void RibbonTrail_SetUpdateInvisible (IntPtr handle, bool enable);
/// <summary>
/// Set whether to update when trail emiiter are not visible.
/// </summary>
private void SetUpdateInvisible (bool enable)
{
Runtime.ValidateRefCounted (this);
RibbonTrail_SetUpdateInvisible (handle, enable);
}
[DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)]
internal static extern void RibbonTrail_SetTailColumn (IntPtr handle, uint tailColumn);
/// <summary>
/// Set number of column for every tails. Can be useful for fixing distortion at high angle.
/// </summary>
private void SetTailColumn (uint tailColumn)
{
Runtime.ValidateRefCounted (this);
RibbonTrail_SetTailColumn (handle, tailColumn);
}
[DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)]
internal static extern void RibbonTrail_SetAnimationLodBias (IntPtr handle, float bias);
/// <summary>
/// Set animation LOD bias.
/// </summary>
private void SetAnimationLodBias (float bias)
{
Runtime.ValidateRefCounted (this);
RibbonTrail_SetAnimationLodBias (handle, bias);
}
[DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)]
internal static extern void RibbonTrail_Commit (IntPtr handle);
/// <summary>
/// Mark for bounding box and vertex buffer update. Call after modifying the trails.
/// </summary>
public void Commit ()
{
Runtime.ValidateRefCounted (this);
RibbonTrail_Commit (handle);
}
[DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)]
internal static extern IntPtr RibbonTrail_GetMaterial (IntPtr handle);
/// <summary>
/// Return material.
/// </summary>
private Material GetMaterial ()
{
Runtime.ValidateRefCounted (this);
return Runtime.LookupObject<Material> (RibbonTrail_GetMaterial (handle));
}
[DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)]
internal static extern ResourceRef RibbonTrail_GetMaterialAttr (IntPtr handle);
/// <summary>
/// Return material attribute.
/// </summary>
private ResourceRef GetMaterialAttr ()
{
Runtime.ValidateRefCounted (this);
return RibbonTrail_GetMaterialAttr (handle);
}
[DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)]
internal static extern float RibbonTrail_GetVertexDistance (IntPtr handle);
/// <summary>
/// Get distance between points.
/// </summary>
private float GetVertexDistance ()
{
Runtime.ValidateRefCounted (this);
return RibbonTrail_GetVertexDistance (handle);
}
[DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)]
internal static extern float RibbonTrail_GetWidth (IntPtr handle);
/// <summary>
/// Get width of the trail.
/// </summary>
private float GetWidth ()
{
Runtime.ValidateRefCounted (this);
return RibbonTrail_GetWidth (handle);
}
[DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)]
internal static extern Urho.Color RibbonTrail_GetStartColor (IntPtr handle);
/// <summary>
/// Get vertex blended color for start of trail.
/// </summary>
private Urho.Color GetStartColor ()
{
Runtime.ValidateRefCounted (this);
return RibbonTrail_GetStartColor (handle);
}
[DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)]
internal static extern Urho.Color RibbonTrail_GetEndColor (IntPtr handle);
/// <summary>
/// Get vertex blended color for end of trail.
/// </summary>
private Urho.Color GetEndColor ()
{
Runtime.ValidateRefCounted (this);
return RibbonTrail_GetEndColor (handle);
}
[DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)]
internal static extern float RibbonTrail_GetStartScale (IntPtr handle);
/// <summary>
/// Get vertex blended scale for start of trail.
/// </summary>
private float GetStartScale ()
{
Runtime.ValidateRefCounted (this);
return RibbonTrail_GetStartScale (handle);
}
[DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)]
internal static extern float RibbonTrail_GetEndScale (IntPtr handle);
/// <summary>
/// Get vertex blended scale for end of trail.
/// </summary>
private float GetEndScale ()
{
Runtime.ValidateRefCounted (this);
return RibbonTrail_GetEndScale (handle);
}
[DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)]
internal static extern bool RibbonTrail_IsSorted (IntPtr handle);
/// <summary>
/// Return whether tails are sorted.
/// </summary>
private bool IsSorted ()
{
Runtime.ValidateRefCounted (this);
return RibbonTrail_IsSorted (handle);
}
[DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)]
internal static extern float RibbonTrail_GetLifetime (IntPtr handle);
/// <summary>
/// Return tail time to live.
/// </summary>
private float GetLifetime ()
{
Runtime.ValidateRefCounted (this);
return RibbonTrail_GetLifetime (handle);
}
[DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)]
internal static extern float RibbonTrail_GetAnimationLodBias (IntPtr handle);
/// <summary>
/// Return animation LOD bias.
/// </summary>
private float GetAnimationLodBias ()
{
Runtime.ValidateRefCounted (this);
return RibbonTrail_GetAnimationLodBias (handle);
}
[DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)]
internal static extern TrailType RibbonTrail_GetTrailType (IntPtr handle);
/// <summary>
/// Return how the trail behave.
/// </summary>
private TrailType GetTrailType ()
{
Runtime.ValidateRefCounted (this);
return RibbonTrail_GetTrailType (handle);
}
[DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)]
internal static extern uint RibbonTrail_GetTailColumn (IntPtr handle);
/// <summary>
/// Get number of column for tails.
/// </summary>
private uint GetTailColumn ()
{
Runtime.ValidateRefCounted (this);
return RibbonTrail_GetTailColumn (handle);
}
[DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)]
internal static extern bool RibbonTrail_IsEmitting (IntPtr handle);
/// <summary>
/// Return whether is currently emitting.
/// </summary>
private bool IsEmitting ()
{
Runtime.ValidateRefCounted (this);
return RibbonTrail_IsEmitting (handle);
}
[DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)]
internal static extern bool RibbonTrail_GetUpdateInvisible (IntPtr handle);
/// <summary>
/// Return whether to update when trail emitter are not visible.
/// </summary>
private bool GetUpdateInvisible ()
{
Runtime.ValidateRefCounted (this);
return RibbonTrail_GetUpdateInvisible (handle);
}
public override StringHash Type {
get {
return UrhoGetType ();
}
}
public override string TypeName {
get {
return GetTypeName ();
}
}
[Preserve]
public new static StringHash TypeStatic {
get {
return GetTypeStatic ();
}
}
public new static string TypeNameStatic {
get {
return GetTypeNameStatic ();
}
}
/// <summary>
/// Return whether a geometry update is necessary, and if it can happen in a worker thread.
/// </summary>
public override UpdateGeometryType UpdateGeometryType {
get {
return GetUpdateGeometryType ();
}
}
/// <summary>
/// Return material.
/// Or
/// Set material.
/// </summary>
public Material Material {
get {
return GetMaterial ();
}
set {
SetMaterial (value);
}
}
/// <summary>
/// Return material attribute.
/// </summary>
public ResourceRef MaterialAttr {
get {
return GetMaterialAttr ();
}
}
/// <summary>
/// Get distance between points.
/// Or
/// Set distance between points.
/// </summary>
public float VertexDistance {
get {
return GetVertexDistance ();
}
set {
SetVertexDistance (value);
}
}
/// <summary>
/// Get width of the trail.
/// Or
/// Set width of the tail. Only works for face camera trail type.
/// </summary>
public float Width {
get {
return GetWidth ();
}
set {
SetWidth (value);
}
}
/// <summary>
/// Get vertex blended color for start of trail.
/// Or
/// Set vertex blended color for start of trail.
/// </summary>
public Urho.Color StartColor {
get {
return GetStartColor ();
}
set {
SetStartColor (value);
}
}
/// <summary>
/// Get vertex blended color for end of trail.
/// Or
/// Set vertex blended scale for end of trail.
/// </summary>
public Urho.Color EndColor {
get {
return GetEndColor ();
}
set {
SetEndColor (value);
}
}
/// <summary>
/// Get vertex blended scale for start of trail.
/// Or
/// Set vertex blended color for start of trail.
/// </summary>
public float StartScale {
get {
return GetStartScale ();
}
set {
SetStartScale (value);
}
}
/// <summary>
/// Get vertex blended scale for end of trail.
/// Or
/// Set vertex blended scale for end of trail.
/// </summary>
public float EndScale {
get {
return GetEndScale ();
}
set {
SetEndScale (value);
}
}
/// <summary>
/// Return how the trail behave.
/// Or
/// Set how the trail behave.
/// </summary>
public TrailType TrailType {
get {
return GetTrailType ();
}
set {
SetTrailType (value);
}
}
/// <summary>
/// Return whether tails are sorted.
/// Or
/// Set whether tails are sorted by distance. Default false.
/// </summary>
public bool Sorted {
get {
return IsSorted ();
}
set {
SetSorted (value);
}
}
/// <summary>
/// Return tail time to live.
/// Or
/// Set tail time to live.
/// </summary>
public float Lifetime {
get {
return GetLifetime ();
}
set {
SetLifetime (value);
}
}
/// <summary>
/// Return whether is currently emitting.
/// Or
/// Set whether trail should be emitting.
/// </summary>
public bool Emitting {
get {
return IsEmitting ();
}
set {
SetEmitting (value);
}
}
/// <summary>
/// Return whether to update when trail emitter are not visible.
/// Or
/// Set whether to update when trail emiiter are not visible.
/// </summary>
public bool UpdateInvisible {
get {
return GetUpdateInvisible ();
}
set {
SetUpdateInvisible (value);
}
}
/// <summary>
/// Get number of column for tails.
/// Or
/// Set number of column for every tails. Can be useful for fixing distortion at high angle.
/// </summary>
public uint TailColumn {
get {
return GetTailColumn ();
}
set {
SetTailColumn (value);
}
}
/// <summary>
/// Return animation LOD bias.
/// Or
/// Set animation LOD bias.
/// </summary>
public float AnimationLodBias {
get {
return GetAnimationLodBias ();
}
set {
SetAnimationLodBias (value);
}
}
}
}
|
florin-chelaru/urho
|
Bindings/Portable/Generated/RibbonTrail.cs
|
C#
|
mit
| 19,269 |
---
layout: page
title: Jupyter Notebook Tutorial
permalink: /notes/jupyter-tutorial/
---
In this class, we will use [Jupyter Notebook](http://jupyter.org/) for the
programming assignments. A Jupyter notebook lets you write and execute Python
code in your web browser. Jupyter notebooks make it very easy to tinker with
code and execute it in bits and pieces; for this reason Jupyter notebooks are
widely used in scientific computing.
Installing and running Jupyter is easy. From the command line, the following
will install Jupyter:
```
pip install jupyter
```
Or the following if you use conda/Anaconda:
```
conda install jupyter
```
Once you have Jupyter installed, start it with this command:
```
jupyter notebook
```
Once Jupyter is running, point your web browser at http://localhost:8888 to
start using Jupyter notebooks. If everything worked correctly, you should
see a screen like this, showing all available Jupyter notebooks in the current
directory:
<div class='fig figcenter'>
<img src='/assets/ipython-tutorial/file-browser.png'>
</div>
If you click through to a notebook file, you will see a screen like this:
<div class='fig figcenter'>
<img src='/assets/ipython-tutorial/notebook-1.png'>
</div>
A Jupyter notebook is made up of a number of **cells**. Each cell can contain
Python code. You can execute a cell by clicking on it and pressing `Shift-Enter`.
When you do so, the code in the cell will run, and the output of the cell
will be displayed beneath the cell. For example, after running the first cell
the notebook looks like this:
<div class='fig figcenter'>
<img src='/assets/ipython-tutorial/notebook-2.png'>
</div>
Global variables are shared between cells. Executing the second cell thus gives
the following result:
<div class='fig figcenter'>
<img src='/assets/ipython-tutorial/notebook-3.png'>
</div>
By convention, Jupyter notebooks are expected to be run from top to bottom.
Failing to execute some cells or executing cells out of order can result in
errors:
<div class='fig figcenter'>
<img src='/assets/ipython-tutorial/notebook-error.png'>
</div>
After you have modified a Jupyter notebook for one of the assignments by
modifying or executing some of its cells, remember to **save your changes!**
This has only been a brief introduction to Jupyter Notebook, but it should
be enough to get you up and running on the assignments for this course. Check out
[these notebooks](http://nbviewer.jupyter.org/github/jupyter/notebook/tree/master/docs/source/examples/Notebook/)
if you want to learn more.
|
compsci682/compsci682.github.io
|
notes/jupyter-tutorial.md
|
Markdown
|
mit
| 2,562 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import PIL
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APIClient
from InvenTree.api_tester import InvenTreeAPITestCase
from InvenTree.status_codes import StockStatus
from part.models import Part, PartCategory
from part.models import BomItem, BomItemSubstitute
from stock.models import StockItem, StockLocation
from company.models import Company
from common.models import InvenTreeSetting
class PartOptionsAPITest(InvenTreeAPITestCase):
"""
Tests for the various OPTIONS endpoints in the /part/ API
Ensure that the required field details are provided!
"""
roles = [
'part.add',
]
def setUp(self):
super().setUp()
def test_part(self):
"""
Test the Part API OPTIONS
"""
actions = self.getActions(reverse('api-part-list'))['POST']
# Check that a bunch o' fields are contained
for f in ['assembly', 'component', 'description', 'image', 'IPN']:
self.assertTrue(f in actions.keys())
# Active is a 'boolean' field
active = actions['active']
self.assertTrue(active['default'])
self.assertEqual(active['help_text'], 'Is this part active?')
self.assertEqual(active['type'], 'boolean')
self.assertEqual(active['read_only'], False)
# String field
ipn = actions['IPN']
self.assertEqual(ipn['type'], 'string')
self.assertFalse(ipn['required'])
self.assertEqual(ipn['max_length'], 100)
self.assertEqual(ipn['help_text'], 'Internal Part Number')
# Related field
category = actions['category']
self.assertEqual(category['type'], 'related field')
self.assertTrue(category['required'])
self.assertFalse(category['read_only'])
self.assertEqual(category['label'], 'Category')
self.assertEqual(category['model'], 'partcategory')
self.assertEqual(category['api_url'], reverse('api-part-category-list'))
self.assertEqual(category['help_text'], 'Part category')
def test_category(self):
"""
Test the PartCategory API OPTIONS endpoint
"""
actions = self.getActions(reverse('api-part-category-list'))
# actions should *not* contain 'POST' as we do not have the correct role
self.assertFalse('POST' in actions)
self.assignRole('part_category.add')
actions = self.getActions(reverse('api-part-category-list'))['POST']
name = actions['name']
self.assertTrue(name['required'])
self.assertEqual(name['label'], 'Name')
loc = actions['default_location']
self.assertEqual(loc['api_url'], reverse('api-location-list'))
def test_bom_item(self):
"""
Test the BomItem API OPTIONS endpoint
"""
actions = self.getActions(reverse('api-bom-list'))['POST']
inherited = actions['inherited']
self.assertEqual(inherited['type'], 'boolean')
# 'part' reference
part = actions['part']
self.assertTrue(part['required'])
self.assertFalse(part['read_only'])
self.assertTrue(part['filters']['assembly'])
# 'sub_part' reference
sub_part = actions['sub_part']
self.assertTrue(sub_part['required'])
self.assertEqual(sub_part['type'], 'related field')
self.assertTrue(sub_part['filters']['component'])
class PartAPITest(InvenTreeAPITestCase):
"""
Series of tests for the Part DRF API
- Tests for Part API
- Tests for PartCategory API
"""
fixtures = [
'category',
'part',
'location',
'bom',
'test_templates',
'company',
]
roles = [
'part.change',
'part.add',
'part.delete',
'part_category.change',
'part_category.add',
]
def setUp(self):
super().setUp()
def test_get_categories(self):
"""
Test that we can retrieve list of part categories,
with various filtering options.
"""
url = reverse('api-part-category-list')
# Request *all* part categories
response = self.client.get(url, format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(len(response.data), 8)
# Request top-level part categories only
response = self.client.get(
url,
{
'parent': 'null',
},
format='json'
)
self.assertEqual(len(response.data), 2)
# Children of PartCategory<1>, cascade
response = self.client.get(
url,
{
'parent': 1,
'cascade': 'true',
},
format='json',
)
self.assertEqual(len(response.data), 5)
# Children of PartCategory<1>, do not cascade
response = self.client.get(
url,
{
'parent': 1,
'cascade': 'false',
},
format='json',
)
self.assertEqual(len(response.data), 3)
def test_add_categories(self):
""" Check that we can add categories """
data = {
'name': 'Animals',
'description': 'All animals go here'
}
url = reverse('api-part-category-list')
response = self.client.post(url, data, format='json')
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
parent = response.data['pk']
# Add some sub-categories to the top-level 'Animals' category
for animal in ['cat', 'dog', 'zebra']:
data = {
'name': animal,
'description': 'A sort of animal',
'parent': parent,
}
response = self.client.post(url, data, format='json')
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(response.data['parent'], parent)
self.assertEqual(response.data['name'], animal)
self.assertEqual(response.data['pathstring'], 'Animals/' + animal)
# There should be now 8 categories
response = self.client.get(url, format='json')
self.assertEqual(len(response.data), 12)
def test_cat_detail(self):
url = reverse('api-part-category-detail', kwargs={'pk': 4})
response = self.client.get(url, format='json')
# Test that we have retrieved the category
self.assertEqual(response.data['description'], 'Integrated Circuits')
self.assertEqual(response.data['parent'], 1)
# Change some data and post it back
data = response.data
data['name'] = 'Changing category'
data['parent'] = None
data['description'] = 'Changing the description'
response = self.client.patch(url, data, format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data['description'], 'Changing the description')
self.assertIsNone(response.data['parent'])
def test_get_all_parts(self):
url = reverse('api-part-list')
data = {'cascade': True}
response = self.client.get(url, data, format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(len(response.data), 13)
def test_get_parts_by_cat(self):
url = reverse('api-part-list')
data = {'category': 2}
response = self.client.get(url, data, format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
# There should only be 2 objects in category C
self.assertEqual(len(response.data), 2)
for part in response.data:
self.assertEqual(part['category'], 2)
def test_include_children(self):
""" Test the special 'include_child_categories' flag
If provided, parts are provided for ANY child category (recursive)
"""
url = reverse('api-part-list')
data = {'category': 1, 'cascade': True}
# Now request to include child categories
response = self.client.get(url, data, format='json')
# Now there should be 5 total parts
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(len(response.data), 3)
def test_test_templates(self):
url = reverse('api-part-test-template-list')
# List ALL items
response = self.client.get(url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(len(response.data), 7)
# Request for a particular part
response = self.client.get(url, data={'part': 10000})
self.assertEqual(len(response.data), 5)
response = self.client.get(url, data={'part': 10004})
self.assertEqual(len(response.data), 7)
# Try to post a new object (missing description)
response = self.client.post(
url,
data={
'part': 10000,
'test_name': 'My very first test',
'required': False,
}
)
self.assertEqual(response.status_code, 400)
# Try to post a new object (should succeed)
response = self.client.post(
url,
data={
'part': 10000,
'test_name': 'New Test',
'required': True,
'description': 'a test description'
},
format='json',
)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
# Try to post a new test with the same name (should fail)
response = self.client.post(
url,
data={
'part': 10004,
'test_name': " newtest",
'description': 'dafsdf',
},
format='json',
)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
# Try to post a new test against a non-trackable part (should fail)
response = self.client.post(
url,
data={
'part': 1,
'test_name': 'A simple test',
}
)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
def test_get_thumbs(self):
"""
Return list of part thumbnails
"""
url = reverse('api-part-thumbs')
response = self.client.get(url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_paginate(self):
"""
Test pagination of the Part list API
"""
for n in [1, 5, 10]:
response = self.get(reverse('api-part-list'), {'limit': n})
data = response.data
self.assertIn('count', data)
self.assertIn('results', data)
self.assertEqual(len(data['results']), n)
def test_default_values(self):
"""
Tests for 'default' values:
Ensure that unspecified fields revert to "default" values
(as specified in the model field definition)
"""
url = reverse('api-part-list')
response = self.client.post(url, {
'name': 'all defaults',
'description': 'my test part',
'category': 1,
})
data = response.data
# Check that the un-specified fields have used correct default values
self.assertTrue(data['active'])
self.assertFalse(data['virtual'])
# By default, parts are purchaseable
self.assertTrue(data['purchaseable'])
# Set the default 'purchaseable' status to True
InvenTreeSetting.set_setting(
'PART_PURCHASEABLE',
True,
self.user
)
response = self.client.post(url, {
'name': 'all defaults',
'description': 'my test part 2',
'category': 1,
})
# Part should now be purchaseable by default
self.assertTrue(response.data['purchaseable'])
# "default" values should not be used if the value is specified
response = self.client.post(url, {
'name': 'all defaults',
'description': 'my test part 2',
'category': 1,
'active': False,
'purchaseable': False,
})
self.assertFalse(response.data['active'])
self.assertFalse(response.data['purchaseable'])
def test_initial_stock(self):
"""
Tests for initial stock quantity creation
"""
url = reverse('api-part-list')
# Track how many parts exist at the start of this test
n = Part.objects.count()
# Set up required part data
data = {
'category': 1,
'name': "My lil' test part",
'description': 'A part with which to test',
}
# Signal that we want to add initial stock
data['initial_stock'] = True
# Post without a quantity
response = self.post(url, data, expected_code=400)
self.assertIn('initial_stock_quantity', response.data)
# Post with an invalid quantity
data['initial_stock_quantity'] = "ax"
response = self.post(url, data, expected_code=400)
self.assertIn('initial_stock_quantity', response.data)
# Post with a negative quantity
data['initial_stock_quantity'] = -1
response = self.post(url, data, expected_code=400)
self.assertIn('Must be greater than zero', response.data['initial_stock_quantity'])
# Post with a valid quantity
data['initial_stock_quantity'] = 12345
response = self.post(url, data, expected_code=400)
self.assertIn('initial_stock_location', response.data)
# Check that the number of parts has not increased (due to form failures)
self.assertEqual(Part.objects.count(), n)
# Now, set a location
data['initial_stock_location'] = 1
response = self.post(url, data, expected_code=201)
# Check that the part has been created
self.assertEqual(Part.objects.count(), n + 1)
pk = response.data['pk']
new_part = Part.objects.get(pk=pk)
self.assertEqual(new_part.total_stock, 12345)
def test_initial_supplier_data(self):
"""
Tests for initial creation of supplier / manufacturer data
"""
url = reverse('api-part-list')
n = Part.objects.count()
# Set up initial part data
data = {
'category': 1,
'name': 'Buy Buy Buy',
'description': 'A purchaseable part',
'purchaseable': True,
}
# Signal that we wish to create initial supplier data
data['add_supplier_info'] = True
# Specify MPN but not manufacturer
data['MPN'] = 'MPN-123'
response = self.post(url, data, expected_code=400)
self.assertIn('manufacturer', response.data)
# Specify manufacturer but not MPN
del data['MPN']
data['manufacturer'] = 1
response = self.post(url, data, expected_code=400)
self.assertIn('MPN', response.data)
# Specify SKU but not supplier
del data['manufacturer']
data['SKU'] = 'SKU-123'
response = self.post(url, data, expected_code=400)
self.assertIn('supplier', response.data)
# Specify supplier but not SKU
del data['SKU']
data['supplier'] = 1
response = self.post(url, data, expected_code=400)
self.assertIn('SKU', response.data)
# Check that no new parts have been created
self.assertEqual(Part.objects.count(), n)
# Now, fully specify the details
data['SKU'] = 'SKU-123'
data['supplier'] = 3
data['MPN'] = 'MPN-123'
data['manufacturer'] = 6
response = self.post(url, data, expected_code=201)
self.assertEqual(Part.objects.count(), n + 1)
pk = response.data['pk']
new_part = Part.objects.get(pk=pk)
# Check that there is a new manufacturer part *and* a new supplier part
self.assertEqual(new_part.supplier_parts.count(), 1)
self.assertEqual(new_part.manufacturer_parts.count(), 1)
def test_strange_chars(self):
"""
Test that non-standard ASCII chars are accepted
"""
url = reverse('api-part-list')
name = "Kaltgerätestecker"
description = "Gerät"
data = {
"name": name,
"description": description,
"category": 2
}
response = self.post(url, data, expected_code=201)
self.assertEqual(response.data['name'], name)
self.assertEqual(response.data['description'], description)
class PartDetailTests(InvenTreeAPITestCase):
"""
Test that we can create / edit / delete Part objects via the API
"""
fixtures = [
'category',
'part',
'location',
'bom',
'test_templates',
]
roles = [
'part.change',
'part.add',
'part.delete',
'part_category.change',
'part_category.add',
]
def setUp(self):
super().setUp()
def test_part_operations(self):
n = Part.objects.count()
# Create a part
response = self.client.post(
reverse('api-part-list'),
{
'name': 'my test api part',
'description': 'a part created with the API',
'category': 1,
}
)
self.assertEqual(response.status_code, 201)
pk = response.data['pk']
# Check that a new part has been added
self.assertEqual(Part.objects.count(), n + 1)
part = Part.objects.get(pk=pk)
self.assertEqual(part.name, 'my test api part')
# Edit the part
url = reverse('api-part-detail', kwargs={'pk': pk})
# Let's change the name of the part
response = self.client.patch(url, {
'name': 'a new better name',
})
self.assertEqual(response.status_code, 200)
self.assertEqual(response.data['pk'], pk)
self.assertEqual(response.data['name'], 'a new better name')
part = Part.objects.get(pk=pk)
# Name has been altered
self.assertEqual(part.name, 'a new better name')
# Part count should not have changed
self.assertEqual(Part.objects.count(), n + 1)
# Now, try to set the name to the *same* value
# 2021-06-22 this test is to check that the "duplicate part" checks don't do strange things
response = self.client.patch(url, {
'name': 'a new better name',
})
self.assertEqual(response.status_code, 200)
# Try to remove the part
response = self.client.delete(url)
# As the part is 'active' we cannot delete it
self.assertEqual(response.status_code, 405)
# So, let's make it not active
response = self.patch(url, {'active': False}, expected_code=200)
response = self.client.delete(url)
self.assertEqual(response.status_code, 204)
# Part count should have reduced
self.assertEqual(Part.objects.count(), n)
def test_duplicates(self):
"""
Check that trying to create 'duplicate' parts results in errors
"""
# Create a part
response = self.client.post(reverse('api-part-list'), {
'name': 'part',
'description': 'description',
'IPN': 'IPN-123',
'category': 1,
'revision': 'A',
})
self.assertEqual(response.status_code, 201)
n = Part.objects.count()
# Check that we cannot create a duplicate in a different category
response = self.client.post(reverse('api-part-list'), {
'name': 'part',
'description': 'description',
'IPN': 'IPN-123',
'category': 2,
'revision': 'A',
})
self.assertEqual(response.status_code, 400)
# Check that only 1 matching part exists
parts = Part.objects.filter(
name='part',
description='description',
IPN='IPN-123'
)
self.assertEqual(parts.count(), 1)
# A new part should *not* have been created
self.assertEqual(Part.objects.count(), n)
# But a different 'revision' *can* be created
response = self.client.post(reverse('api-part-list'), {
'name': 'part',
'description': 'description',
'IPN': 'IPN-123',
'category': 2,
'revision': 'B',
})
self.assertEqual(response.status_code, 201)
self.assertEqual(Part.objects.count(), n + 1)
# Now, check that we cannot *change* an existing part to conflict
pk = response.data['pk']
url = reverse('api-part-detail', kwargs={'pk': pk})
# Attempt to alter the revision code
response = self.client.patch(
url,
{
'revision': 'A',
},
format='json',
)
self.assertEqual(response.status_code, 400)
# But we *can* change it to a unique revision code
response = self.client.patch(
url,
{
'revision': 'C',
}
)
self.assertEqual(response.status_code, 200)
def test_image_upload(self):
"""
Test that we can upload an image to the part API
"""
self.assignRole('part.add')
# Create a new part
response = self.client.post(
reverse('api-part-list'),
{
'name': 'imagine',
'description': 'All the people',
'category': 1,
},
expected_code=201
)
pk = response.data['pk']
url = reverse('api-part-detail', kwargs={'pk': pk})
p = Part.objects.get(pk=pk)
# Part should not have an image!
with self.assertRaises(ValueError):
print(p.image.file)
# Create a custom APIClient for file uploads
# Ref: https://stackoverflow.com/questions/40453947/how-to-generate-a-file-upload-test-request-with-django-rest-frameworks-apireq
upload_client = APIClient()
upload_client.force_authenticate(user=self.user)
# Try to upload a non-image file
with open('dummy_image.txt', 'w') as dummy_image:
dummy_image.write('hello world')
with open('dummy_image.txt', 'rb') as dummy_image:
response = upload_client.patch(
url,
{
'image': dummy_image,
},
format='multipart',
)
self.assertEqual(response.status_code, 400)
# Now try to upload a valid image file
img = PIL.Image.new('RGB', (128, 128), color='red')
img.save('dummy_image.jpg')
with open('dummy_image.jpg', 'rb') as dummy_image:
response = upload_client.patch(
url,
{
'image': dummy_image,
},
format='multipart',
)
self.assertEqual(response.status_code, 200)
# And now check that the image has been set
p = Part.objects.get(pk=pk)
class PartAPIAggregationTest(InvenTreeAPITestCase):
"""
Tests to ensure that the various aggregation annotations are working correctly...
"""
fixtures = [
'category',
'company',
'part',
'location',
'bom',
'test_templates',
]
roles = [
'part.view',
'part.change',
]
def setUp(self):
super().setUp()
# Add a new part
self.part = Part.objects.create(
name='Banana',
description='This is a banana',
category=PartCategory.objects.get(pk=1),
)
# Create some stock items associated with the part
# First create 600 units which are OK
StockItem.objects.create(part=self.part, quantity=100)
StockItem.objects.create(part=self.part, quantity=200)
StockItem.objects.create(part=self.part, quantity=300)
# Now create another 400 units which are LOST
StockItem.objects.create(part=self.part, quantity=400, status=StockStatus.LOST)
def get_part_data(self):
url = reverse('api-part-list')
response = self.client.get(url, format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
for part in response.data:
if part['pk'] == self.part.pk:
return part
# We should never get here!
self.assertTrue(False) # pragma: no cover
def test_stock_quantity(self):
"""
Simple test for the stock quantity
"""
data = self.get_part_data()
self.assertEqual(data['in_stock'], 600)
self.assertEqual(data['stock_item_count'], 4)
# Add some more stock items!!
for i in range(100):
StockItem.objects.create(part=self.part, quantity=5)
# Add another stock item which is assigned to a customer (and shouldn't count)
customer = Company.objects.get(pk=4)
StockItem.objects.create(part=self.part, quantity=9999, customer=customer)
data = self.get_part_data()
self.assertEqual(data['in_stock'], 1100)
self.assertEqual(data['stock_item_count'], 105)
class BomItemTest(InvenTreeAPITestCase):
"""
Unit tests for the BomItem API
"""
fixtures = [
'category',
'part',
'location',
'stock',
'bom',
'company',
]
roles = [
'part.add',
'part.change',
'part.delete',
]
def setUp(self):
super().setUp()
def test_bom_list(self):
"""
Tests for the BomItem list endpoint
"""
# How many BOM items currently exist in the database?
n = BomItem.objects.count()
url = reverse('api-bom-list')
response = self.get(url, expected_code=200)
self.assertEqual(len(response.data), n)
# Now, filter by part
response = self.get(
url,
data={
'part': 100,
},
expected_code=200
)
# Filter by "validated"
response = self.get(
url,
data={
'validated': True,
},
expected_code=200,
)
# Should be zero validated results
self.assertEqual(len(response.data), 0)
# Now filter by "not validated"
response = self.get(
url,
data={
'validated': False,
},
expected_code=200
)
# There should be at least one non-validated item
self.assertTrue(len(response.data) > 0)
# Now, let's validate an item
bom_item = BomItem.objects.first()
bom_item.validate_hash()
response = self.get(
url,
data={
'validated': True,
},
expected_code=200
)
# Check that the expected response is returned
self.assertEqual(len(response.data), 1)
self.assertEqual(response.data[0]['pk'], bom_item.pk)
def test_get_bom_detail(self):
"""
Get the detail view for a single BomItem object
"""
url = reverse('api-bom-item-detail', kwargs={'pk': 3})
response = self.get(url, expected_code=200)
self.assertEqual(int(float(response.data['quantity'])), 25)
# Increase the quantity
data = response.data
data['quantity'] = 57
data['note'] = 'Added a note'
response = self.patch(url, data, expected_code=200)
self.assertEqual(int(float(response.data['quantity'])), 57)
self.assertEqual(response.data['note'], 'Added a note')
def test_add_bom_item(self):
"""
Test that we can create a new BomItem via the API
"""
url = reverse('api-bom-list')
data = {
'part': 100,
'sub_part': 4,
'quantity': 777,
}
self.post(url, data, expected_code=201)
# Now try to create a BomItem which references itself
data['part'] = 100
data['sub_part'] = 100
self.client.post(url, data, expected_code=400)
def test_variants(self):
"""
Tests for BomItem use with variants
"""
stock_url = reverse('api-stock-list')
# BOM item we are interested in
bom_item = BomItem.objects.get(pk=1)
bom_item.allow_variants = True
bom_item.save()
# sub part that the BOM item points to
sub_part = bom_item.sub_part
sub_part.is_template = True
sub_part.save()
# How many stock items are initially available for this part?
response = self.get(
stock_url,
{
'bom_item': bom_item.pk,
},
expected_code=200
)
n_items = len(response.data)
self.assertEqual(n_items, 2)
loc = StockLocation.objects.get(pk=1)
# Now we will create some variant parts and stock
for ii in range(5):
# Create a variant part!
variant = Part.objects.create(
name=f"Variant_{ii}",
description="A variant part",
component=True,
variant_of=sub_part
)
variant.save()
Part.objects.rebuild()
# Create some stock items for this new part
for jj in range(ii):
StockItem.objects.create(
part=variant,
location=loc,
quantity=100
)
# Keep track of running total
n_items += ii
# Now, there should be more stock items available!
response = self.get(
stock_url,
{
'bom_item': bom_item.pk,
},
expected_code=200
)
self.assertEqual(len(response.data), n_items)
# Now, disallow variant parts in the BomItem
bom_item.allow_variants = False
bom_item.save()
# There should now only be 2 stock items available again
response = self.get(
stock_url,
{
'bom_item': bom_item.pk,
},
expected_code=200
)
self.assertEqual(len(response.data), 2)
def test_substitutes(self):
"""
Tests for BomItem substitutes
"""
url = reverse('api-bom-substitute-list')
stock_url = reverse('api-stock-list')
# Initially we have no substitute parts
response = self.get(url, expected_code=200)
self.assertEqual(len(response.data), 0)
# BOM item we are interested in
bom_item = BomItem.objects.get(pk=1)
# Filter stock items which can be assigned against this stock item
response = self.get(
stock_url,
{
"bom_item": bom_item.pk,
},
expected_code=200
)
n_items = len(response.data)
loc = StockLocation.objects.get(pk=1)
# Let's make some!
for ii in range(5):
sub_part = Part.objects.create(
name=f"Substitute {ii}",
description="A substitute part",
component=True,
is_template=False,
assembly=False
)
# Create a new StockItem for this Part
StockItem.objects.create(
part=sub_part,
quantity=1000,
location=loc,
)
# Now, create an "alternative" for the BOM Item
BomItemSubstitute.objects.create(
bom_item=bom_item,
part=sub_part
)
# We should be able to filter the API list to just return this new part
response = self.get(url, data={'part': sub_part.pk}, expected_code=200)
self.assertEqual(len(response.data), 1)
# We should also have more stock available to allocate against this BOM item!
response = self.get(
stock_url,
{
"bom_item": bom_item.pk,
},
expected_code=200
)
self.assertEqual(len(response.data), n_items + ii + 1)
# There should now be 5 substitute parts available in the database
response = self.get(url, expected_code=200)
self.assertEqual(len(response.data), 5)
def test_bom_item_uses(self):
"""
Tests for the 'uses' field
"""
url = reverse('api-bom-list')
# Test that the direct 'sub_part' association works
assemblies = []
for i in range(5):
assy = Part.objects.create(
name=f"Assy_{i}",
description="An assembly made of other parts",
active=True,
assembly=True
)
assemblies.append(assy)
components = []
# Create some sub-components
for i in range(5):
cmp = Part.objects.create(
name=f"Component_{i}",
description="A sub component",
active=True,
component=True
)
for j in range(i):
# Create a BOM item
BomItem.objects.create(
quantity=10,
part=assemblies[j],
sub_part=cmp,
)
components.append(cmp)
response = self.get(
url,
{
'uses': cmp.pk,
},
expected_code=200,
)
self.assertEqual(len(response.data), i)
class PartParameterTest(InvenTreeAPITestCase):
"""
Tests for the ParParameter API
"""
superuser = True
fixtures = [
'category',
'part',
'location',
'params',
]
def setUp(self):
super().setUp()
def test_list_params(self):
"""
Test for listing part parameters
"""
url = reverse('api-part-parameter-list')
response = self.client.get(url, format='json')
self.assertEqual(len(response.data), 5)
# Filter by part
response = self.client.get(
url,
{
'part': 3,
},
format='json'
)
self.assertEqual(len(response.data), 3)
# Filter by template
response = self.client.get(
url,
{
'template': 1,
},
format='json',
)
self.assertEqual(len(response.data), 3)
def test_create_param(self):
"""
Test that we can create a param via the API
"""
url = reverse('api-part-parameter-list')
response = self.client.post(
url,
{
'part': '2',
'template': '3',
'data': 70
}
)
self.assertEqual(response.status_code, 201)
response = self.client.get(url, format='json')
self.assertEqual(len(response.data), 6)
def test_param_detail(self):
"""
Tests for the PartParameter detail endpoint
"""
url = reverse('api-part-parameter-detail', kwargs={'pk': 5})
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
data = response.data
self.assertEqual(data['pk'], 5)
self.assertEqual(data['part'], 3)
self.assertEqual(data['data'], '12')
# PATCH data back in
response = self.client.patch(url, {'data': '15'}, format='json')
self.assertEqual(response.status_code, 200)
# Check that the data changed!
response = self.client.get(url, format='json')
data = response.data
self.assertEqual(data['data'], '15')
|
inventree/InvenTree
|
InvenTree/part/test_api.py
|
Python
|
mit
| 36,773 |
var checkDep = require('../util').checkDep;
var isPrefixed = require('../util').isPrefixed;
var isGet = require('../util').isGet;
function create() {
return function(options) {
var models = checkDep(options, 'models');
var adapter = checkDep(options, 'adapter');
var prefix = checkDep(options, 'prefix');
var schema = adapter.getSchema(models);
return function(request, respone, next) {
var query = request.query.q;
if (isGet(request) && isPrefixed(request, prefix)) {
return adapter.graphql(schema, query)
.then(function(result) {
respone.json(result);
})
.catch(function(err) {
next(err);
});
}
return next();
};
};
}
module.exports.create = create;
|
terebentina/graffiti
|
src/express/index.js
|
JavaScript
|
mit
| 784 |
<?php
/*
* Created at 25.05.2009
*
* @author Markus Moeller - Twick.it
*/
require_once("../../util/inc.php");
printXMLHeader();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:widget="http://www.netvibes.com/ns/">
<head>
<title>Twick.it</title>
<link rel="icon" type="image/png" href="http://twick.it/interfaces/uwa/favicon.ico" />
<meta name="author" content="Markus M&ouml;ller - Twick.it" />
<meta name="author_email" content="[email protected]" />
<meta name="website" content="http://www.twick.it" />
<meta name="description" content="Allows to search explanations at Twick.it, the explain-engine." />
<meta name="version" content="0.1" />
<meta name="keywords" content="twick.it, explain engine, Erklärmaschine" />
<meta name="screenshot" content="http://twick.it/interfaces/uwa/screenshot.png" />
<meta name="thumbnail" content="http://twick.it/interfaces/uwa/thumbnail.png" />
<meta name="author_photo" content="http://www.gravatar.com/avatar/c437dd814266449417f7c3a0560de037?s=208" />
<meta name="author_link" content="http://twick.it/user/derlangemarkus" />
<meta name="apiVersion" content="1.0" />
<meta name="debugMode" content="true" />
<link rel="stylesheet" type="text/css" href="http://www.netvibes.com/themes/uwa/style.css" />
<script type="text/javascript" src="http://www.netvibes.com/js/UWA/load.js.php?env=Standalone"></script>
<widget:preferences>
<preference name="language" type="list" label="Language" onchange="refresh" defaultValue="de">
<option value="auto" label="auto" />
<?php foreach($languages as $languageData) { ?>
<option value="<?php echo($languageData["code"]) ?>" label="<?php echo($languageData["name"]) ?>" />
<?php } ?>
</preference>
</widget:preferences>
<style type="text/css">
body {
font-family: arial,sans-serif;
font-size:11px;
}
#search {
width:100%;
background-image:url(logo.gif);
background-position:right 1px;
background-repeat:no-repeat;
height:33px;
font-size:20px;
border: 1px solid #666;
}
.searchSuggest {
display:block;
color: #84b204;
font-weight:bold;
}
#searchSuggest {
height:200px;
overflow: auto;
}
#searchSuggest a {
text-decoration: none;
display:block;
}
#searchSuggest a:hover {
background-color:#EEE;
}
#searchSuggest span {
display:block;
}
.searchSuggestTags {
color:#333;
display:block;
overflow:hidden;
border-bottom:1px solid #333;
}
a.powered:link, a.powered:active, a.powered:visited {
float:right;
color:#666;
text-decoration: none;
padding-top:4px;
}
a.powered:hover, a.powered:focus {
color:#333;
text-decoration: underline;
}
</style>
<script type="text/javascript" src="<?php echo(HTTP_ROOT) ?>/html/js/scriptaculous/lib/prototype.js"></script>
<script type="text/javascript">
var suggestTimeouts;
var suggestIndex = -1;
var suggestLength = -1;
var prevSearch;
function updateSuggest() {
if(suggestTimeouts != null) {
clearTimeout(suggestTimeouts);
suggestTimeouts=window.setTimeout("_updateSuggest()", 150);
} else {
suggestTimeouts=window.setTimeout("_updateSuggest()", 0);
}
}
function _updateSuggest() {
var search = document.searchForm.search.value;
if (search != prevSearch) {
suggestIndex = -1;
if (search.length > 1) {
var url = "<?php echo(HTTP_ROOT) ?>/interfaces/api/explain.json?similar=1&lng=" + Twickit.getLanguage() + "&limit=20&search=" + encodeURIComponent(search);
UWA.Data.getJson(url, Twickit.display);
} else {
document.getElementById('searchSuggest').innerHTML = "";
}
prevSearch = search;
}
}
function searchUpDown(inEvent) {
var code; //variable to save keystroke
if (!inEvent) var inEvent = window.event; //did i get any event
if (inEvent.keyCode) code = inEvent.keyCode;
if (code == 38) {
if (suggestIndex > 0) {
updateSuggestIndex(false);
suggestIndex--;
document.getElementById("search").value = document.getElementById("searchSuggest" + suggestIndex).innerHTML;
prevSearch = document.getElementById("search").value;
}
} else if (code == 40) {
if (suggestIndex < suggestLength-1) {
updateSuggestIndex(true);
suggestIndex++;
document.getElementById("search").value = document.getElementById("searchSuggest" + suggestIndex).innerHTML;
prevSearch = document.getElementById("search").value;
}
} else {
updateSuggest();
}
}
function updateSuggestIndex(inDown) {
var nextIndex = inDown ? suggestIndex+1 : suggestIndex-1;
if (suggestIndex >= 0) {
document.getElementById("searchSuggest" + suggestIndex).style.backgroundColor = "#FFF";
document.getElementById("searchSuggestTags" + suggestIndex).style.backgroundColor = "#FFF";
}
document.getElementById("searchSuggest" + nextIndex).style.backgroundColor = "#CCC";
document.getElementById("searchSuggestTags" + nextIndex).style.backgroundColor = "#CCC";
}
var Twickit = {}
Twickit.updatePreferences = function() {
document.getElementById("twickitSubmitButton").value = Twickit.getLanguage() == "de" ? "Suchen" : "Search";
widget.setTitle("<a href='http://twick.it?lng=" + Twickit.getLanguage() + "'>Twick.it</a>");
}
Twickit.getLanguage = function() {
var curlang=widget.getValue('language');
if(curlang=='auto') {
curlang=widget.lang.substring(0,2);
}
return curlang;
}
Twickit.display = function(suggests) {
var suggestText = "";
for (var i=0; i<suggests.topics.length; i++) {
var tags = "";
var separator = "";
tags = suggests.topics[i].twicks[0].text;
if(i>=30) {
if (i==30) {
suggestText += "<a href='http://twick.it/find_topic.php?search=" + encodeURIComponent(search) + "&lng=" + Twickit.getLanguage() + "' target='_blank'>" + (Twickit.getLanguage() == "de" ? "mehr" : "more") + "</a>";
}
} else {
suggestText += "<a href='" + suggests.topics[i].url.replace(/'/g, "%27") + "' target='_top'><span id='searchSuggest" + i + "' class='searchSuggest'>" + suggests.topics[i].title + "</span><span class='searchSuggestTags' id='searchSuggestTags" + i + "'>" + tags + "</span></a>";
}
}
suggestLength = suggests.topics.length;
notice.innerHTML = suggestText;
}
</script>
</head>
<body>
<p><form action="<?php echo(HTTP_ROOT) ?>/find_topic.php" method="GET" name="searchForm" target="_top">
<input type="text" name="search" id="search" autocomplete="off" onfocus="this.select();"/>
<input type="submit" value="<?php loc('interfaces.igoogle.search') ?>" style="float:left;" id="twickitSubmitButton"/><a href="http://twick.it?lng=<?php echo(getLanguage()) ?>" target="_blank" class="powered">powered by Twick.it</a><br style="clear:both;" />
</form>
<div id="searchSuggest"></div>
<script type="text/javascript">
document.getElementById("search").onkeyup = searchUpDown;
widget.onRefresh = Twickit.updatePreferences;
widget.onLoad = Twickit.updatePreferences;
</script></p>
</body>
</html>
|
derlangemarkus/Twick.it
|
base/interfaces/uwa/gadget.php
|
PHP
|
mit
| 7,245 |
<?php
namespace JMS\SerializerBundle\Tests\Serializer;
use Doctrine\Common\Annotations\AnnotationReader;
use JMS\SerializerBundle\Metadata\Driver\AnnotationDriver;
use JMS\SerializerBundle\Serializer\GraphNavigator;
use Metadata\MetadataFactory;
class GraphNavigatorTest extends \PHPUnit_Framework_TestCase
{
private $metadataFactory;
private $navigator;
private $visitor;
/**
* @expectedException \RuntimeException
* @expectedExceptionMessage Resources are not supported in serialized data.
*/
public function testResourceThrowsException()
{
$this->navigator->accept(STDIN, null, $this->visitor);
}
protected function setUp()
{
$this->visitor = $this->getMock('JMS\SerializerBundle\Serializer\VisitorInterface');
$this->metadataFactory = new MetadataFactory(new AnnotationDriver(new AnnotationReader()));
$this->navigator = new GraphNavigator(GraphNavigator::DIRECTION_SERIALIZATION, $this->metadataFactory);
}
}
|
gayan/FoodCombo
|
vendor/jms/serializer-bundle/JMS/SerializerBundle/Tests/Serializer/GraphNavigatorTest.php
|
PHP
|
mit
| 1,007 |
<!doctype html>
<html class="default no-js">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Node | tomo</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../assets/css/main.css">
<script src="../assets/js/modernizr.js"></script>
</head>
<body>
<header>
<div class="tsd-page-toolbar">
<div class="container">
<div class="table-wrap">
<div class="table-cell" id="tsd-search" data-index="../assets/js/search.js" data-base="..">
<div class="field">
<label for="tsd-search-field" class="tsd-widget search no-caption">Search</label>
<input id="tsd-search-field" type="text" />
</div>
<ul class="results">
<li class="state loading">Preparing search index...</li>
<li class="state failure">The search index is not available</li>
</ul>
<a href="../index.html" class="title">tomo</a>
</div>
<div class="table-cell" id="tsd-widgets">
<div id="tsd-filter">
<a href="#" class="tsd-widget options no-caption" data-toggle="options">Options</a>
<div class="tsd-filter-group">
<div class="tsd-select" id="tsd-filter-visibility">
<span class="tsd-select-label">All</span>
<ul class="tsd-select-list">
<li data-value="public">Public</li>
<li data-value="protected">Public/Protected</li>
<li data-value="private" class="selected">All</li>
</ul>
</div>
<input type="checkbox" id="tsd-filter-inherited" checked />
<label class="tsd-widget" for="tsd-filter-inherited">Inherited</label>
<input type="checkbox" id="tsd-filter-externals" checked />
<label class="tsd-widget" for="tsd-filter-externals">Externals</label>
<input type="checkbox" id="tsd-filter-only-exported" />
<label class="tsd-widget" for="tsd-filter-only-exported">Only exported</label>
</div>
</div>
<a href="#" class="tsd-widget menu no-caption" data-toggle="menu">Menu</a>
</div>
</div>
</div>
</div>
<div class="tsd-page-title">
<div class="container">
<ul class="tsd-breadcrumb">
<li>
<a href="../globals.html">Globals</a>
</li>
<li>
<a href="../modules/_node_.html">"Node"</a>
</li>
<li>
<a href="_node_.node.html">Node</a>
</li>
</ul>
<h1>Class Node</h1>
</div>
</div>
</header>
<div class="container container-main">
<div class="row">
<div class="col-8 col-content">
<section class="tsd-panel tsd-hierarchy">
<h3>Hierarchy</h3>
<ul class="tsd-hierarchy">
<li>
<span class="target">Node</span>
</li>
</ul>
</section>
<section class="tsd-panel-group tsd-index-group">
<h2>Index</h2>
<section class="tsd-panel tsd-index-panel">
<div class="tsd-index-content">
<section class="tsd-index-section tsd-is-not-exported">
<h3>Constructors</h3>
<ul class="tsd-index-list">
<li class="tsd-kind-constructor tsd-parent-kind-class tsd-is-not-exported"><a href="_node_.node.html#constructor" class="tsd-kind-icon">constructor</a></li>
</ul>
</section>
<section class="tsd-index-section tsd-is-not-exported">
<h3>Properties</h3>
<ul class="tsd-index-list">
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-not-exported"><a href="_node_.node.html#location" class="tsd-kind-icon">location</a></li>
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-not-exported"><a href="_node_.node.html#position" class="tsd-kind-icon">position</a></li>
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-not-exported"><a href="_node_.node.html#type" class="tsd-kind-icon">type</a></li>
</ul>
</section>
</div>
</section>
</section>
<section class="tsd-panel-group tsd-member-group tsd-is-not-exported">
<h2>Constructors</h2>
<section class="tsd-panel tsd-member tsd-kind-constructor tsd-parent-kind-class tsd-is-not-exported">
<a name="constructor" class="tsd-anchor"></a>
<h3>constructor</h3>
<ul class="tsd-signatures tsd-kind-constructor tsd-parent-kind-class tsd-is-not-exported">
<li class="tsd-signature tsd-kind-icon">new <wbr>Node<span class="tsd-signature-symbol">(</span>type<span class="tsd-signature-symbol">: </span><span class="tsd-signature-type">any</span>, position<span class="tsd-signature-symbol">: </span><span class="tsd-signature-type">any</span>, location<span class="tsd-signature-symbol">: </span><span class="tsd-signature-type">any</span><span class="tsd-signature-symbol">)</span><span class="tsd-signature-symbol">: </span><a href="_node_.node.html" class="tsd-signature-type">Node</a></li>
</ul>
<ul class="tsd-descriptions">
<li class="tsd-description">
<aside class="tsd-sources">
<ul>
<li>Defined in <a href="https://github.com/iwatakeshi/tomo/blob/master/src/Node.ts#L4">Node.ts:4</a></li>
</ul>
</aside>
<h4 class="tsd-parameters-title">Parameters</h4>
<ul class="tsd-parameters">
<li>
<h5>type: <span class="tsd-signature-type">any</span></h5>
</li>
<li>
<h5>position: <span class="tsd-signature-type">any</span></h5>
</li>
<li>
<h5>location: <span class="tsd-signature-type">any</span></h5>
</li>
</ul>
<h4 class="tsd-returns-title">Returns <a href="_node_.node.html" class="tsd-signature-type">Node</a></h4>
</li>
</ul>
</section>
</section>
<section class="tsd-panel-group tsd-member-group tsd-is-not-exported">
<h2>Properties</h2>
<section class="tsd-panel tsd-member tsd-kind-property tsd-parent-kind-class tsd-is-not-exported">
<a name="location" class="tsd-anchor"></a>
<h3>location</h3>
<div class="tsd-signature tsd-kind-icon">location<span class="tsd-signature-symbol">:</span> <span class="tsd-signature-type">any</span></div>
<aside class="tsd-sources">
<ul>
<li>Defined in <a href="https://github.com/iwatakeshi/tomo/blob/master/src/Node.ts#L4">Node.ts:4</a></li>
</ul>
</aside>
</section>
<section class="tsd-panel tsd-member tsd-kind-property tsd-parent-kind-class tsd-is-not-exported">
<a name="position" class="tsd-anchor"></a>
<h3>position</h3>
<div class="tsd-signature tsd-kind-icon">position<span class="tsd-signature-symbol">:</span> <span class="tsd-signature-type">any</span></div>
<aside class="tsd-sources">
<ul>
<li>Defined in <a href="https://github.com/iwatakeshi/tomo/blob/master/src/Node.ts#L3">Node.ts:3</a></li>
</ul>
</aside>
</section>
<section class="tsd-panel tsd-member tsd-kind-property tsd-parent-kind-class tsd-is-not-exported">
<a name="type" class="tsd-anchor"></a>
<h3>type</h3>
<div class="tsd-signature tsd-kind-icon">type<span class="tsd-signature-symbol">:</span> <span class="tsd-signature-type">any</span></div>
<aside class="tsd-sources">
<ul>
<li>Defined in <a href="https://github.com/iwatakeshi/tomo/blob/master/src/Node.ts#L2">Node.ts:2</a></li>
</ul>
</aside>
</section>
</section>
</div>
<div class="col-4 col-menu menu-sticky-wrap menu-highlight">
<nav class="tsd-navigation primary">
<ul>
<li class="globals ">
<a href="../globals.html"><em>Globals</em></a>
</li>
<li class=" tsd-kind-external-module">
<a href="../modules/_collections_.html">"<wbr>Collections"</a>
</li>
<li class=" tsd-kind-external-module">
<a href="../modules/_location_.html">"<wbr>Location"</a>
</li>
<li class="current tsd-kind-external-module">
<a href="../modules/_node_.html">"<wbr>Node"</a>
</li>
<li class=" tsd-kind-external-module">
<a href="../modules/_options_.html">"<wbr>Options"</a>
</li>
<li class=" tsd-kind-external-module">
<a href="../modules/_parser_.html">"<wbr>Parser"</a>
</li>
<li class=" tsd-kind-external-module">
<a href="../modules/_scanner_.html">"<wbr>Scanner"</a>
</li>
<li class=" tsd-kind-external-module">
<a href="../modules/_source_.html">"<wbr>Source"</a>
</li>
<li class=" tsd-kind-external-module">
<a href="../modules/_stream_.html">"<wbr>Stream"</a>
</li>
<li class=" tsd-kind-external-module">
<a href="../modules/_token_.html">"<wbr>Token"</a>
</li>
<li class=" tsd-kind-external-module">
<a href="../modules/_utils_.html">"<wbr>Utils"</a>
</li>
</ul>
</nav>
<nav class="tsd-navigation secondary menu-sticky">
<ul class="before-current">
</ul>
<ul class="current">
<li class="current tsd-kind-class tsd-parent-kind-external-module tsd-is-not-exported">
<a href="_node_.node.html" class="tsd-kind-icon">Node</a>
<ul>
<li class=" tsd-kind-constructor tsd-parent-kind-class tsd-is-not-exported">
<a href="_node_.node.html#constructor" class="tsd-kind-icon">constructor</a>
</li>
<li class=" tsd-kind-property tsd-parent-kind-class tsd-is-not-exported">
<a href="_node_.node.html#location" class="tsd-kind-icon">location</a>
</li>
<li class=" tsd-kind-property tsd-parent-kind-class tsd-is-not-exported">
<a href="_node_.node.html#position" class="tsd-kind-icon">position</a>
</li>
<li class=" tsd-kind-property tsd-parent-kind-class tsd-is-not-exported">
<a href="_node_.node.html#type" class="tsd-kind-icon">type</a>
</li>
</ul>
</li>
</ul>
<ul class="after-current">
</ul>
</nav>
</div>
</div>
</div>
<footer class="with-border-bottom">
<div class="container">
<h2>Legend</h2>
<div class="tsd-legend-group">
<ul class="tsd-legend">
<li class="tsd-kind-module"><span class="tsd-kind-icon">Module</span></li>
<li class="tsd-kind-object-literal"><span class="tsd-kind-icon">Object literal</span></li>
<li class="tsd-kind-variable"><span class="tsd-kind-icon">Variable</span></li>
<li class="tsd-kind-function"><span class="tsd-kind-icon">Function</span></li>
<li class="tsd-kind-function tsd-has-type-parameter"><span class="tsd-kind-icon">Function with type parameter</span></li>
<li class="tsd-kind-index-signature"><span class="tsd-kind-icon">Index signature</span></li>
<li class="tsd-kind-type-alias"><span class="tsd-kind-icon">Type alias</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-enum"><span class="tsd-kind-icon">Enumeration</span></li>
<li class="tsd-kind-enum-member"><span class="tsd-kind-icon">Enumeration member</span></li>
<li class="tsd-kind-property tsd-parent-kind-enum"><span class="tsd-kind-icon">Property</span></li>
<li class="tsd-kind-method tsd-parent-kind-enum"><span class="tsd-kind-icon">Method</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-interface"><span class="tsd-kind-icon">Interface</span></li>
<li class="tsd-kind-interface tsd-has-type-parameter"><span class="tsd-kind-icon">Interface with type parameter</span></li>
<li class="tsd-kind-constructor tsd-parent-kind-interface"><span class="tsd-kind-icon">Constructor</span></li>
<li class="tsd-kind-property tsd-parent-kind-interface"><span class="tsd-kind-icon">Property</span></li>
<li class="tsd-kind-method tsd-parent-kind-interface"><span class="tsd-kind-icon">Method</span></li>
<li class="tsd-kind-index-signature tsd-parent-kind-interface"><span class="tsd-kind-icon">Index signature</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-class"><span class="tsd-kind-icon">Class</span></li>
<li class="tsd-kind-class tsd-has-type-parameter"><span class="tsd-kind-icon">Class with type parameter</span></li>
<li class="tsd-kind-constructor tsd-parent-kind-class"><span class="tsd-kind-icon">Constructor</span></li>
<li class="tsd-kind-property tsd-parent-kind-class"><span class="tsd-kind-icon">Property</span></li>
<li class="tsd-kind-method tsd-parent-kind-class"><span class="tsd-kind-icon">Method</span></li>
<li class="tsd-kind-accessor tsd-parent-kind-class"><span class="tsd-kind-icon">Accessor</span></li>
<li class="tsd-kind-index-signature tsd-parent-kind-class"><span class="tsd-kind-icon">Index signature</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-constructor tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited constructor</span></li>
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited property</span></li>
<li class="tsd-kind-method tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited method</span></li>
<li class="tsd-kind-accessor tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited accessor</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-protected"><span class="tsd-kind-icon">Protected property</span></li>
<li class="tsd-kind-method tsd-parent-kind-class tsd-is-protected"><span class="tsd-kind-icon">Protected method</span></li>
<li class="tsd-kind-accessor tsd-parent-kind-class tsd-is-protected"><span class="tsd-kind-icon">Protected accessor</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-private"><span class="tsd-kind-icon">Private property</span></li>
<li class="tsd-kind-method tsd-parent-kind-class tsd-is-private"><span class="tsd-kind-icon">Private method</span></li>
<li class="tsd-kind-accessor tsd-parent-kind-class tsd-is-private"><span class="tsd-kind-icon">Private accessor</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-static"><span class="tsd-kind-icon">Static property</span></li>
<li class="tsd-kind-call-signature tsd-parent-kind-class tsd-is-static"><span class="tsd-kind-icon">Static method</span></li>
</ul>
</div>
</div>
</footer>
<div class="container tsd-generator">
<p>Generated using <a href="http://typedoc.io" target="_blank">TypeDoc</a></p>
</div>
<div class="overlay"></div>
<script src="../assets/js/main.js"></script>
<script>if (location.protocol == 'file:') document.write('<script src="../assets/js/search.js"><' + '/script>');</script>
</body>
</html>
|
iwatakeshi/cherry
|
documenation/classes/_node_.node.html
|
HTML
|
mit
| 14,513 |
<!DOCTYPE html><title>comix-ngn Infinite</title>
<!--<script src="plugins/bellerophon.cng.min.js" dir template></script>-->
<script src="../comixngn.js" comicID="big" disable="rollbar" dir="../" tir="../" air="../assets/"></script>
<script src="../plugins/infinite.cng.js" ></script>
<!--<base href="/comic-ng/">-->
<div id="standard" class="venue"></div>
|
seun40/comix-ngn
|
labs/infinitetest.html
|
HTML
|
mit
| 355 |
---
title: Ukuqobeka Nokudinwa
date: 27/06/2021
---
`Funda: uGenesis 2:1–3. Kungani ukuba uThixo adale umhla wokuphumla kungekabikho mntu udiniweyo?`
Uluntu lungekabaleki luye kuzifaka kubomi obuneengxaki, uThixo wamisela uPhawu, indlela ephilileyo yokusebenzisa inkumbulo yethu. Lo mhla wawuza kuba lixesha lokuyeka nokonwabela ngokuzithandela ubomi; umhla wokuqikileka nje nokungenzi nto, umhla wokonwabela ukubuka isipho sengca, umoya, izilwanyana, amanzi, abantu, ngaphezu kwako konke, uMdali waso sonke isipho esilungileyo.
Esi yayingesiso isimemo sexesha elinye elaliza kuphela kwakuphunywa e-Eden. UThixo wayefuna ukuqinisekisa ukuba isimemo siya kumelana nexesha, waza wathi kwasekuqalekeni, wasontela uphumlo lweSabatha kulo lonke ilaphu lexesha. Sasiya kuhlala sikho isimemo rhoqo, sokuvuyela ukuphumla kweNdalo lonke ixesha ngomhla wesixhenxe.
Umntu ebengacinga ukuba, njengoko sinezixhobo zokwenza singasebenzi nzima, besimelwe kukungadinwa njengabo babephila kumawaka amabini eminyaka eyadlulayo. Sekunjalo, akwanelanga ngoku ukuphumla. Nemizuzu esingasebenziyo ngayo nayo ichithwa ngokwenza into eninzi. Sisoloko singathi sishiywe lixesha; nokuba sesenze okungakanani, kusala kukuninzi ekufuneka kwenziwe.
Uphando lukwabonisa ukuba, silala kancinane, kwaye abaninzi baxhomekeka kwisiyobisi ukubagcina bengalelanga. Nangona sineecell phones ezikhawulezayo, iikhompyutha ezenza uqhagamshelo olukhawulezayo, sekunjalo asinaxesha laneleyo.
`Zifundisa ntoni ezi ndima zilandelayo ngokubaluleka kokuba sifumane ukuphumla? Marko 6:31, INdumiso 4:8, Eksodus 23:12, Duteronomi 5:14, noMateyu 11:28.`
UThixo owasidalayo wayesazi ukuba siya kuludinga uphumlo lomzimba. Wakha imijikelezo exesheni—ubusuku, neSabatha—ukuze asinike ithuba lophumlo lomzimba. Ukumamkela uYesu njengeNkosi yobomi bethu nako kubandakanya ukukuxabisa kwethu ukwenza ithuba lokuphumla. Ngapha koko, umthetho weSabatha awulilo icebiso nje kuphela. Ungumyalelo!
`Uthini ngobukho bakho obukutshutshisayo? Ungenza ntoni ukuze ufumane kakuhle ukuphumla, okwasemzimbeni nokwasemoyeni, uThixo afuna ukuba sibe nako?`
|
imasaru/sabbath-school-lessons
|
src/xh/2021-03/01/02.md
|
Markdown
|
mit
| 2,103 |
# -*- coding: utf-8 -*-
from irc3 import testing
class TestUserList(testing.BotTestCase):
def test_userlist(self):
bot = self.callFTU(nick='foo')
bot.include('irc3.plugins.core',
'irc3.plugins.userlist')
plugin = bot.get_plugin('irc3.plugins.userlist.Userlist')
bot.dispatch(':bar!u@b JOIN #foo')
self.assertIn('bar', plugin.channels['#foo'])
self.assertNotIn('bar', plugin.channels['#bar'])
self.assertIn('bar', plugin.nicks)
bot.dispatch(':bar!u@b JOIN #bar')
self.assertIn('bar', plugin.channels['#bar'])
self.assertIn('bar', plugin.nicks)
bot.dispatch(':gawel!u@h MODE #foo +v-v+v bar bar bar')
self.assertIn('bar', plugin.channels['#foo'].modes['+'])
bot.dispatch(':foo!u@b KICK #foo bar :bastard!')
self.assertNotIn('bar', plugin.channels['#foo'])
self.assertNotIn('bar', plugin.channels['#foo'].modes['+'])
bot.dispatch(':gawel!u@h MODE #foo +c') # coverage
bot.dispatch(':gawel!u@h MODE gawel') # coverage
bot.dispatch(':gawel!u@h MODE #bar +v bar')
self.assertIn('bar', plugin.channels['#bar'].modes['+'])
bot.dispatch(':bar!u@b NICK babar')
self.assertIn('babar', plugin.nicks)
self.assertIn('babar', plugin.channels['#bar'])
self.assertIn('babar', plugin.channels['#bar'].modes['+'])
self.assertNotIn('bar', plugin.channels['#bar'].modes['+'])
bot.dispatch(':babar!u@b QUIT :lksdlds')
self.assertNotIn('babar', plugin.nicks)
self.assertNotIn('babar', plugin.channels['#bar'])
bot.dispatch(':serv 352 irc3 #chan ~user host serv bar H@ :Blah')
self.assertIn('bar', plugin.channels['#chan'])
self.assertIn('bar', plugin.nicks)
bot.dispatch(':serv 353 irc3 = #chan2 :bar @gawel')
self.assertIn('bar', plugin.channels['#chan2'])
self.assertIn('gawel', plugin.channels['#chan2'])
self.assertIn('gawel', plugin.channels['#chan2'].modes['@'])
self.assertIn('gawel', plugin.nicks)
bot.notify('connection_lost')
self.assertEqual(len(plugin.nicks), 0)
self.assertEqual(len(plugin.channels), 0)
bot.dispatch(':serv 353 irc3 = #chan2 :bar @gawel')
self.assertEqual(len(plugin.nicks), 2)
self.assertEqual(len(plugin.channels), 1)
bot.dispatch(':gawel!u@h MODE #chan2 +v bar')
self.assertIn('bar', plugin.channels['#chan2'].modes['+'])
bot.dispatch(':bar!u@h PART #chan2')
self.assertEqual(len(plugin.nicks), 1)
self.assertNotIn('bar', plugin.channels['#chan2'].modes['+'])
bot.dispatch(':foo!u@h PART #chan2')
self.assertNotIn('#chan2', plugin.channels)
bot.dispatch(':foo!u@h QUIT')
self.assertEqual(len(plugin.nicks), 0)
|
mrhanky17/irc3
|
tests/test_userlist.py
|
Python
|
mit
| 2,865 |
/*
* pLowPassFilter.cpp
*
* Author: Petel__
* Copyright (c) 2014-2016 HKUST SmartCar Team
* Refer to LICENSE for details
*/
#include <pLowPassFilter.h>
using namespace std;
using namespace libsc;
pLowPassFilter::pLowPassFilter(float Beta)
:
m_lastOutput(0.0f),
m_beta(Beta)
{}
pLowPassFilter::pLowPassFilter(Timer::TimerInt dt, float timeConst)
:
m_lastOutput(0.0f),
m_beta(dt / (timeConst + dt))
{}
float pLowPassFilter::filter(const float val)
{
return (m_lastOutput = m_lastOutput + m_beta * (val - m_lastOutput));
}
|
hkust-smartcar/Magnetic16-T1
|
src/pComponents/pLowPassFilter.cpp
|
C++
|
mit
| 565 |
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.network.v2019_04_01;
import java.util.Collection;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.microsoft.rest.ExpandableStringEnum;
/**
* Defines values for VirtualNetworkGatewayType.
*/
public final class VirtualNetworkGatewayType extends ExpandableStringEnum<VirtualNetworkGatewayType> {
/** Static value Vpn for VirtualNetworkGatewayType. */
public static final VirtualNetworkGatewayType VPN = fromString("Vpn");
/** Static value ExpressRoute for VirtualNetworkGatewayType. */
public static final VirtualNetworkGatewayType EXPRESS_ROUTE = fromString("ExpressRoute");
/**
* Creates or finds a VirtualNetworkGatewayType from its string representation.
* @param name a name to look for
* @return the corresponding VirtualNetworkGatewayType
*/
@JsonCreator
public static VirtualNetworkGatewayType fromString(String name) {
return fromString(name, VirtualNetworkGatewayType.class);
}
/**
* @return known VirtualNetworkGatewayType values
*/
public static Collection<VirtualNetworkGatewayType> values() {
return values(VirtualNetworkGatewayType.class);
}
}
|
navalev/azure-sdk-for-java
|
sdk/network/mgmt-v2019_04_01/src/main/java/com/microsoft/azure/management/network/v2019_04_01/VirtualNetworkGatewayType.java
|
Java
|
mit
| 1,440 |
var once = require('once')
module.exports = function untagResource(store, data, cb) {
cb = once(cb)
var tableName = data.ResourceArn.split('/').pop()
store.getTable(tableName, false, function(err) {
if (err && err.name == 'NotFoundError') {
err.body.message = 'Requested resource not found'
}
if (err) return cb(err)
var batchDeletes = data.TagKeys.map(function(key) { return {type: 'del', key: key} })
store.getTagDb(tableName).batch(batchDeletes, function(err) {
if (err) return cb(err)
cb(null, '')
})
})
}
|
mapbox/dynalite
|
actions/untagResource.js
|
JavaScript
|
mit
| 565 |
<ul class="listado">
{% for prospecto in prospectos %}
<a href="{{ path('prospecto', {cliente: id_cliente, prospecto: prospecto.id_u_cliente })}}">
<li>
{{ prospecto.nombre_prospecto }} {{ prospecto.apellido_prospecto }}
</li>
</a>
{% endfor %}
</ul>
|
cristianangulo/secsx
|
templates/includes/nav-prospectos.html
|
HTML
|
mit
| 273 |
# Generated by Django 2.1.5 on 2019-02-12 05:11
import django.contrib.postgres.fields
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('private_sharing', '0016_auto_20190128_2111'),
]
operations = [
migrations.AlterModelOptions(
name='datarequestproject',
options={'ordering': ['name']},
),
migrations.AddField(
model_name='datarequestproject',
name='requested_sources',
field=models.ManyToManyField(related_name='requesting_projects', to='private_sharing.DataRequestProject'),
),
migrations.AddField(
model_name='datarequestprojectmember',
name='granted_sources',
field=models.ManyToManyField(to='private_sharing.DataRequestProject'),
),
migrations.AlterField(
model_name='datarequestproject',
name='request_sources_access',
field=django.contrib.postgres.fields.ArrayField(base_field=models.CharField(max_length=100), blank=True, default=list, help_text='List of sources this project is requesting access to on Open Humans.', size=None),
),
]
|
OpenHumans/open-humans
|
private_sharing/migrations/0017_auto_20190212_0511.py
|
Python
|
mit
| 1,218 |
---
layout: default
pagination:
enabled: true
---
<!-- Pagination -->
{% include paginate.html %}
|
bsullins/teslanomics.github.io
|
index.html
|
HTML
|
mit
| 100 |
import os
from pymt.component.component import Component
def test_print_events(tmpdir, with_no_components):
air = Component.load(
"""
name: air_port
class: AirPort
print:
- name: air__temperature
interval: 25.
format: nc
"""
)
earth = Component.load(
"""
name: earth_port
class: EarthPort
print:
- name: glacier_top_surface__slope
interval: 20.
format: netcdf
"""
)
with tmpdir.as_cwd():
earth.connect(
"air_port",
air,
vars_to_map=[
("glacier_top_surface__slope", "air__temperature"),
("earth_surface__temperature", "air__temperature"),
],
)
earth.go()
assert os.path.isfile("glacier_top_surface__slope.nc")
assert os.path.isfile("air__temperature.nc")
|
csdms/coupling
|
tests/component/test_map_component.py
|
Python
|
mit
| 822 |
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M21 3H3c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h5v1c0 .55.45 1 1 1h6c.55 0 1-.45 1-1v-1h5c1.1 0 1.99-.9 1.99-2L23 5c0-1.11-.9-2-2-2zm-1 14H4c-.55 0-1-.45-1-1V6c0-.55.45-1 1-1h16c.55 0 1 .45 1 1v10c0 .55-.45 1-1 1zm-5.52-5.13l-3.98 2.28c-.67.38-1.5-.11-1.5-.87V8.72c0-.77.83-1.25 1.5-.87l3.98 2.28c.67.39.67 1.35 0 1.74z" /></g></React.Fragment>
, 'OndemandVideoRounded');
|
Kagami/material-ui
|
packages/material-ui-icons/src/OndemandVideoRounded.js
|
JavaScript
|
mit
| 544 |
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon([/*#__PURE__*/_jsx("path", {
d: "M12 4c-4.41 0-8 3.59-8 8s3.59 8 8 8 8-3.59 8-8-3.59-8-8-8zm2.01 10.01L6.5 17.5l3.49-7.51L17.5 6.5l-3.49 7.51z",
opacity: ".3"
}, "0"), /*#__PURE__*/_jsx("path", {
d: "M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm-5.5-2.5 7.51-3.49L17.5 6.5 9.99 9.99 6.5 17.5zm5.5-6.6c.61 0 1.1.49 1.1 1.1s-.49 1.1-1.1 1.1-1.1-.49-1.1-1.1.49-1.1 1.1-1.1z"
}, "1")], 'ExploreTwoTone');
|
oliviertassinari/material-ui
|
packages/mui-icons-material/lib/esm/ExploreTwoTone.js
|
JavaScript
|
mit
| 615 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_24) on Wed Apr 17 10:23:34 UTC 2013 -->
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
org.encog.ml.anneal (Encog Core 3.2.0-SNAPSHOT API)
</TITLE>
<META NAME="date" CONTENT="2013-04-17">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title = "org.encog.ml.anneal (Encog Core 3.2.0-SNAPSHOT API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-use.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../org/encog/ml/package-summary.html"><B>PREV PACKAGE</B></A>
<A HREF="../../../../org/encog/ml/bayesian/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?org/encog/ml/anneal/package-summary.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-summary.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if (window == top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<H2>
Package org.encog.ml.anneal
</H2>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Class Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../org/encog/ml/anneal/SimulatedAnnealing.html" title="class in org.encog.ml.anneal">SimulatedAnnealing<UNIT_TYPE></A></B></TD>
<TD>Simulated annealing is a common training method.</TD>
</TR>
</TABLE>
<P>
<DL>
</DL>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-use.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../org/encog/ml/package-summary.html"><B>PREV PACKAGE</B></A>
<A HREF="../../../../org/encog/ml/bayesian/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?org/encog/ml/anneal/package-summary.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-summary.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if (window == top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright © 2013. All Rights Reserved.
</BODY>
</HTML>
|
ladygagapowerbot/bachelor-thesis-implementation
|
lib/Encog/apidocs/org/encog/ml/anneal/package-summary.html
|
HTML
|
mit
| 8,108 |
var GcodeViewer = function(canvas) {
var _stage,
_txtLayer,
_layer;
var init = function() {
_stage = new Kinetic.Stage({
container: 'gcode-viewer',
width: 640,
height: 480
});
_layer = new Kinetic.Layer();
_txtLayer = new Kinetic.Layer();
_stage.add(_layer);
//_stage.add(_txtLayer);
/**
* Ugly debug code
*/
var bk = new Kinetic.Rect({
x:0,
y:0,
width: _stage.getWidth(),
height: _stage.getHeight(),
fill:"white",opacity:0.01
});
//_txtLayer.add(bk);
//var mouseText = new Kinetic.Text({
// fill: 'black',
// text: ''
//});
//
//_txtLayer.add(mouseText);
//
//bk.on('mousemove', function() {
// var pos = _stage.getPointerPosition();
// mouseText.text('x ' + pos.x + ' / y ' + pos.y);
// mouseText.x(pos.x);
// mouseText.y(pos.y - 15);
// _txtLayer.draw();
//});
//
//bk.on('click', function() {
// var pos = _stage.getPointerPosition();
// var point = new Kinetic.Ellipse({
// radius: {
// x: 2,
// y: 2
// },
// x: pos.x,
// y: pos.y,
// fill: 'red'
// });
// _txtLayer.add(point);
// _txtLayer.draw();
//});
_txtLayer.draw();
};
this.draw = function(data) {
var parsedData;
try {
parsedData = jQuery.parseJSON(data);
} catch(e) {}
// is it json or gcode ? Yo ?
if(parsedData) {
drawGeoJson(parsedData);
} else {
drawGcode(data);
}
_layer.draw();
};
var drawGeoJson = function(data) {
for(var i = 0; i < data.features.length; i++) {
var feature = data.features[i];
for(var j = 0; j < feature.geometry.coordinates.length; j++) {
var coordinate = feature.geometry.coordinates[j];
for(var k = 0; k < coordinate.length; k++) {
var line = new Kinetic.Line({
points: [
coordinate[k-1 >= 0 ? k-1 : k][0],
_stage.getHeight() - coordinate[k-1 >= 0 ? k-1 : k][1],
coordinate[k][0],
_stage.getHeight() - coordinate[k][1]],
stroke: k % 2 ? 'black' : 'red',
tension: 1
});
_layer.add(line);
}
}
}
};
var drawGcode = function(data) {
data = data.split('\n');
var coords = [];
var isSilent = false; // test Z in gcode to know if we trace or not
var noPrevious = false;
for(var i = 0; i < data.length; i++) {
var command = data[i].split(' ');
if(command[2] && command[2][0] === 'Z') {
var zValue = command[2].substr(1);
// if we just got out of a Z0 command (light just went on)
noPrevious = zValue <= 0;
zValue > 0 ? isSilent = false : isSilent = true;
}
if(command[2]&& command[2][0] === 'X') {
//if(!isSilent) {
var x = command[2].substr(1);
var y = _stage.getHeight() - command[3].substr(1);
var prevCoord;
if(!noPrevious) {
var line = new Kinetic.Line({
points: [
coords.length-1 >= 0 ? coords[coords.length-1].x : 0,
coords.length-1 >= 0 ? coords[coords.length-1].y : 0,
x,
y
],
stroke: i % 2 ? 'black' : 'red',
tension: 1
});
_layer.add(line);
}
//}
coords.push({x: x, y: y});
}
}
};
this.clear = function() {
_layer.removeChildren();
//context.clearRect(0, 0, canvas.width, canvas.height);
};
init();
};
|
3000d/node-drawbot
|
web/public_html/assets/js/gcodeViewer.js
|
JavaScript
|
mit
| 3,627 |
<?php
/*
* This file is part of the PostmanGeneratorBundle package.
*
* (c) Vincent Chalamon <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace RequestParser;
use PostmanGeneratorBundle\RequestParser\RequestParserChain;
use Prophecy\Prophecy\ObjectProphecy;
class RequestParserChainTest extends \PHPUnit_Framework_TestCase
{
/**
* @var ObjectProphecy
*/
private $requestMock;
/**
* @var ObjectProphecy
*/
private $requestParserMock;
/**
* @var RequestParserChain
*/
private $parser;
/**
* {@inheritdoc}
*/
protected function setUp()
{
$this->requestMock = $this->prophesize('PostmanGeneratorBundle\Model\Request');
$this->requestParserMock = $this->prophesize('PostmanGeneratorBundle\RequestParser\RequestParserInterface');
$this->parser = new RequestParserChain([
$this->requestParserMock->reveal(),
$this->requestParserMock->reveal(),
]);
}
public function testSupports()
{
$this->assertTrue($this->parser->supports($this->requestMock->reveal()));
}
public function testParse()
{
$this->requestParserMock->supports($this->requestMock->reveal())
->willReturn(true, false)
->shouldBeCalledTimes(2);
$this->requestParserMock->parse($this->requestMock->reveal())->shouldBeCalledTimes(1);
$this->parser->parse($this->requestMock->reveal());
}
}
|
toofff/PostmanGeneratorBundle
|
tests/RequestParser/RequestParserChainTest.php
|
PHP
|
mit
| 1,593 |
package elasta.orm.query.expression.builder;
import elasta.criteria.Func;
import java.util.List;
/**
* Created by Jango on 17/02/09.
*/
public interface HavingBuilder {
HavingBuilder add(Func func);
HavingBuilder add(List<Func> funcs);
List<Func> build();
}
|
codefacts/Elastic-Components
|
elasta-orm/src/main/java/elasta/orm/query/expression/builder/HavingBuilder.java
|
Java
|
mit
| 283 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="es">
<head>
<!-- Generated by javadoc (version 1.7.0_03) on Tue Jun 19 11:19:54 COT 2012 -->
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>W-Index</title>
<meta name="date" content="2012-06-19">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="W-Index";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../overview-summary.html">Overview</a></li>
<li>Package</li>
<li>Class</li>
<li>Use</li>
<li><a href="../overview-tree.html">Tree</a></li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li class="navBarCell1Rev">Index</li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="index-19.html">Prev Letter</a></li>
<li><a href="index-21.html">Next Letter</a></li>
</ul>
<ul class="navList">
<li><a href="../index.html?index-filesindex-20.html" target="_top">Frames</a></li>
<li><a href="index-20.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="contentContainer"><a href="index-1.html">A</a> <a href="index-2.html">B</a> <a href="index-3.html">C</a> <a href="index-4.html">D</a> <a href="index-5.html">E</a> <a href="index-6.html">F</a> <a href="index-7.html">G</a> <a href="index-8.html">H</a> <a href="index-9.html">I</a> <a href="index-10.html">K</a> <a href="index-11.html">L</a> <a href="index-12.html">M</a> <a href="index-13.html">N</a> <a href="index-14.html">O</a> <a href="index-15.html">P</a> <a href="index-16.html">R</a> <a href="index-17.html">S</a> <a href="index-18.html">T</a> <a href="index-19.html">V</a> <a href="index-20.html">W</a> <a href="index-21.html">_</a> <a name="_W_">
<!-- -->
</a>
<h2 class="title">W</h2>
<dl>
<dt><span class="strong"><a href="../BESA/Mobile/Message/BlockingMessageBPO.html#waitForACK(long)">waitForACK(long)</a></span> - Method in class BESA.Mobile.Message.<a href="../BESA/Mobile/Message/BlockingMessageBPO.html" title="class in BESA.Mobile.Message">BlockingMessageBPO</a></dt>
<dd> </dd>
<dt><span class="strong"><a href="../BESA/Mobile/Message/BlockingMessageBPO.html#waitForACK()">waitForACK()</a></span> - Method in class BESA.Mobile.Message.<a href="../BESA/Mobile/Message/BlockingMessageBPO.html" title="class in BESA.Mobile.Message">BlockingMessageBPO</a></dt>
<dd> </dd>
<dt><a href="../BESA/Mobile/ConnectionsAdministrator/WaitForSetupInfoBPO.html" title="class in BESA.Mobile.ConnectionsAdministrator"><span class="strong">WaitForSetupInfoBPO</span></a> - Class in <a href="../BESA/Mobile/ConnectionsAdministrator/package-summary.html">BESA.Mobile.ConnectionsAdministrator</a></dt>
<dd> </dd>
<dt><span class="strong"><a href="../BESA/Mobile/ConnectionsAdministrator/WaitForSetupInfoBPO.html#WaitForSetupInfoBPO(BESA.Mobile.CommunicationChannel.ICommunicationChannelBPO)">WaitForSetupInfoBPO(ICommunicationChannelBPO)</a></span> - Constructor for class BESA.Mobile.ConnectionsAdministrator.<a href="../BESA/Mobile/ConnectionsAdministrator/WaitForSetupInfoBPO.html" title="class in BESA.Mobile.ConnectionsAdministrator">WaitForSetupInfoBPO</a></dt>
<dd> </dd>
<dt><span class="strong"><a href="../BESA/Mobile/CommunicationChannel/BaseClasses/CommunicationChannelBPO.html#wakeUp()">wakeUp()</a></span> - Method in class BESA.Mobile.CommunicationChannel.BaseClasses.<a href="../BESA/Mobile/CommunicationChannel/BaseClasses/CommunicationChannelBPO.html" title="class in BESA.Mobile.CommunicationChannel.BaseClasses">CommunicationChannelBPO</a></dt>
<dd> </dd>
<dt><span class="strong"><a href="../BESA/Mobile/CommunicationChannel/BaseClasses/CommunicationChannelBPO.html#write(BESA.Mobile.Message.MessageBPO)">write(MessageBPO)</a></span> - Method in class BESA.Mobile.CommunicationChannel.BaseClasses.<a href="../BESA/Mobile/CommunicationChannel/BaseClasses/CommunicationChannelBPO.html" title="class in BESA.Mobile.CommunicationChannel.BaseClasses">CommunicationChannelBPO</a></dt>
<dd> </dd>
<dt><span class="strong"><a href="../BESA/Mobile/CommunicationChannel/ICommunicationChannelBPO.html#write(BESA.Mobile.Message.MessageBPO)">write(MessageBPO)</a></span> - Method in interface BESA.Mobile.CommunicationChannel.<a href="../BESA/Mobile/CommunicationChannel/ICommunicationChannelBPO.html" title="interface in BESA.Mobile.CommunicationChannel">ICommunicationChannelBPO</a></dt>
<dd> </dd>
<dt><span class="strong"><a href="../BESA/Mobile/CommunicationChannel/BaseClasses/CommunicationChannelBPO.html#writeObject(java.lang.Object)">writeObject(Object)</a></span> - Method in class BESA.Mobile.CommunicationChannel.BaseClasses.<a href="../BESA/Mobile/CommunicationChannel/BaseClasses/CommunicationChannelBPO.html" title="class in BESA.Mobile.CommunicationChannel.BaseClasses">CommunicationChannelBPO</a></dt>
<dd> </dd>
<dt><span class="strong"><a href="../BESA/Mobile/CommunicationChannel/Types/Socket/ClientSocketBPO.html#writeObject(java.lang.Object)">writeObject(Object)</a></span> - Method in class BESA.Mobile.CommunicationChannel.Types.Socket.<a href="../BESA/Mobile/CommunicationChannel/Types/Socket/ClientSocketBPO.html" title="class in BESA.Mobile.CommunicationChannel.Types.Socket">ClientSocketBPO</a></dt>
<dd> </dd>
</dl>
<a href="index-1.html">A</a> <a href="index-2.html">B</a> <a href="index-3.html">C</a> <a href="index-4.html">D</a> <a href="index-5.html">E</a> <a href="index-6.html">F</a> <a href="index-7.html">G</a> <a href="index-8.html">H</a> <a href="index-9.html">I</a> <a href="index-10.html">K</a> <a href="index-11.html">L</a> <a href="index-12.html">M</a> <a href="index-13.html">N</a> <a href="index-14.html">O</a> <a href="index-15.html">P</a> <a href="index-16.html">R</a> <a href="index-17.html">S</a> <a href="index-18.html">T</a> <a href="index-19.html">V</a> <a href="index-20.html">W</a> <a href="index-21.html">_</a> </div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../overview-summary.html">Overview</a></li>
<li>Package</li>
<li>Class</li>
<li>Use</li>
<li><a href="../overview-tree.html">Tree</a></li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li class="navBarCell1Rev">Index</li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="index-19.html">Prev Letter</a></li>
<li><a href="index-21.html">Next Letter</a></li>
</ul>
<ul class="navList">
<li><a href="../index.html?index-filesindex-20.html" target="_top">Frames</a></li>
<li><a href="index-20.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
|
Coregraph/Ayllu
|
JigSaw - AYPUY - CS/BESA3/BESA-DOC/jdoc/BPOBESA/index-files/index-20.html
|
HTML
|
mit
| 8,598 |
/*
|---------------------------------------------------------------------------------------------
| Extent jQuery Object
|---------------------------------------------------------------------------------------------
*/
$.extend({
dataTypeDropdown: function () {
return $().dataTypeDropdown(false);
}
});
/*
|---------------------------------------------------------------------------------------------
| Extent jQuery Functions
|---------------------------------------------------------------------------------------------
*/
$.fn.extend({
dataTypeDropdown: function (append = true) {
var options = dataTypeJson(), optionHTML = "";
window.optionHTML = "";
for (var i in options) {
if (i == 0) {
$.each(options[i], function (name, display) {
window.optionHTML += "<option value='" + name + "' >" + display + "</option>";
});
} else {
$.each(options[i], function (name, object) {
name = name.replace(/(\b\w)/gi, function (m) {
return m.toUpperCase();
});
window.optGroup = "<optgroup label=\"" + strReplaceAll(name, '-', ' ') + "\">";
$.each(object, function (name, display) {
window.optGroup += "<option value=\"" + name + "\">" + display + "</option>";
});
window.optGroup += "</optgroup>";
window.optionHTML += window.optGroup;
});
}
}
optionHTML = window.optionHTML;
delete window.optionHTML;
if (append === true) {
this.html(optionHTML);
} else {
return optionHTML;
}
}
});
/*
|---------------------------------------------------------------------------------------------
| Independent Functions
|---------------------------------------------------------------------------------------------
*/
function dataTypeJson(o = null) {
var dataTypes = [{
"int": "INT",
"varchar": "VARCHAR",
"text": "TEXT",
"date": "DATE"
}, {
'numeric': {
"tinyint": "TINYINT",
"smallint": "SMALLINT",
"mediumint": "MEDIUMINT",
"int": "INT",
"bigint": "BIGINT",
"decimal": "DECIMAL",
"float": "FLOAT",
"double": "DOUBLE",
"real": "REAL",
"bit": "BIT",
"boolean": "BOOLEAN",
"serial": "SERIAL"
}
}, {
"date-and-time": {
"date": "DATE",
"datetime": "DATETIME",
"timestamp": "TIMESTAMP",
"time": "TIME",
"year": "YEAR"
}
}, {
"string": {
"char": "CHAR",
"varchar": "VARCHAR",
"tinytext": "TINYTEXT",
"text": "TEXT",
"mediumtext": "MEDIUMTEXT",
"longtext": "LONGTEXT",
"binary": "BINARY",
"varbinary": "VARBINARY",
"tinyblob": "TINYBLOB",
"mediumblob": "MEDIUMBLOB",
"blob": "BLOB",
"longblob": "LONGBLOB",
"enum": "ENUM",
"set": "SET"
}
}, {
"spatial": {
"geometry": "GEOMETRY",
"point": "POINT",
"linestring": "LINESTRING",
"polygon": "POLYGON",
"multipoint": "MULTIPOINT",
"multilinestring": "MULTILINESTRING",
"multipolygon": "MULTIPOLYGON",
"geometrycollection": "GEOMETRYCOLLECTION"
}
}, {
"JSON": {
"json": "JSON"
}
}];
//add datatypes
dataTypes.push(o);
return dataTypes;
}
function dataTypeJsonAlt(o = null) {
var dataTypes = {
'numeric': {
"tinyint": "TINYINT",
"smallint": "SMALLINT",
"mediumint": "MEDIUMINT",
"int": "INT",
"bigint": "BIGINT",
"decimal": "DECIMAL",
"float": "FLOAT",
"double": "DOUBLE",
"real": "REAL",
"bit": "BIT",
"boolean": "BOOLEAN",
"serial": "SERIAL"
},
"date-and-time": {
"date": "DATE",
"datetime": "DATETIME",
"timestamp": "TIMESTAMP",
"time": "TIME",
"year": "YEAR"
},
"string": {
"char": "CHAR",
"varchar": "VARCHAR",
"tinytext": "TINYTEXT",
"text": "TEXT",
"mediumtext": "MEDIUMTEXT",
"longtext": "LONGTEXT",
"binary": "BINARY",
"varbinary": "VARBINARY",
"tinyblob": "TINYBLOB",
"mediumblob": "MEDIUMBLOB",
"blob": "BLOB",
"longblob": "LONGBLOB",
"enum": "ENUM",
"set": "SET"
},
"spatial": {
"geometry": "GEOMETRY",
"point": "POINT",
"linestring": "LINESTRING",
"polygon": "POLYGON",
"multipoint": "MULTIPOINT",
"multilinestring": "MULTILINESTRING",
"multipolygon": "MULTIPOLYGON",
"geometrycollection": "GEOMETRYCOLLECTION"
},
"JSON": {
"json": "JSON"
}
};
//add datatypes
dataTypes.push(o);
return dataTypes;
}
function strReplaceAll(string, Find, Replace) {
try {
return string.replace(new RegExp(Find, "gi"), Replace);
} catch (ex) {
return string;
}
}
function initSlimScroll() {
window.attempt = 1;
var timeInterval = setInterval(function () {
var height = {
contentWrapper: $(window).height() - ($('.navbar').outerHeight() + $('#footer').outerHeight()),
contentOutlet: $('.content-wrapper').innerHeight(),
outletContent: $('.content-outlet').prop('scrollHeight')
};
//$('.side-bar-left').height($('.content-wrapper').outerHeight());
$('.content-wrapper').css('height', height.contentWrapper + $('#footer').outerHeight());
$('.content-outlet').css('height', (height.contentWrapper));
// console.log(height);
if (window.attempt > 50) {
clearTimeout(timeInterval);
}
window.attempt++;
}, 10);
}
|
progitlabs/Ripple
|
public/js/functions.js
|
JavaScript
|
mit
| 6,477 |
<!-- Main content -->
<section class='content'>
<div class='row'>
<div class='col-xs-12'>
<div>
<div class='box-header'>
<h3 class='box-title'>
<?php
foreach ($judul as $joedoel) {
echo $joedoel->judul;
}
?>
</h3>
<h4>
<a href="<?= base_url('C_pasien/pesan_baru') ?>" class="btn btn-default">Buat Pesan</a>
<a href="<?= base_url('C_pasien/inbox') ?>" class="btn btn-default">Kotak Masuk</a>
<a href="<?= base_url('C_pasien/outbox') ?>" class="btn btn-default">Kotak Keluar</a>
<table class="table table-bordered">
<?php
$usern = $this->ion_auth->user()->row();
$user = $usern->email;
foreach ($baca as $pesan) {
?>
<tr>
<?php
if ($pesan->dari == $user) {
?>
<td align="right" colspan="2">
<div>
<b><?= $pesan->jam ?></b><br/>
<?= $pesan->dari ?><hr/>
<?= $pesan->pesan ?>
</div>
</td>
<?php
}else{
?>
<td colspan="2">
<div>
<b><?= $pesan->jam ?></b><br/>
<?= $pesan->dari ?><hr/>
<?= $pesan->pesan ?><hr/>
</div>
</td>
<?php
}
?>
</tr>
<?php
}
echo form_open('C_pasien/kirim_pesan');
?>
<input type="hidden" name="id_percakapan" value="<?= $this->uri->segment(3) ?>">
<tr>
<td><textarea type="text" name="pesan" class="form-control" required=""></textarea></td><td style="width: 150px; text-align: center;"><input type="submit" value="Balas" class="btn btn-primary"></td>
</tr>
</form>
</table>
</div><!-- /.box-body -->
</div><!-- /.box -->
</div><!-- /.col -->
</div><!-- /.row -->
</section><!-- /.content -->
|
smakkerz/la-derma
|
application/views/Pasien/c_pesan_baca.php
|
PHP
|
mit
| 2,257 |
/*
* Copyright (c) 2018.
*
* This file is part of AvaIre.
*
* AvaIre is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* AvaIre is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with AvaIre. If not, see <https://www.gnu.org/licenses/>.
*
*
*/
package com.avairebot.exceptions;
public class InvalidPluginsPathException extends Exception {
public InvalidPluginsPathException(String message) {
super(message);
}
}
|
AvaIre/AvaIre
|
src/main/java/com/avairebot/exceptions/InvalidPluginsPathException.java
|
Java
|
mit
| 890 |
route_namespace '/notices' do
condition do
restrict_to(:user)
end
get '/:type/new' do |type|
# was a notice already issued and another is requested?
redispatch = params[:redispatch]
@type = type # useful in the view
@redispatch = redispatch # useful in the view
case type
when "email"
if @user.email_verified?
return erb :"/emails/already_verified"
end
if redispatch
@user.notices.all({ type: 'email' }).destroy
else # no re-dispatch requested
# notice already sent and is pending?
if @user.awaiting_email_verification?
return erb :"/emails/already_dispatched"
end
end
unless @n = @user.verify_email
halt 500, "Unable to generate a verification link: #{@user.all_errors}"
end
dispatch_email_verification(@user) { |success, msg|
unless success
@user.notices.all({ type: 'email' }).destroy
halt 500, msg
end
}
when "password"
if redispatch
unless @n = @user.generate_temporary_password
halt 500, "Unable to generate temporary password: #{@user.all_errors}"
end
dispatch_temp_password(@user) { |success, msg|
unless success
@user.notices.all({ type: 'password' }).destroy
halt 500, msg
end
}
flash[:notice] = "Another temporary password message has been sent to your email."
end
else # an unknown type
halt 400, "Unrecognized verification parameter '#{type}'."
end
erb :"/emails/dispatched"
end
get '/:token/accept' do |token|
unless @n = @user.notices.first({ salt: token })
halt 400, "No such verification link."
end
case @n.status
when :expired
return erb :"emails/expired"
when :accepted
flash[:warning] = "This verification notice seems to have been accepted earlier."
return redirect "/settings/notifications"
else
@n.accept!
case @n.type
when 'email'
flash[:notice] = "Your email address '#{@n.user.email}' has been verified."
return redirect "/settings/account"
when 'password'
return redirect "/settings/account"
end
end
end
end # namespace['/notices']
|
amireh/pibi.legacy
|
controllers/notices.rb
|
Ruby
|
mit
| 2,309 |
// boost\math\distributions\non_central_chi_squared.hpp
// Copyright John Maddock 2008.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt
// or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_MATH_SPECIAL_NON_CENTRAL_CHI_SQUARE_HPP
#define BOOST_MATH_SPECIAL_NON_CENTRAL_CHI_SQUARE_HPP
#include <boost/math/distributions/fwd.hpp>
#include <boost/math/special_functions/gamma.hpp> // for incomplete gamma. gamma_q
#include <boost/math/special_functions/bessel.hpp> // for cyl_bessel_i
#include <boost/math/special_functions/round.hpp> // for iround
#include <boost/math/distributions/complement.hpp> // complements
#include <boost/math/distributions/chi_squared.hpp> // central distribution
#include <boost/math/distributions/detail/common_error_handling.hpp> // error checks
#include <boost/math/special_functions/fpclassify.hpp> // isnan.
#include <boost/math/tools/roots.hpp> // for root finding.
#include <boost/math/distributions/detail/generic_mode.hpp>
#include <boost/math/distributions/detail/generic_quantile.hpp>
namespace boost
{
namespace math
{
template <class RealType, class Policy>
class non_central_chi_squared_distribution;
namespace detail{
template <class T, class Policy>
T non_central_chi_square_q(T x, T f, T theta, const Policy& pol, T init_sum = 0)
{
//
// Computes the complement of the Non-Central Chi-Square
// Distribution CDF by summing a weighted sum of complements
// of the central-distributions. The weighting factor is
// a Poisson Distribution.
//
// This is an application of the technique described in:
//
// Computing discrete mixtures of continuous
// distributions: noncentral chisquare, noncentral t
// and the distribution of the square of the sample
// multiple correlation coefficient.
// D. Benton, K. Krishnamoorthy.
// Computational Statistics & Data Analysis 43 (2003) 249 - 267
//
BOOST_MATH_STD_USING
// Special case:
if(x == 0)
return 1;
//
// Initialize the variables we'll be using:
//
T lambda = theta / 2;
T del = f / 2;
T y = x / 2;
std::uintmax_t max_iter = policies::get_max_series_iterations<Policy>();
T errtol = boost::math::policies::get_epsilon<T, Policy>();
T sum = init_sum;
//
// k is the starting location for iteration, we'll
// move both forwards and backwards from this point.
// k is chosen as the peek of the Poisson weights, which
// will occur *before* the largest term.
//
int k = iround(lambda, pol);
// Forwards and backwards Poisson weights:
T poisf = boost::math::gamma_p_derivative(static_cast<T>(1 + k), lambda, pol);
T poisb = poisf * k / lambda;
// Initial forwards central chi squared term:
T gamf = boost::math::gamma_q(del + k, y, pol);
// Forwards and backwards recursion terms on the central chi squared:
T xtermf = boost::math::gamma_p_derivative(del + 1 + k, y, pol);
T xtermb = xtermf * (del + k) / y;
// Initial backwards central chi squared term:
T gamb = gamf - xtermb;
//
// Forwards iteration first, this is the
// stable direction for the gamma function
// recurrences:
//
int i;
for(i = k; static_cast<std::uintmax_t>(i-k) < max_iter; ++i)
{
T term = poisf * gamf;
sum += term;
poisf *= lambda / (i + 1);
gamf += xtermf;
xtermf *= y / (del + i + 1);
if(((sum == 0) || (fabs(term / sum) < errtol)) && (term >= poisf * gamf))
break;
}
//Error check:
if(static_cast<std::uintmax_t>(i-k) >= max_iter)
return policies::raise_evaluation_error(
"cdf(non_central_chi_squared_distribution<%1%>, %1%)",
"Series did not converge, closest value was %1%", sum, pol);
//
// Now backwards iteration: the gamma
// function recurrences are unstable in this
// direction, we rely on the terms diminishing in size
// faster than we introduce cancellation errors.
// For this reason it's very important that we start
// *before* the largest term so that backwards iteration
// is strictly converging.
//
for(i = k - 1; i >= 0; --i)
{
T term = poisb * gamb;
sum += term;
poisb *= i / lambda;
xtermb *= (del + i) / y;
gamb -= xtermb;
if((sum == 0) || (fabs(term / sum) < errtol))
break;
}
return sum;
}
template <class T, class Policy>
T non_central_chi_square_p_ding(T x, T f, T theta, const Policy& pol, T init_sum = 0)
{
//
// This is an implementation of:
//
// Algorithm AS 275:
// Computing the Non-Central #2 Distribution Function
// Cherng G. Ding
// Applied Statistics, Vol. 41, No. 2. (1992), pp. 478-482.
//
// This uses a stable forward iteration to sum the
// CDF, unfortunately this can not be used for large
// values of the non-centrality parameter because:
// * The first term may underflow to zero.
// * We may need an extra-ordinary number of terms
// before we reach the first *significant* term.
//
BOOST_MATH_STD_USING
// Special case:
if(x == 0)
return 0;
T tk = boost::math::gamma_p_derivative(f/2 + 1, x/2, pol);
T lambda = theta / 2;
T vk = exp(-lambda);
T uk = vk;
T sum = init_sum + tk * vk;
if(sum == 0)
return sum;
std::uintmax_t max_iter = policies::get_max_series_iterations<Policy>();
T errtol = boost::math::policies::get_epsilon<T, Policy>();
int i;
T lterm(0), term(0);
for(i = 1; static_cast<std::uintmax_t>(i) < max_iter; ++i)
{
tk = tk * x / (f + 2 * i);
uk = uk * lambda / i;
vk = vk + uk;
lterm = term;
term = vk * tk;
sum += term;
if((fabs(term / sum) < errtol) && (term <= lterm))
break;
}
//Error check:
if(static_cast<std::uintmax_t>(i) >= max_iter)
return policies::raise_evaluation_error(
"cdf(non_central_chi_squared_distribution<%1%>, %1%)",
"Series did not converge, closest value was %1%", sum, pol);
return sum;
}
template <class T, class Policy>
T non_central_chi_square_p(T y, T n, T lambda, const Policy& pol, T init_sum)
{
//
// This is taken more or less directly from:
//
// Computing discrete mixtures of continuous
// distributions: noncentral chisquare, noncentral t
// and the distribution of the square of the sample
// multiple correlation coefficient.
// D. Benton, K. Krishnamoorthy.
// Computational Statistics & Data Analysis 43 (2003) 249 - 267
//
// We're summing a Poisson weighting term multiplied by
// a central chi squared distribution.
//
BOOST_MATH_STD_USING
// Special case:
if(y == 0)
return 0;
std::uintmax_t max_iter = policies::get_max_series_iterations<Policy>();
T errtol = boost::math::policies::get_epsilon<T, Policy>();
T errorf(0), errorb(0);
T x = y / 2;
T del = lambda / 2;
//
// Starting location for the iteration, we'll iterate
// both forwards and backwards from this point. The
// location chosen is the maximum of the Poisson weight
// function, which ocurrs *after* the largest term in the
// sum.
//
int k = iround(del, pol);
T a = n / 2 + k;
// Central chi squared term for forward iteration:
T gamkf = boost::math::gamma_p(a, x, pol);
if(lambda == 0)
return gamkf;
// Central chi squared term for backward iteration:
T gamkb = gamkf;
// Forwards Poisson weight:
T poiskf = gamma_p_derivative(static_cast<T>(k+1), del, pol);
// Backwards Poisson weight:
T poiskb = poiskf;
// Forwards gamma function recursion term:
T xtermf = boost::math::gamma_p_derivative(a, x, pol);
// Backwards gamma function recursion term:
T xtermb = xtermf * x / a;
T sum = init_sum + poiskf * gamkf;
if(sum == 0)
return sum;
int i = 1;
//
// Backwards recursion first, this is the stable
// direction for gamma function recurrences:
//
while(i <= k)
{
xtermb *= (a - i + 1) / x;
gamkb += xtermb;
poiskb = poiskb * (k - i + 1) / del;
errorf = errorb;
errorb = gamkb * poiskb;
sum += errorb;
if((fabs(errorb / sum) < errtol) && (errorb <= errorf))
break;
++i;
}
i = 1;
//
// Now forwards recursion, the gamma function
// recurrence relation is unstable in this direction,
// so we rely on the magnitude of successive terms
// decreasing faster than we introduce cancellation error.
// For this reason it's vital that k is chosen to be *after*
// the largest term, so that successive forward iterations
// are strictly (and rapidly) converging.
//
do
{
xtermf = xtermf * x / (a + i - 1);
gamkf = gamkf - xtermf;
poiskf = poiskf * del / (k + i);
errorf = poiskf * gamkf;
sum += errorf;
++i;
}while((fabs(errorf / sum) > errtol) && (static_cast<std::uintmax_t>(i) < max_iter));
//Error check:
if(static_cast<std::uintmax_t>(i) >= max_iter)
return policies::raise_evaluation_error(
"cdf(non_central_chi_squared_distribution<%1%>, %1%)",
"Series did not converge, closest value was %1%", sum, pol);
return sum;
}
template <class T, class Policy>
T non_central_chi_square_pdf(T x, T n, T lambda, const Policy& pol)
{
//
// As above but for the PDF:
//
BOOST_MATH_STD_USING
std::uintmax_t max_iter = policies::get_max_series_iterations<Policy>();
T errtol = boost::math::policies::get_epsilon<T, Policy>();
T x2 = x / 2;
T n2 = n / 2;
T l2 = lambda / 2;
T sum = 0;
int k = itrunc(l2);
T pois = gamma_p_derivative(static_cast<T>(k + 1), l2, pol) * gamma_p_derivative(static_cast<T>(n2 + k), x2);
if(pois == 0)
return 0;
T poisb = pois;
for(int i = k; ; ++i)
{
sum += pois;
if(pois / sum < errtol)
break;
if(static_cast<std::uintmax_t>(i - k) >= max_iter)
return policies::raise_evaluation_error(
"pdf(non_central_chi_squared_distribution<%1%>, %1%)",
"Series did not converge, closest value was %1%", sum, pol);
pois *= l2 * x2 / ((i + 1) * (n2 + i));
}
for(int i = k - 1; i >= 0; --i)
{
poisb *= (i + 1) * (n2 + i) / (l2 * x2);
sum += poisb;
if(poisb / sum < errtol)
break;
}
return sum / 2;
}
template <class RealType, class Policy>
inline RealType non_central_chi_squared_cdf(RealType x, RealType k, RealType l, bool invert, const Policy&)
{
typedef typename policies::evaluation<RealType, Policy>::type value_type;
typedef typename policies::normalise<
Policy,
policies::promote_float<false>,
policies::promote_double<false>,
policies::discrete_quantile<>,
policies::assert_undefined<> >::type forwarding_policy;
BOOST_MATH_STD_USING
value_type result;
if(l == 0)
return invert == false ? cdf(boost::math::chi_squared_distribution<RealType, Policy>(k), x) : cdf(complement(boost::math::chi_squared_distribution<RealType, Policy>(k), x));
else if(x > k + l)
{
// Complement is the smaller of the two:
result = detail::non_central_chi_square_q(
static_cast<value_type>(x),
static_cast<value_type>(k),
static_cast<value_type>(l),
forwarding_policy(),
static_cast<value_type>(invert ? 0 : -1));
invert = !invert;
}
else if(l < 200)
{
// For small values of the non-centrality parameter
// we can use Ding's method:
result = detail::non_central_chi_square_p_ding(
static_cast<value_type>(x),
static_cast<value_type>(k),
static_cast<value_type>(l),
forwarding_policy(),
static_cast<value_type>(invert ? -1 : 0));
}
else
{
// For largers values of the non-centrality
// parameter Ding's method will consume an
// extra-ordinary number of terms, and worse
// may return zero when the result is in fact
// finite, use Krishnamoorthy's method instead:
result = detail::non_central_chi_square_p(
static_cast<value_type>(x),
static_cast<value_type>(k),
static_cast<value_type>(l),
forwarding_policy(),
static_cast<value_type>(invert ? -1 : 0));
}
if(invert)
result = -result;
return policies::checked_narrowing_cast<RealType, forwarding_policy>(
result,
"boost::math::non_central_chi_squared_cdf<%1%>(%1%, %1%, %1%)");
}
template <class T, class Policy>
struct nccs_quantile_functor
{
nccs_quantile_functor(const non_central_chi_squared_distribution<T,Policy>& d, T t, bool c)
: dist(d), target(t), comp(c) {}
T operator()(const T& x)
{
return comp ?
target - cdf(complement(dist, x))
: cdf(dist, x) - target;
}
private:
non_central_chi_squared_distribution<T,Policy> dist;
T target;
bool comp;
};
template <class RealType, class Policy>
RealType nccs_quantile(const non_central_chi_squared_distribution<RealType, Policy>& dist, const RealType& p, bool comp)
{
BOOST_MATH_STD_USING
static const char* function = "quantile(non_central_chi_squared_distribution<%1%>, %1%)";
typedef typename policies::evaluation<RealType, Policy>::type value_type;
typedef typename policies::normalise<
Policy,
policies::promote_float<false>,
policies::promote_double<false>,
policies::discrete_quantile<>,
policies::assert_undefined<> >::type forwarding_policy;
value_type k = dist.degrees_of_freedom();
value_type l = dist.non_centrality();
value_type r;
if(!detail::check_df(
function,
k, &r, Policy())
||
!detail::check_non_centrality(
function,
l,
&r,
Policy())
||
!detail::check_probability(
function,
static_cast<value_type>(p),
&r,
Policy()))
return (RealType)r;
//
// Special cases get short-circuited first:
//
if(p == 0)
return comp ? policies::raise_overflow_error<RealType>(function, 0, Policy()) : 0;
if(p == 1)
return comp ? 0 : policies::raise_overflow_error<RealType>(function, 0, Policy());
//
// This is Pearson's approximation to the quantile, see
// Pearson, E. S. (1959) "Note on an approximation to the distribution of
// noncentral chi squared", Biometrika 46: 364.
// See also:
// "A comparison of approximations to percentiles of the noncentral chi2-distribution",
// Hardeo Sahai and Mario Miguel Ojeda, Revista de Matematica: Teoria y Aplicaciones 2003 10(1-2) : 57-76.
// Note that the latter reference refers to an approximation of the CDF, when they really mean the quantile.
//
value_type b = -(l * l) / (k + 3 * l);
value_type c = (k + 3 * l) / (k + 2 * l);
value_type ff = (k + 2 * l) / (c * c);
value_type guess;
if(comp)
{
guess = b + c * quantile(complement(chi_squared_distribution<value_type, forwarding_policy>(ff), p));
}
else
{
guess = b + c * quantile(chi_squared_distribution<value_type, forwarding_policy>(ff), p);
}
//
// Sometimes guess goes very small or negative, in that case we have
// to do something else for the initial guess, this approximation
// was provided in a private communication from Thomas Luu, PhD candidate,
// University College London. It's an asymptotic expansion for the
// quantile which usually gets us within an order of magnitude of the
// correct answer.
// Fast and accurate parallel computation of quantile functions for random number generation,
// Thomas LuuDoctorial Thesis 2016
// http://discovery.ucl.ac.uk/1482128/
//
if(guess < 0.005)
{
value_type pp = comp ? 1 - p : p;
//guess = pow(pow(value_type(2), (k / 2 - 1)) * exp(l / 2) * pp * k, 2 / k);
guess = pow(pow(value_type(2), (k / 2 - 1)) * exp(l / 2) * pp * k * boost::math::tgamma(k / 2, forwarding_policy()), (2 / k));
if(guess == 0)
guess = tools::min_value<value_type>();
}
value_type result = detail::generic_quantile(
non_central_chi_squared_distribution<value_type, forwarding_policy>(k, l),
p,
guess,
comp,
function);
return policies::checked_narrowing_cast<RealType, forwarding_policy>(
result,
function);
}
template <class RealType, class Policy>
RealType nccs_pdf(const non_central_chi_squared_distribution<RealType, Policy>& dist, const RealType& x)
{
BOOST_MATH_STD_USING
static const char* function = "pdf(non_central_chi_squared_distribution<%1%>, %1%)";
typedef typename policies::evaluation<RealType, Policy>::type value_type;
typedef typename policies::normalise<
Policy,
policies::promote_float<false>,
policies::promote_double<false>,
policies::discrete_quantile<>,
policies::assert_undefined<> >::type forwarding_policy;
value_type k = dist.degrees_of_freedom();
value_type l = dist.non_centrality();
value_type r;
if(!detail::check_df(
function,
k, &r, Policy())
||
!detail::check_non_centrality(
function,
l,
&r,
Policy())
||
!detail::check_positive_x(
function,
(value_type)x,
&r,
Policy()))
return (RealType)r;
if(l == 0)
return pdf(boost::math::chi_squared_distribution<RealType, forwarding_policy>(dist.degrees_of_freedom()), x);
// Special case:
if(x == 0)
return 0;
if(l > 50)
{
r = non_central_chi_square_pdf(static_cast<value_type>(x), k, l, forwarding_policy());
}
else
{
r = log(x / l) * (k / 4 - 0.5f) - (x + l) / 2;
if(fabs(r) >= tools::log_max_value<RealType>() / 4)
{
r = non_central_chi_square_pdf(static_cast<value_type>(x), k, l, forwarding_policy());
}
else
{
r = exp(r);
r = 0.5f * r
* boost::math::cyl_bessel_i(k/2 - 1, sqrt(l * x), forwarding_policy());
}
}
return policies::checked_narrowing_cast<RealType, forwarding_policy>(
r,
function);
}
template <class RealType, class Policy>
struct degrees_of_freedom_finder
{
degrees_of_freedom_finder(
RealType lam_, RealType x_, RealType p_, bool c)
: lam(lam_), x(x_), p(p_), comp(c) {}
RealType operator()(const RealType& v)
{
non_central_chi_squared_distribution<RealType, Policy> d(v, lam);
return comp ?
RealType(p - cdf(complement(d, x)))
: RealType(cdf(d, x) - p);
}
private:
RealType lam;
RealType x;
RealType p;
bool comp;
};
template <class RealType, class Policy>
inline RealType find_degrees_of_freedom(
RealType lam, RealType x, RealType p, RealType q, const Policy& pol)
{
const char* function = "non_central_chi_squared<%1%>::find_degrees_of_freedom";
if((p == 0) || (q == 0))
{
//
// Can't a thing if one of p and q is zero:
//
return policies::raise_evaluation_error<RealType>(function,
"Can't find degrees of freedom when the probability is 0 or 1, only possible answer is %1%",
RealType(std::numeric_limits<RealType>::quiet_NaN()), Policy());
}
degrees_of_freedom_finder<RealType, Policy> f(lam, x, p < q ? p : q, p < q ? false : true);
tools::eps_tolerance<RealType> tol(policies::digits<RealType, Policy>());
std::uintmax_t max_iter = policies::get_max_root_iterations<Policy>();
//
// Pick an initial guess that we know will give us a probability
// right around 0.5.
//
RealType guess = x - lam;
if(guess < 1)
guess = 1;
std::pair<RealType, RealType> ir = tools::bracket_and_solve_root(
f, guess, RealType(2), false, tol, max_iter, pol);
RealType result = ir.first + (ir.second - ir.first) / 2;
if(max_iter >= policies::get_max_root_iterations<Policy>())
{
return policies::raise_evaluation_error<RealType>(function, "Unable to locate solution in a reasonable time:"
" or there is no answer to problem. Current best guess is %1%", result, Policy());
}
return result;
}
template <class RealType, class Policy>
struct non_centrality_finder
{
non_centrality_finder(
RealType v_, RealType x_, RealType p_, bool c)
: v(v_), x(x_), p(p_), comp(c) {}
RealType operator()(const RealType& lam)
{
non_central_chi_squared_distribution<RealType, Policy> d(v, lam);
return comp ?
RealType(p - cdf(complement(d, x)))
: RealType(cdf(d, x) - p);
}
private:
RealType v;
RealType x;
RealType p;
bool comp;
};
template <class RealType, class Policy>
inline RealType find_non_centrality(
RealType v, RealType x, RealType p, RealType q, const Policy& pol)
{
const char* function = "non_central_chi_squared<%1%>::find_non_centrality";
if((p == 0) || (q == 0))
{
//
// Can't do a thing if one of p and q is zero:
//
return policies::raise_evaluation_error<RealType>(function,
"Can't find non centrality parameter when the probability is 0 or 1, only possible answer is %1%",
RealType(std::numeric_limits<RealType>::quiet_NaN()), Policy());
}
non_centrality_finder<RealType, Policy> f(v, x, p < q ? p : q, p < q ? false : true);
tools::eps_tolerance<RealType> tol(policies::digits<RealType, Policy>());
std::uintmax_t max_iter = policies::get_max_root_iterations<Policy>();
//
// Pick an initial guess that we know will give us a probability
// right around 0.5.
//
RealType guess = x - v;
if(guess < 1)
guess = 1;
std::pair<RealType, RealType> ir = tools::bracket_and_solve_root(
f, guess, RealType(2), false, tol, max_iter, pol);
RealType result = ir.first + (ir.second - ir.first) / 2;
if(max_iter >= policies::get_max_root_iterations<Policy>())
{
return policies::raise_evaluation_error<RealType>(function, "Unable to locate solution in a reasonable time:"
" or there is no answer to problem. Current best guess is %1%", result, Policy());
}
return result;
}
}
template <class RealType = double, class Policy = policies::policy<> >
class non_central_chi_squared_distribution
{
public:
typedef RealType value_type;
typedef Policy policy_type;
non_central_chi_squared_distribution(RealType df_, RealType lambda) : df(df_), ncp(lambda)
{
const char* function = "boost::math::non_central_chi_squared_distribution<%1%>::non_central_chi_squared_distribution(%1%,%1%)";
RealType r;
detail::check_df(
function,
df, &r, Policy());
detail::check_non_centrality(
function,
ncp,
&r,
Policy());
} // non_central_chi_squared_distribution constructor.
RealType degrees_of_freedom() const
{ // Private data getter function.
return df;
}
RealType non_centrality() const
{ // Private data getter function.
return ncp;
}
static RealType find_degrees_of_freedom(RealType lam, RealType x, RealType p)
{
const char* function = "non_central_chi_squared<%1%>::find_degrees_of_freedom";
typedef typename policies::evaluation<RealType, Policy>::type eval_type;
typedef typename policies::normalise<
Policy,
policies::promote_float<false>,
policies::promote_double<false>,
policies::discrete_quantile<>,
policies::assert_undefined<> >::type forwarding_policy;
eval_type result = detail::find_degrees_of_freedom(
static_cast<eval_type>(lam),
static_cast<eval_type>(x),
static_cast<eval_type>(p),
static_cast<eval_type>(1-p),
forwarding_policy());
return policies::checked_narrowing_cast<RealType, forwarding_policy>(
result,
function);
}
template <class A, class B, class C>
static RealType find_degrees_of_freedom(const complemented3_type<A,B,C>& c)
{
const char* function = "non_central_chi_squared<%1%>::find_degrees_of_freedom";
typedef typename policies::evaluation<RealType, Policy>::type eval_type;
typedef typename policies::normalise<
Policy,
policies::promote_float<false>,
policies::promote_double<false>,
policies::discrete_quantile<>,
policies::assert_undefined<> >::type forwarding_policy;
eval_type result = detail::find_degrees_of_freedom(
static_cast<eval_type>(c.dist),
static_cast<eval_type>(c.param1),
static_cast<eval_type>(1-c.param2),
static_cast<eval_type>(c.param2),
forwarding_policy());
return policies::checked_narrowing_cast<RealType, forwarding_policy>(
result,
function);
}
static RealType find_non_centrality(RealType v, RealType x, RealType p)
{
const char* function = "non_central_chi_squared<%1%>::find_non_centrality";
typedef typename policies::evaluation<RealType, Policy>::type eval_type;
typedef typename policies::normalise<
Policy,
policies::promote_float<false>,
policies::promote_double<false>,
policies::discrete_quantile<>,
policies::assert_undefined<> >::type forwarding_policy;
eval_type result = detail::find_non_centrality(
static_cast<eval_type>(v),
static_cast<eval_type>(x),
static_cast<eval_type>(p),
static_cast<eval_type>(1-p),
forwarding_policy());
return policies::checked_narrowing_cast<RealType, forwarding_policy>(
result,
function);
}
template <class A, class B, class C>
static RealType find_non_centrality(const complemented3_type<A,B,C>& c)
{
const char* function = "non_central_chi_squared<%1%>::find_non_centrality";
typedef typename policies::evaluation<RealType, Policy>::type eval_type;
typedef typename policies::normalise<
Policy,
policies::promote_float<false>,
policies::promote_double<false>,
policies::discrete_quantile<>,
policies::assert_undefined<> >::type forwarding_policy;
eval_type result = detail::find_non_centrality(
static_cast<eval_type>(c.dist),
static_cast<eval_type>(c.param1),
static_cast<eval_type>(1-c.param2),
static_cast<eval_type>(c.param2),
forwarding_policy());
return policies::checked_narrowing_cast<RealType, forwarding_policy>(
result,
function);
}
private:
// Data member, initialized by constructor.
RealType df; // degrees of freedom.
RealType ncp; // non-centrality parameter
}; // template <class RealType, class Policy> class non_central_chi_squared_distribution
typedef non_central_chi_squared_distribution<double> non_central_chi_squared; // Reserved name of type double.
// Non-member functions to give properties of the distribution.
template <class RealType, class Policy>
inline const std::pair<RealType, RealType> range(const non_central_chi_squared_distribution<RealType, Policy>& /* dist */)
{ // Range of permissible values for random variable k.
using boost::math::tools::max_value;
return std::pair<RealType, RealType>(static_cast<RealType>(0), max_value<RealType>()); // Max integer?
}
template <class RealType, class Policy>
inline const std::pair<RealType, RealType> support(const non_central_chi_squared_distribution<RealType, Policy>& /* dist */)
{ // Range of supported values for random variable k.
// This is range where cdf rises from 0 to 1, and outside it, the pdf is zero.
using boost::math::tools::max_value;
return std::pair<RealType, RealType>(static_cast<RealType>(0), max_value<RealType>());
}
template <class RealType, class Policy>
inline RealType mean(const non_central_chi_squared_distribution<RealType, Policy>& dist)
{ // Mean of poisson distribution = lambda.
const char* function = "boost::math::non_central_chi_squared_distribution<%1%>::mean()";
RealType k = dist.degrees_of_freedom();
RealType l = dist.non_centrality();
RealType r;
if(!detail::check_df(
function,
k, &r, Policy())
||
!detail::check_non_centrality(
function,
l,
&r,
Policy()))
return r;
return k + l;
} // mean
template <class RealType, class Policy>
inline RealType mode(const non_central_chi_squared_distribution<RealType, Policy>& dist)
{ // mode.
static const char* function = "mode(non_central_chi_squared_distribution<%1%> const&)";
RealType k = dist.degrees_of_freedom();
RealType l = dist.non_centrality();
RealType r;
if(!detail::check_df(
function,
k, &r, Policy())
||
!detail::check_non_centrality(
function,
l,
&r,
Policy()))
return (RealType)r;
return detail::generic_find_mode(dist, 1 + k, function);
}
template <class RealType, class Policy>
inline RealType variance(const non_central_chi_squared_distribution<RealType, Policy>& dist)
{ // variance.
const char* function = "boost::math::non_central_chi_squared_distribution<%1%>::variance()";
RealType k = dist.degrees_of_freedom();
RealType l = dist.non_centrality();
RealType r;
if(!detail::check_df(
function,
k, &r, Policy())
||
!detail::check_non_centrality(
function,
l,
&r,
Policy()))
return r;
return 2 * (2 * l + k);
}
// RealType standard_deviation(const non_central_chi_squared_distribution<RealType, Policy>& dist)
// standard_deviation provided by derived accessors.
template <class RealType, class Policy>
inline RealType skewness(const non_central_chi_squared_distribution<RealType, Policy>& dist)
{ // skewness = sqrt(l).
const char* function = "boost::math::non_central_chi_squared_distribution<%1%>::skewness()";
RealType k = dist.degrees_of_freedom();
RealType l = dist.non_centrality();
RealType r;
if(!detail::check_df(
function,
k, &r, Policy())
||
!detail::check_non_centrality(
function,
l,
&r,
Policy()))
return r;
BOOST_MATH_STD_USING
return pow(2 / (k + 2 * l), RealType(3)/2) * (k + 3 * l);
}
template <class RealType, class Policy>
inline RealType kurtosis_excess(const non_central_chi_squared_distribution<RealType, Policy>& dist)
{
const char* function = "boost::math::non_central_chi_squared_distribution<%1%>::kurtosis_excess()";
RealType k = dist.degrees_of_freedom();
RealType l = dist.non_centrality();
RealType r;
if(!detail::check_df(
function,
k, &r, Policy())
||
!detail::check_non_centrality(
function,
l,
&r,
Policy()))
return r;
return 12 * (k + 4 * l) / ((k + 2 * l) * (k + 2 * l));
} // kurtosis_excess
template <class RealType, class Policy>
inline RealType kurtosis(const non_central_chi_squared_distribution<RealType, Policy>& dist)
{
return kurtosis_excess(dist) + 3;
}
template <class RealType, class Policy>
inline RealType pdf(const non_central_chi_squared_distribution<RealType, Policy>& dist, const RealType& x)
{ // Probability Density/Mass Function.
return detail::nccs_pdf(dist, x);
} // pdf
template <class RealType, class Policy>
RealType cdf(const non_central_chi_squared_distribution<RealType, Policy>& dist, const RealType& x)
{
const char* function = "boost::math::non_central_chi_squared_distribution<%1%>::cdf(%1%)";
RealType k = dist.degrees_of_freedom();
RealType l = dist.non_centrality();
RealType r;
if(!detail::check_df(
function,
k, &r, Policy())
||
!detail::check_non_centrality(
function,
l,
&r,
Policy())
||
!detail::check_positive_x(
function,
x,
&r,
Policy()))
return r;
return detail::non_central_chi_squared_cdf(x, k, l, false, Policy());
} // cdf
template <class RealType, class Policy>
RealType cdf(const complemented2_type<non_central_chi_squared_distribution<RealType, Policy>, RealType>& c)
{ // Complemented Cumulative Distribution Function
const char* function = "boost::math::non_central_chi_squared_distribution<%1%>::cdf(%1%)";
non_central_chi_squared_distribution<RealType, Policy> const& dist = c.dist;
RealType x = c.param;
RealType k = dist.degrees_of_freedom();
RealType l = dist.non_centrality();
RealType r;
if(!detail::check_df(
function,
k, &r, Policy())
||
!detail::check_non_centrality(
function,
l,
&r,
Policy())
||
!detail::check_positive_x(
function,
x,
&r,
Policy()))
return r;
return detail::non_central_chi_squared_cdf(x, k, l, true, Policy());
} // ccdf
template <class RealType, class Policy>
inline RealType quantile(const non_central_chi_squared_distribution<RealType, Policy>& dist, const RealType& p)
{ // Quantile (or Percent Point) function.
return detail::nccs_quantile(dist, p, false);
} // quantile
template <class RealType, class Policy>
inline RealType quantile(const complemented2_type<non_central_chi_squared_distribution<RealType, Policy>, RealType>& c)
{ // Quantile (or Percent Point) function.
return detail::nccs_quantile(c.dist, c.param, true);
} // quantile complement.
} // namespace math
} // namespace boost
// This include must be at the end, *after* the accessors
// for this distribution have been defined, in order to
// keep compilers that support two-phase lookup happy.
#include <boost/math/distributions/detail/derived_accessors.hpp>
#endif // BOOST_MATH_SPECIAL_NON_CENTRAL_CHI_SQUARE_HPP
|
satya-das/common
|
third_party/boost_tp/boost/math/distributions/non_central_chi_squared.hpp
|
C++
|
mit
| 40,678 |
<!DOCTYPE html>
<html lang="en">
<head>
<title>Notebook.md</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Buttons/2.0.0/css/buttons.css" />
<link href="../lib/css/font-awesome.min.css" rel="stylesheet">
<link href="./index.css" rel="stylesheet">
</head>
<body>
<div class="container-fluid">
<div class="row" id="main">
<div class="col-sm-3 nav">
<router-link class="button button-block" to="/home" exact>HOME</router-link>
<router-link class="button button-block" to="/news" exact>NEWS</router-link>
<router-link class="button button-block" to="/about" exact>ABOUT</router-link>
</div>
<div class="col-sm-7">
<h1>Hello Vue</h1>
<router-view></router-view>
</div>
</div>
</div>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.4/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-router/2.3.0/vue-router.js"></script>
<script src="./index.js"></script>
<script src="./router.js"></script>
</html>
|
PCWMXPY/Notebook.md
|
storage/main/index.html
|
HTML
|
mit
| 1,342 |
using UnityEngine;
namespace Expanse.Motion
{
/// <summary>
/// Motion that moves a Color towards a target value.
/// </summary>
public class ColorMotion : ValueMotion<Color>
{
public ColorMotion() : base(1, null, null) { }
public ColorMotion(float duration) : base(duration, null, null) { }
public ColorMotion(float duration, CallBackRelay cbr) : base(duration, cbr, null) { }
public ColorMotion(float duration, MonoBehaviour attachedMonobehaviour) : base(duration, null, attachedMonobehaviour) { }
public ColorMotion(float duration, CallBackRelay cbr, MonoBehaviour attachedMonobehaviour) : base(duration, cbr, attachedMonobehaviour) { }
protected override void OnProgressChanged()
{
CurrentValue = Color.LerpUnclamped(StartValue, TargetValue, ValueProgress);
}
}
}
|
AikenParker/Expanse
|
Motion/ValueMotion/ColorMotion.cs
|
C#
|
mit
| 873 |
package ru.atom.thread.mm;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
/**
* Created by sergey on 3/14/17.
*/
public class ThreadSafeQueue {
private static BlockingQueue<Connection> instance = new LinkedBlockingQueue<>();
public static BlockingQueue<Connection> getInstance() {
return instance;
}
}
|
elBroom/atom
|
lecture05/src/main/java/ru/atom/thread/mm/ThreadSafeQueue.java
|
Java
|
mit
| 372 |
// This is Generated Source.
import MeetingServiceInfoResource from "../definitions/MeetingServiceInfoResource";
import PathSegment from "../PathSegment";
export default class ServiceInfo extends PathSegment {
constructor(prv: PathSegment, id?: string, service?) {
super("service-info", id, prv, service);
}
/**
*
*/
get(): Promise<MeetingServiceInfoResource> {
return this._send({
body: undefined,
ignoreId: true,
method: "get",
query: undefined,
}).then((res) => {
return res.json();
});
}
/**
*
* return {ApiResponse}
*/
getRaw(): Promise<any> {
return this._send({
body: undefined,
ignoreId: true,
method: "get",
query: undefined,
});
}
}
|
zengfenfei/ringcentral-js-client
|
src/paths/ServiceInfo.ts
|
TypeScript
|
mit
| 868 |
/****
Author: Christian Moist
Copyright 2009 MCM Electronics
****/
input.submit, input.submit-grn {padding: 2px 4px;}
a {color: #3d3d3d;}
/**** layout styles ****/
#header #search-bar {background: transparent url('/images/v4/ie/bar-sprite.gif') no-repeat 0 0; border: none; padding-top: 16px; padding-bottom: 12px;}
#header #search-bar-mini {background: transparent url('/images/v4/ie/bar-sprite.gif') no-repeat 0 -52px; border: none; padding-top: 16px; padding-bottom: 12px; padding-right: 2px; width: 677px;}
#footer #footer-head {background: transparent url('/images/v4/ie/bar-sprite.gif') no-repeat 0 -174px; border: none; height: 29px;}
.body .header-bg {background: transparent url('/images/v4/ie/bar-sprite.gif') no-repeat 0 -104px;}
#product-page #info-column #img-desc {background-image: none; border-bottom: 1px solid #CCC;}
.attribute-bar {zoom: 1;}
.attribute-bar div,
.attribute-bar h2 {position: relative;}
#header #account {width: 300px;}
#header #head-promo {width: 384px; float: left;}
#header #head-promo a {margin: 0 auto;}
#basket-page #source-code input {max-width: 70%;}
#basket-page #source-code input.submit {max-width: 30%;}
/**** loader styles ****/
#loader {filter: alpha(opacity=25);}
/* Print Styles */
@media print {
.print {display: block !important;}
}
|
urbanspectra-nyc/nycsys
|
compare-systems/css/v4/styles-ie.css
|
CSS
|
mit
| 1,848 |
/**
import Promise from 'promise';
export default function() {
var promise = new Promise(function (resolve, reject) {
resolve(true);
});
return promise;
};
**/
export default null;
|
z5internet/ruf
|
src/resources/assets/react-app/uiHooks/addNewTeamMember.js
|
JavaScript
|
mit
| 195 |
/* browserify task
---------------
Bundle javascripty things with browserify!
This task is set up to generate multiple separate bundles, from
different sources, and to use Watchify when run from the default task.
See browserify.bundleConfigs in gulp/config.js
*/
var browserify = require('browserify');
var watchify = require('watchify');
var bundleLogger = require('../util/bundleLogger');
var gulp = require('gulp');
var handleErrors = require('../util/handleErrors');
var source = require('vinyl-source-stream');
var config = require('../config').browserify;
var buffer = require('vinyl-buffer');
var sourcemaps = require('gulp-sourcemaps');
var babelify = require('babelify');
gulp.task('browserify', ['jshint'], function(callback) {
var bundleQueue = config.bundleConfigs.length;
var browserifyThis = function(bundleConfig) {
var bundler = browserify({
// Required watchify args
cache: {}, packageCache: {}, fullPaths: false,
// Specify the entry point of your app
entries: bundleConfig.entries,
// Add file extentions to make optional in your requires
extensions: config.extensions,
// Enable source maps, since they are only loaded on demand there is no need to disable
debug: true
}).transform(babelify.configure({stage: 1}));
var bundle = function() {
// Log when bundling starts
bundleLogger.start(bundleConfig.outputName);
return bundler
.bundle()
// Report compile errors
.on('error', handleErrors)
// Use vinyl-source-stream to make the
// stream gulp compatible. Specifiy the
// desired output filename here.
.pipe(source(bundleConfig.outputName))
.pipe(buffer())
// Create independent source map file in the build directory
.pipe(sourcemaps.init({loadMaps: true}))
.pipe(sourcemaps.write('./'))
// Specify the output destination
.pipe(gulp.dest(bundleConfig.dest))
.on('end', reportFinished);
};
if(global.isWatching) {
// Wrap with watchify and rebundle on changes
bundler = watchify(bundler);
// Rebundle on update
bundler.on('update', bundle);
}
var reportFinished = function() {
// Log when bundling completes
bundleLogger.end(bundleConfig.outputName);
if(bundleQueue) {
bundleQueue--;
if(bundleQueue === 0) {
// If queue is empty, tell gulp the task is complete.
// https://github.com/gulpjs/gulp/blob/master/docs/API.md#accept-a-callback
callback();
}
}
};
return bundle();
};
// Start bundling with Browserify for each bundleConfig specified
config.bundleConfigs.forEach(browserifyThis);
});
|
b4456609/pet-new
|
docs/gulp/tasks/browserify.js
|
JavaScript
|
mit
| 2,806 |
# purescript-d3v4
## From the ground up re-implementation of purescript-d3
### Key points:
* same DSL approach as @pelotom's original, but...
* ...fewer typeclasses (so far)
* latest version of D3, ie v4
* ADTs for the polymorphic parameter types with resulting explicit representation in the DSL
* purescript-eff-functions to wrap all the underlying calls (instead of easy-ffi)
### Installing and running examples
*(prerequisites assumed: `node`, `npm`, `purescript`)*
Clone repo `https://github.com/afcondon/purescript-d3v4.git` and `cd` into the install directory
```
$ npm install
$ bower install
$ npm run build
```
From here you can build any demo you wish in the form `$ npm run example-{demo_name}`, such as
```
$ npm run example-fivecircles
$ npm run example-gupIII
$ npm run example-barchart
$ npm run example-forcelayout
$ npm run example-default
```
If you serve http from the install directory - as for example...
```
$ python -m SimpleHTTPServer
```
...you should be able to see all five of these simple demos run now from the simple demo page at `[install_dir]/index.html`
### Some resources about visualization generally...
All of Edward Tufte's books are essential but [this](https://www.amazon.com/Envisioning-Information-Edward-R-Tufte/dp/0961392118) is maybe a good one to start with in this context.
Very nice [book](https://www.amazon.com/Book-Trees-Visualizing-Branches-Knowledge/dp/1616892188) by Manuel Lima about the ubiquitous tree diagram, all the way back to Ramon Llull in 13thC. [Visual Complexity](https://www.amazon.com/Visual-Complexity-Mapping-Patterns-Information/dp/1616892196) by the same author is also great and perhaps even more relevant to some of the kinds of uses i anticipate for purescript-d3v4
Comprehensive overview / [introduction](https://www.amazon.com/Visualization-Analysis-Design-Peters-Series/dp/1466508914) to data visualization by the great Tamara Munzner.
![Envisioning Information cover image][1]
![The Book of Trees][2]
![Visual Complexity][3]
![Visualization Analysis][4]
[1]: ./images/EI.jpg
[2]: ./images/BoT.jpg
[3]: ./images/VC.jpg
[4]: ./images/VAaD.jpg
### ...and D3 specifically
[General Update Pattern:](http://bl.ocks.org/mbostock/3808234)
[How Selections Work (as it was in d3v3)](https://bost.ocks.org/mike/selection/)
[Irene Ros D3v4 -What’s New?](https://iros.github.io/d3-v4-whats-new/)
[Simpson's Paradox](http://vudlab.com/simpsons/) illustrated and explained using a variety of D3 ideas to very good effect.
$ubscription video course (no affiliation) on D3 with excellent free newsletter: [DashingD3](https://www.dashingd3js.com)
### Further thoughts
D3 encodes a _wealth_ of domain specific information about data visualization that is the fruit of both creator Mike Bostock's previous visualization libraries and, also, the extraordinarily rich eco-system of users that it has accumulated.
It presents an interface and documentation of such depth that even JavaScript neophytes or, in some cases, non-programmers can take it and produce the graphics and even animations or interactive visualizations that they require.
By being very largely decoupled from the actual presentation technology of HTML DOM / SVG / Canvas etc it both enables users to very often defer learning those technologies and enables people with expertise in those technologies to work with visualizations without learning very much if anything about D3.
In essence, D3 presents a Domain Specific Language (DSL) embedded in JavaScript for the creation of visualizations. Functional programming languages such as Haskell and Purescript, are ideally suited to the creation of DSLs and [purescript-d3](https://github.com/pelotom/purescript-d3) by [Tom Crockett](https://github.com/pelotom) demonstrated how with a couple of operator aliases and wrappers for D3 functions one could very nearly replicate the form of the JavaScript "DSL" that is D3 in Purescript.
### Objectives
This repo is attempting to find a balance between the following objectives (*NB* the first two are certainly in tension with one another to some extent):
1. define a DSL in Purescript that is so close to the JavaScript D3 style that one can read and perhaps write it without resorting to reference material
2. leverage the undoubted advantages of strong static typing and immutability to make it easier to program by making invalid programs harder to express and error values such as undefined and null explicit
3. a third objective is to ensure that this repo sits well within the Purescript library ecosystem, eschewing redundant definitions of, for example DOM, Events, Dates etc and sitting nicely within web apps built using Pux, Thermite, Halogen etc.˛
4. a fourth objective is to make explicit much of the D3 APIs (much of whose semantics is defined only by, admittedly very good, documentation) in such a way that they _may_ suggest reformulations into a more powerful / expressive functional programming style *without losing* the domain specific knowledge that D3 represents.
This last perhaps needs some elaborating. There's an open question in my mind as to how far it is useful to represent the underlying D3 API in a strict language. Many, perhaps a majority, of D3's API endpoints take the form of polymorphic functions which can be called with varying numbers and types of parameters. This is key to reducing the visual noise of the "DSL" and a big part of JavaScript's appeal to the programmer. It's also a big, big source of complexity in debugging and understanding of others' code or your own code after elapsed time.
In this current draft, i've added some visual noise by making the parameters explicit using ADTs while retaining the simplicity of the function name. An alternative, seen in `purescript-d3`, is to provide variations on the function name (`attr`, `attr'`, `attr''` etc). Another alternative would be to explicitly model the optionality of the parameters with `Maybe`s and `Either`s and `Nullable`s. Another alternative might be to do something clever with lenses.
#### Ex 1. Making parameter types explicit with ADTs (`purescript-d3v4`)
``` haskell
circles <- g ... selectAll "circle"
.. dataBind (Data circleData)
.. enter .. append "circle"
.. attr "cx" (AttrFn (\d i nodes el -> pure d.x))
.. attr "cy" (AttrFn (\d i nodes el -> pure d.y))
.. attr "r" (SetAttr 20.0)
.. style "stroke" (Value "black")
.. style "fill" (Value "red")
```
#### Ex 2. Providing variations on function names (`purescript-d3`)
``` haskell
rootSelect ".chart"
.. selectAll "div"
.. bindData array
.. enter .. append "div"
.. style' "width" (\d -> show (x d) ++ "px")
.. text' show
```
#### Ex 3. Explicitly modelling optionality of params (not implemented)
#### Ex 4. (something clever with lenses)
### _TODO - write more on the pros and cons of these four approaches._
Beyond these four stylistic choices there are, i intuit, possibilities for perceiving and exploiting deeper abstractions and perhaps formulating a more powerful DSL entirely, perhaps one that is sufficiently powerful to rival D3's own.
|
afcondon/psd3-example
|
README.md
|
Markdown
|
mit
| 7,174 |
require 'spec_helper'
describe "errors/error_404.html.erb" do
pending "add some examples to (or delete) #{__FILE__}"
end
|
prank7/jsTwitter
|
spec/views/errors/error_404.html.erb_spec.rb
|
Ruby
|
mit
| 124 |
package gemx.dialogs;
import java.io.File;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.dnd.*;
import res.Messages;
public class PreprocessScriptAndDirectoriesDialog {
private Shell parent;
private Shell shellC;
private Combo comboPreprocessScript;
private String resStringPreprocessScript;
private List directoriesList;
private String lastDirectory;
private String[] resDirectories;
private boolean valueValid;
public PreprocessScriptAndDirectoriesDialog(Shell shell) {
resStringPreprocessScript = ""; //$NON-NLS-1$
resDirectories = new String[0];
valueValid = false;
parent = shell;
shellC = new Shell(shell, SWT.DIALOG_TRIM | SWT.PRIMARY_MODAL);
{
GridLayout gridLayout = new GridLayout();
gridLayout.numColumns = 2;
gridLayout.marginHeight = 15;
gridLayout.marginWidth = 15;
gridLayout.horizontalSpacing = 15;
shellC.setLayout(gridLayout);
}
{
Label labelPreprocessScript = new Label(shellC, SWT.NULL);
labelPreprocessScript.setText(Messages.getString("gemx.PreprocessScriptAndDirectoriesDialog.S_PREPROCESS_SCRIPT")); //$NON-NLS-1$
comboPreprocessScript = new Combo(shellC, SWT.DROP_DOWN);
{
GridData gridData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
gridData.widthHint = 200;
comboPreprocessScript.setLayoutData(gridData);
}
comboPreprocessScript.setFocus();
comboPreprocessScript.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.character == SWT.CR) {
resStringPreprocessScript = comboPreprocessScript.getText();
shellC.dispose();
}
}
});
}
Button defaultButton;
{
Label directoriesLabel = new Label(shellC, SWT.NULL);
directoriesLabel.setText(Messages.getString("gemx.PreprocessScriptAndDirectoriesDialog.S_TARGET_DIRECTORY_LIST")); //$NON-NLS-1$
Button addButton = new Button(shellC, SWT.PUSH);
{
GridData gridData = new GridData(GridData.FILL | GridData.HORIZONTAL_ALIGN_END);;
gridData.widthHint = 150;
addButton.setLayoutData(gridData);
}
addButton.setText(Messages.getString("gemx.PreprocessScriptAndDirectoriesDialog.S_ADD_DIRECTORY")); //$NON-NLS-1$
addButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
DirectoryDialog dialog = new DirectoryDialog(shellC);
if (lastDirectory != null) {
dialog.setFilterPath(lastDirectory);
}
dialog.setText(Messages.getString("gemx.PreprocessScriptAndDirectoriesDialog.S_GEMX_SELECT_TARGET_DIRECTORY")); //$NON-NLS-1$
//dialog.setMessage(Messages.getString("gemx.MainWindow.S_SELECT_A_ROOT_DIRECTORY_OF_THE_TARGET_SOURCE_FILES")); //$NON-NLS-1$
String path = dialog.open();
if (path == null || path.length() == 0) {
return;
}
directoriesList.add(path);
lastDirectory = path;
}
});
//Label dummyLabel = new Label(shellC, SWT.NULL);
directoriesList = new List(shellC, SWT.VIRTUAL | SWT.MULTI | SWT.V_SCROLL);
{
GridData gridData = new GridData(GridData.FILL_HORIZONTAL);
gridData.widthHint = 500;
gridData.heightHint = 100;
gridData.horizontalIndent = 10;
gridData.horizontalSpan = 2;
directoriesList.setLayoutData(gridData);
}
Menu pmenu = new Menu(shellC, SWT.POP_UP);
directoriesList.setMenu(pmenu);
{
MenuItem pitem = new MenuItem(pmenu, SWT.PUSH);
pitem.setText(Messages.getString("gemx.PreprocessScriptAndDirectoriesDialog.S_REMOVE")); //$NON-NLS-1$
pitem.setSelection(true);
pitem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
int[] selectionIndices = directoriesList.getSelectionIndices();
directoriesList.remove(selectionIndices);
}
});
}
DropTarget target = new DropTarget(directoriesList, DND.DROP_DEFAULT | DND.DROP_COPY);
FileTransfer transfer = FileTransfer.getInstance();
Transfer[] types = new Transfer[]{transfer};
target.setTransfer(types);
target.addDropListener(new DropTargetAdapter() {
@Override
public void dragEnter(DropTargetEvent evt){
evt.detail = DND.DROP_COPY;
}
@Override
public void drop(DropTargetEvent evt){
String[] directories = (String[])evt.data;
for (String d : directories) {
if (! new File(d).isDirectory()) {
MessageBox mes = new MessageBox(shellC, SWT.OK | SWT.ICON_ERROR);
mes.setText("Error - GemX"); //$NON-NLS-1$
mes.setMessage(Messages.getString("gemx.PreprocessScriptAndDirectoriesDialog.S_DROPPED_ITEM_IS_NOT_DIRECTORY")); //$NON-NLS-1$
mes.open();
return;
}
}
for (String d : directories) {
directoriesList.add(d);
}
}
});
defaultButton = addButton;
}
{
Composite buttonsCompo = new Composite(shellC, SWT.NONE);
GridData gridData2 = new GridData(GridData.HORIZONTAL_ALIGN_END);
gridData2.horizontalSpan = 2;
buttonsCompo.setLayoutData(gridData2);
{
GridLayout gridLayout = new GridLayout();
gridLayout.numColumns = 2;
gridLayout.marginHeight = 0;
gridLayout.marginWidth = 0;
gridLayout.horizontalSpacing = 10;
gridLayout.makeColumnsEqualWidth = true;
buttonsCompo.setLayout(gridLayout);
}
Button button1 = new Button(buttonsCompo, SWT.PUSH);
{
GridData gridData = new GridData(GridData.FILL);
gridData.widthHint = 100;
button1.setLayoutData(gridData);
button1.setText(Messages.getString("gemx.MainWindow.S_NEXT")); //$NON-NLS-1$
button1.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
resStringPreprocessScript = comboPreprocessScript.getText();
resDirectories = directoriesList.getItems();
if (resDirectories == null || resDirectories.length == 0) {
MessageBox mes = new MessageBox(shellC, SWT.OK | SWT.ICON_ERROR);
mes.setText("Error - GemX"); //$NON-NLS-1$
mes.setMessage(Messages.getString("gemx.PreprocessScriptAndDirectoriesDialog.S_NO_DIRECTORIES_ARE_SELECTED")); //$NON-NLS-1$
mes.open();
return;
}
valueValid = true;
shellC.dispose();
}
});
}
Button button2 = new Button(buttonsCompo, SWT.PUSH);
{
GridData gridData = new GridData(GridData.FILL_HORIZONTAL);
gridData.widthHint = 100;
button2.setLayoutData(gridData);
button2.setText(Messages.getString("gemx.MainWindow.S_CANCEL")); //$NON-NLS-1$
button2.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
resStringPreprocessScript = ""; //$NON-NLS-1$
resDirectories = new String[0];
valueValid = false;
shellC.dispose();
}
});
}
}
defaultButton.setFocus();
}
public void setText(String str) {
shellC.setText(str);
}
public String getText() {
return shellC.getText();
}
public boolean open() {
shellC.pack();
shellC.setLocation(parent.getLocation().x
+ (parent.getSize().x - shellC.getSize().x) / 2, parent
.getLocation().y
+ (parent.getSize().y - shellC.getSize().y) / 2);
shellC.open();
while (!shellC.isDisposed()) {
if (!shellC.getDisplay().readAndDispatch()) {
shellC.getDisplay().sleep();
}
}
return valueValid;
}
public void addPreprocessScript(String str, int i) {
comboPreprocessScript.add(str, i);
}
public void addPreprocessScript(String str) {
comboPreprocessScript.add(str);
}
public void removePreprocesssScripts(int from, int to) {
comboPreprocessScript.remove(from, to);
}
public void removePrprocessScript(int i) {
comboPreprocessScript.remove(i);
}
public void removePreprocessScript(String str) {
comboPreprocessScript.remove(str);
}
public void removeAllPreprocessScripts() {
comboPreprocessScript.removeAll();
}
public void setPreprocessScript(String str) {
comboPreprocessScript.setText(str);
}
public String getPreprocessScript() {
return resStringPreprocessScript;
}
public void setLastDirectory(String lastDirectory) {
this.lastDirectory = lastDirectory;
}
public String[] getDirectories() {
return this.resDirectories;
}
}
|
petersenna/ccfinderx-gui
|
GemX/gemx/dialogs/PreprocessScriptAndDirectoriesDialog.java
|
Java
|
mit
| 8,555 |
from collections import namedtuple
from io import StringIO
import sys
class catch_streams:
result = namedtuple('Streams', ['out', 'err'])
def __enter__(self):
self.old_stdout = sys.stdout
self.old_stderr = sys.stderr
sys.stdout = StringIO()
sys.stderr = StringIO()
return self.result(sys.stdout, sys.stderr)
def __exit__(self, exc_type, exc_val, exc_tb):
sys.stdout = self.old_stdout
sys.stderr = self.old_stderr
|
mysz/versionner
|
test/streamcatcher.py
|
Python
|
mit
| 487 |
package megapi
import (
"bytes"
"encoding/binary"
"github.com/hybridgroup/gobot"
"sync"
)
var _ gobot.Driver = (*MotorDriver)(nil)
// MotorDriver represents a motor
type MotorDriver struct {
name string
megaPi *MegaPiAdaptor
port byte
halted bool
syncRoot *sync.Mutex
}
// NewMotorDriver creates a new MotorDriver using the provided name, and at the given port
func NewMotorDriver(megaPi *MegaPiAdaptor, name string, port byte) *MotorDriver {
return &MotorDriver{
name: name,
megaPi: megaPi,
port: port,
halted: true,
syncRoot: &sync.Mutex{},
}
}
// Name returns the name of this motor
func (m *MotorDriver) Name() string {
return m.name
}
// Start implements the Driver interface
func (m *MotorDriver) Start() []error {
m.syncRoot.Lock()
defer m.syncRoot.Unlock()
m.halted = false
m.speedHelper(0)
return []error{}
}
// Halt terminates the Driver interface
func (m *MotorDriver) Halt() []error {
m.syncRoot.Lock()
defer m.syncRoot.Unlock()
m.halted = true
m.speedHelper(0)
return []error{}
}
// Connection returns the Connection associated with the Driver
func (m *MotorDriver) Connection() gobot.Connection {
return gobot.Connection(m.megaPi)
}
// Speed sets the motors speed to the specified value
func (m *MotorDriver) Speed(speed int16) error {
m.syncRoot.Lock()
defer m.syncRoot.Unlock()
if m.halted {
return nil
}
m.speedHelper(speed)
return nil
}
// there is some sort of bug on the hardware such that you cannot
// send the exact same speed to 2 different motors consecutively
// hence we ensure we always alternate speeds
func (m *MotorDriver) speedHelper(speed int16) {
m.sendSpeed(speed - 1)
m.sendSpeed(speed)
}
// sendSpeed sets the motors speed to the specified value
func (m *MotorDriver) sendSpeed(speed int16) {
bufOut := new(bytes.Buffer)
// byte sequence: 0xff, 0x55, id, action, device, port
bufOut.Write([]byte{0xff, 0x55, 0x6, 0x0, 0x2, 0xa, m.port})
binary.Write(bufOut, binary.LittleEndian, speed)
bufOut.Write([]byte{0xa})
m.megaPi.writeBytesChannel <- bufOut.Bytes()
}
|
Jay-AHR/qpid_em
|
vendor/github.com/hybridgroup/gobot/platforms/megapi/motor_driver.go
|
GO
|
mit
| 2,081 |
//%LICENSE////////////////////////////////////////////////////////////////
//
// Licensed to The Open Group (TOG) under one or more contributor license
// agreements. Refer to the OpenPegasusNOTICE.txt file distributed with
// this work for additional information regarding copyright ownership.
// Each contributor licenses this file to you under the OpenPegasus Open
// Source License; you may not use this file except in compliance with the
// License.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//////////////////////////////////////////////////////////////////////////
//
//%/////////////////////////////////////////////////////////////////////////
#include <Pegasus/Common/Config.h>
#include <Pegasus/Common/String.h>
#include <Pegasus/Common/PegasusVersion.h>
PEGASUS_USING_PEGASUS;
PEGASUS_USING_STD;
#include "UNIX_DiagnosticResultProvider.h"
extern "C"
PEGASUS_EXPORT CIMProvider* PegasusCreateProvider(const String& providerName)
{
if (String::equalNoCase(providerName, CIMHelper::EmptyString)) return NULL;
else if (String::equalNoCase(providerName, "UNIX_DiagnosticResultProvider")) return new UNIX_DiagnosticResultProvider();
return NULL;
}
|
brunolauze/openpegasus-providers-old
|
src/Providers/UNIXProviders/DiagnosticResult/UNIX_DiagnosticResultMain.cpp
|
C++
|
mit
| 2,201 |
<?php
namespace Test\Phinx\Migration\Manager;
class EnvironmentTest extends \PHPUnit_Framework_TestCase
{
/**
* @var \Phinx\Migration\Manager\Environment
*/
private $environment;
public function setUp()
{
$this->environment = new \Phinx\Migration\Manager\Environment('test', array());
}
public function testConstructorWorksAsExpected()
{
$env = new \Phinx\Migration\Manager\Environment('testenv', array('foo' => 'bar'));
$this->assertEquals('testenv', $env->getName());
$this->assertArrayHasKey('foo', $env->getOptions());
}
public function testSettingTheName()
{
$this->environment->setName('prod123');
$this->assertEquals('prod123', $this->environment->getName());
}
public function testSettingOptions()
{
$this->environment->setOptions(array('foo' => 'bar'));
$this->assertArrayHasKey('foo', $this->environment->getOptions());
}
/**
* @expectedException \RuntimeException
* @expectedExceptionMessage Invalid adapter specified: fakeadapter
*/
public function testInvalidAdapter()
{
$this->environment->setOptions(array('adapter' => 'fakeadapter'));
$this->environment->getAdapter();
}
/**
* @expectedException \RuntimeException
*/
public function testNoAdapter()
{
$this->environment->getAdapter();
}
public function testSchemaName()
{
$this->assertEquals('phinxlog', $this->environment->getSchemaTableName());
$this->environment->setSchemaTableName('changelog');
$this->assertEquals('changelog', $this->environment->getSchemaTableName());
}
public function testAdapterFactoryCreatesMysqlAdapter()
{
$this->environment->setOptions(array('adapter' => 'mysql'));
$this->assertTrue($this->environment->getAdapter() instanceof \Phinx\Db\Adapter\MysqlAdapter);
}
public function testAdapterFactoryCreatesSqliteAdapter()
{
$this->environment->setOptions(array('adapter' => 'sqlite'));
$this->assertTrue($this->environment->getAdapter() instanceof \Phinx\Db\Adapter\SQLiteAdapter);
}
public function testCurrentVersion()
{
$stub = $this->getMock('\Phinx\Db\Adapter\PdoAdapter', array(), array(array()));
$stub->expects($this->any())
->method('getVersions')
->will($this->returnValue(array('20110301080000')));
$this->environment->setAdapter($stub);
$this->assertEquals('20110301080000', $this->environment->getCurrentVersion());
}
public function testExecutingAMigrationUp()
{
// stub adapter
$adapterStub = $this->getMock('\Phinx\Db\Adapter\PdoAdapter', array(), array(array()));
$adapterStub->expects($this->once())
->method('migrated')
->will($this->returnArgument(0));
$this->environment->setAdapter($adapterStub);
// up
$upMigration = $this->getMock('\Phinx\Migration\AbstractMigration', array('up'), array('20110301080000'));
$upMigration->expects($this->once())
->method('up');
$this->environment->executeMigration($upMigration, \Phinx\Migration\MigrationInterface::UP);
}
public function testExecutingAMigrationDown()
{
// stub adapter
$adapterStub = $this->getMock('\Phinx\Db\Adapter\PdoAdapter', array(), array(array()));
$adapterStub->expects($this->once())
->method('migrated')
->will($this->returnArgument(0));
$this->environment->setAdapter($adapterStub);
// down
$downMigration = $this->getMock('\Phinx\Migration\AbstractMigration', array('down'), array('20110301080000'));
$downMigration->expects($this->once())
->method('down');
$this->environment->executeMigration($downMigration, \Phinx\Migration\MigrationInterface::DOWN);
}
public function testExecutingAMigrationWithTransactions()
{
// stub adapter
$adapterStub = $this->getMock('\Phinx\Db\Adapter\PdoAdapter', array(), array(array()));
$adapterStub->expects($this->once())
->method('beginTransaction');
$adapterStub->expects($this->once())
->method('commitTransaction');
$adapterStub->expects($this->exactly(2))
->method('hasTransactions')
->will($this->returnValue(true));
$this->environment->setAdapter($adapterStub);
// migrate
$migration = $this->getMock('\Phinx\Migration\AbstractMigration', array('up'), array('20110301080000'));
$migration->expects($this->once())
->method('up');
$this->environment->executeMigration($migration, \Phinx\Migration\MigrationInterface::UP);
}
public function testExecutingAChangeMigrationUp()
{
// stub adapter
$adapterStub = $this->getMock('\Phinx\Db\Adapter\PdoAdapter', array(), array(array()));
$adapterStub->expects($this->once())
->method('migrated')
->will($this->returnArgument(0));
$this->environment->setAdapter($adapterStub);
// migration
$migration = $this->getMock('\Phinx\Migration\AbstractMigration', array('change'), array('20130301080000'));
$migration->expects($this->once())
->method('change');
$this->environment->executeMigration($migration, \Phinx\Migration\MigrationInterface::UP);
}
public function testExecutingAChangeMigrationDown()
{
// stub adapter
$adapterStub = $this->getMock('\Phinx\Db\Adapter\PdoAdapter', array(), array(array()));
$adapterStub->expects($this->once())
->method('migrated')
->will($this->returnArgument(0));
$this->environment->setAdapter($adapterStub);
// migration
$migration = $this->getMock('\Phinx\Migration\AbstractMigration', array('change'), array('20130301080000'));
$migration->expects($this->once())
->method('change');
$this->environment->executeMigration($migration, \Phinx\Migration\MigrationInterface::DOWN);
}
}
|
rsdevigo/phinx
|
tests/Phinx/Migration/Manager/EnvironmentTest.php
|
PHP
|
mit
| 6,548 |
module.exports = require('./index.json');
|
kazupon/duo-jsonlint
|
test/fixtures/valid/index.js
|
JavaScript
|
mit
| 42 |
/*
* Power BI Visualizations
*
* Copyright (c) Microsoft Corporation
* All rights reserved.
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the ""Software""), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/// <reference path="../_references.ts"/>
module powerbitests {
import AnimatedText = powerbi.visuals.AnimatedText;
describe("AnimatedText", () => {
let animatedText: AnimatedText;
beforeEach(() => {
animatedText = new AnimatedText("animatedText");
});
it("AnimatedText_getSeedFontHeight does not exceed style maximum", () => {
animatedText.style = powerbi.visuals.visualStyles.create();
expect(animatedText.getSeedFontHeight(100, 90)).toBeLessThan(100);
});
it("AnimatedText_getSeedFontHeight returns a smaller number than the height", () => {
animatedText.style = powerbi.visuals.visualStyles.create();
expect(animatedText.getSeedFontHeight(100, 90)).toBeLessThan(100);
});
it("AnimatedText TextColor is #333 by default", () => {
animatedText.style = powerbi.visuals.visualStyles.create();
helpers.assertColorsMatch(animatedText.style.titleText.color.value, '#333');
});
it("AnimatedText_setTextColor correctly sets style", () => {
animatedText.style = powerbi.visuals.visualStyles.create();
let setTextColor = '#F00';
animatedText.setTextColor(setTextColor);
helpers.assertColorsMatch(animatedText.style.titleText.color.value, setTextColor);
});
it("AnimatedText_getTextAnchor when the aligment is 'left'", () => {
animatedText.visualConfiguration = {
align: "left"
};
expect(animatedText.getTextAnchor()).toBe("start");
});
it("AnimatedText_getTextAnchor when the aligment is 'right'", () => {
animatedText.visualConfiguration = {
align: "right"
};
expect(animatedText.getTextAnchor()).toBe("end");
});
it("AnimatedText_getTextAnchor when the aligment is undefined", () => {
animatedText.visualConfiguration = undefined;
expect(animatedText.getTextAnchor()).toBe("middle");
animatedText.visualConfiguration = {
align: "center"
};
expect(animatedText.getTextAnchor()).toBe("middle");
});
it("AnimatedText_getTranslateX alignment is 'left'", () => {
animatedText.visualConfiguration = {
align: "left"
};
expect(animatedText.getTranslateX(0)).toBe(0);
expect(animatedText.getTranslateX(100)).toBe(0);
});
it("AnimatedText_getTranslateX alignment is 'right'", () => {
animatedText.visualConfiguration = {
align: "right"
};
expect(animatedText.getTranslateX(0)).toBe(0);
expect(animatedText.getTranslateX(100)).toBe(100);
});
it("AnimatedText_getTranslateX when alignment is undefined, returns the center", () => {
animatedText.visualConfiguration = undefined;
expect(animatedText.getTranslateX(0)).toBe(0);
expect(animatedText.getTranslateX(100)).toBe(50);
});
});
describe("AnimatedText DOM tests", () => {
let animatedTextBuilder: AnimatedTextBuilder;
let animationOptions: powerbi.AnimationOptions = {
transitionImmediate: true
};
beforeEach((done) => {
animatedTextBuilder =
new AnimatedTextBuilder("200", "300", "animatedText", animationOptions);
done();
});
it("AnimatedText_getAdjustedFontHeight when seed font width is bigger than the width", () => {
// parameters are availableWidth, textToMeasure, seedFontHeight
// When the measured text with the seed height is bigger than availableWidth, decrease the font height
expect(animatedTextBuilder.animatedText.getAdjustedFontHeight(4, "text", 10)).toBeLessThan(10);
});
it("AnimatedText_getAdjustedFontHeight when seed font width is smaller or equal to the width", () => {
// parameters are availableWidth, textToMeasure, seedFontHeight
// When the measured text with the seed height is equal/smaller than availableWidth, return the font height
expect(animatedTextBuilder.animatedText.getAdjustedFontHeight(30, "text", 3)).toBe(3);
});
it("AnimatedText doValueTransition sets text", (done) => {
animatedTextBuilder.doValueTransition(3, 4);
expect($(".animatedText")).toBeInDOM();
expect($(".mainText")).toBeInDOM();
setTimeout(() => {
expect($(".mainText").text()).toEqual("4");
done();
}, DefaultWaitForRender);
});
it("AnimatedText doValueTransition formats number > 10000", (done) => {
animatedTextBuilder.doValueTransition(3, 4534353);
expect($(".animatedText")).toBeInDOM();
expect($(".mainText")).toBeInDOM();
setTimeout(() => {
expect($(".mainText").text()).toEqual("4.53M");
done();
}, DefaultWaitForRender);
});
it("AnimatedText doValueTransition sets translateY correctly", (done) => {
animatedTextBuilder.doValueTransition(3, 4);
expect($(".animatedText")).toBeInDOM();
expect($(".mainText")).toBeInDOM();
setTimeout(() => {
// IE and Chrome represent the transform differently
expect($(".mainText").attr("transform")).toMatch(/translate\(\d+(,| )130\)/);
done();
}, DefaultWaitForRender);
});
it("AnimatedText doValueTransition to 0", (done) => {
animatedTextBuilder.doValueTransition(null, 0);
expect($(".animatedText")).toBeInDOM();
expect($(".mainText")).toBeInDOM();
setTimeout(() => {
expect($(".mainText").text()).toEqual("0");
done();
}, DefaultWaitForRender);
});
it("AnimatedText doValueTransition to null", (done) => {
animatedTextBuilder.doValueTransition(null, null);
expect($(".animatedText")).toBeInDOM();
expect($(".mainText")).toBeInDOM();
setTimeout(() => {
expect(helpers.findElementText($(".mainText"))).toEqual("(Blank)");
done();
}, DefaultWaitForRender);
});
it("AnimatedText doValueTransition with text color set", (done) => {
let setTextColor = 'rgb(255,0,0)';
animatedTextBuilder.animatedText.setTextColor(setTextColor);
animatedTextBuilder.doValueTransition(3, 4);
expect($(".animatedText")).toBeInDOM();
expect($(".mainText")).toBeInDOM();
setTimeout(() => {
helpers.assertColorsMatch($(".mainText").css('fill'), setTextColor);
done();
}, DefaultWaitForRender);
});
});
class AnimatedTextBuilder {
private element: JQuery;
private animationOptions: powerbi.AnimationOptions;
private animatedTextVisual: AnimatedText;
public get animatedText(): AnimatedText {
return this.animatedTextVisual;
}
constructor(
height: string,
width: string,
animatedTextName: string,
animationOptions: powerbi.AnimationOptions) {
this.animationOptions = animationOptions;
this.element = powerbitests.helpers.testDom(height, width);
this.animatedTextVisual = new AnimatedText(animatedTextName);
this.init();
}
private init(): void {
this.animatedText.currentViewport = {
height: this.element.height(),
width: this.element.width()
};
this.animatedText.hostServices = powerbitests.mocks.createVisualHostServices();
this.animatedText.svg = d3.select(this.element.get(0)).append("svg");
this.animatedText.style = powerbi.visuals.visualStyles.create();
}
public doValueTransition(startValue: any, endValue: any): void {
this.animatedText.doValueTransition(startValue, endValue, null, this.animationOptions, 0, false);
}
}
}
|
sjkp/PowerBI-visuals
|
src/Clients/PowerBIVisualsTests/visuals/animatedTextTests.ts
|
TypeScript
|
mit
| 9,758 |
'use strict';
var fs = require('fs');
var path = require('path');
var glob = require('globby');
var assert = require('assert');
var should = require('should');
var utils = require('../lib/utils');
var App = require('..');
var app;
describe('views render', function () {
beforeEach(function () {
app = new App();
app.engine('tmpl', require('engine-lodash'));
app.create('page');
});
describe('.render', function () {
it('should render a view from the collection:', function (done) {
app.pages('a.tmpl', {path: 'a.tmpl', content: 'a<%= a %>z', a: 'bbb'});
app.pages.render('a.tmpl', {}, function (err, res) {
if (err) return done(err);
res.content.should.equal('abbbz');
done();
});
});
});
});
|
adjohnson916/template
|
test/views.render.js
|
JavaScript
|
mit
| 768 |
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Update migration item input.
*/
public class UpdateMigrationItemInput {
/**
* Update migration item input properties.
*/
@JsonProperty(value = "properties")
private UpdateMigrationItemInputProperties properties;
/**
* Get update migration item input properties.
*
* @return the properties value
*/
public UpdateMigrationItemInputProperties properties() {
return this.properties;
}
/**
* Set update migration item input properties.
*
* @param properties the properties value to set
* @return the UpdateMigrationItemInput object itself.
*/
public UpdateMigrationItemInput withProperties(UpdateMigrationItemInputProperties properties) {
this.properties = properties;
return this;
}
}
|
selvasingh/azure-sdk-for-java
|
sdk/recoveryservices.siterecovery/mgmt-v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateMigrationItemInput.java
|
Java
|
mit
| 1,177 |
// Code generated by Microsoft (R) AutoRest Code Generator 1.2.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Searchservice.Models
{
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Runtime;
using System.Runtime.Serialization;
/// <summary>
/// Defines values for ScoringFunctionInterpolation.
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
public enum ScoringFunctionInterpolation
{
[EnumMember(Value = "linear")]
Linear,
[EnumMember(Value = "constant")]
Constant,
[EnumMember(Value = "quadratic")]
Quadratic,
[EnumMember(Value = "logarithmic")]
Logarithmic
}
internal static class ScoringFunctionInterpolationEnumExtension
{
internal static string ToSerializedValue(this ScoringFunctionInterpolation? value) =>
value == null ? null : ((ScoringFunctionInterpolation)value).ToSerializedValue();
internal static string ToSerializedValue(this ScoringFunctionInterpolation value)
{
switch( value )
{
case ScoringFunctionInterpolation.Linear:
return "linear";
case ScoringFunctionInterpolation.Constant:
return "constant";
case ScoringFunctionInterpolation.Quadratic:
return "quadratic";
case ScoringFunctionInterpolation.Logarithmic:
return "logarithmic";
}
return null;
}
internal static ScoringFunctionInterpolation? ParseScoringFunctionInterpolation(this string value)
{
switch( value )
{
case "linear":
return ScoringFunctionInterpolation.Linear;
case "constant":
return ScoringFunctionInterpolation.Constant;
case "quadratic":
return ScoringFunctionInterpolation.Quadratic;
case "logarithmic":
return ScoringFunctionInterpolation.Logarithmic;
}
return null;
}
}
}
|
veronicagg/autorest
|
Samples/1c-multiple-input-swaggers/Client/Models/ScoringFunctionInterpolation.cs
|
C#
|
mit
| 2,232 |
'use strict'
import { Request } from '../middlewares/api'
import * as types from '../constants/ActionTypes'
import { PAGES_URL } from '../constants/URLs'
import { addNotification, removeNotification } from '../helpers'
// Actions
function requestPages () {
return {
type: types.REQUEST_PAGES
}
}
function receivePages (json) {
return {
type: types.RECEIVE_PAGES,
pages: json
}
}
export function fetchPages () {
return dispatch => {
dispatch(requestPages())
Request.get(PAGES_URL)
.then(json => dispatch(receivePages(json)))
.catch(err => console.error(err))
}
}
function createPageRequest (name) {
return { type: types.CREATE_PAGE_REQUEST, name }
}
function createPageSuccess (json) {
return { type: types.CREATE_PAGE_SUCCESS, page: json }
}
function createPageFailure (error) {
return { type: types.CREATE_PAGE_FAILURE, error }
}
export function createPage (NotificationSystem, name) {
return dispatch => {
const n = addNotification.call(NotificationSystem, 'Creating', 'info')
dispatch(createPageRequest(name))
Request.post(PAGES_URL, { name })
.then(json => {
removeNotification.call(NotificationSystem, n)
addNotification.call(NotificationSystem, 'Created', 'success', 3)
dispatch(createPageSuccess(json))
})
.catch(err => {
removeNotification.call(NotificationSystem, n)
addNotification.call(NotificationSystem, 'Error', 'error', 3)
dispatch(createPageFailure(err))
})
}
}
function togglePublishRequest (id) {
return { type: types.TOGGLE_PUBLISH_REQUEST, id }
}
function togglePublishSuccess (json) {
return { type: types.TOGGLE_PUBLISH_SUCCESS, page: json }
}
function togglePublishFailure (error) {
return { type: types.TOGGLE_PUBLISH_FAILURE, error }
}
export function togglePublish (NotificationSystem, id, published) {
return dispatch => {
const n = addNotification.call(NotificationSystem, published ? 'Publishing' : 'Unpublishing', 'info')
dispatch(togglePublishRequest(id))
Request.put(`${PAGES_URL}/${id}`, { published })
.then(json => {
removeNotification.call(NotificationSystem, n)
addNotification.call(NotificationSystem, published ? 'Published' : 'Unpublished', 'success', 3)
dispatch(togglePublishSuccess(json))
})
.catch(err => {
removeNotification.call(NotificationSystem, n)
addNotification.call(NotificationSystem, 'Error', 'error', 3)
dispatch(togglePublishFailure(err))
})
}
}
function deletePageRequest (id, params) {
return { type: types.DELETE_PAGE_REQUEST, id }
}
function deletePageSuccess (json) {
return { type: types.DELETE_PAGE_SUCCESS, page: json }
}
function deletePageFailure (error) {
return { type: types.DELETE_PAGE_FAILURE, error }
}
export function deletePage (NotificationSystem, id) {
return dispatch => {
const n = addNotification.call(NotificationSystem, 'Deleting', 'info')
dispatch(deletePageRequest(id))
Request.delete(`${PAGES_URL}/${id}`)
.then(json => {
removeNotification.call(NotificationSystem, n)
addNotification.call(NotificationSystem, 'Deleted', 'success', 3)
dispatch(deletePageSuccess(json))
})
.catch(err => {
removeNotification.call(NotificationSystem, n)
addNotification.call(NotificationSystem, 'Error', 'error', 3)
dispatch(deletePageFailure(err))
})
}
}
|
imperodesign/clever-pages-admin
|
assets/src/js/actions/pages.js
|
JavaScript
|
mit
| 3,444 |
const debug = require('debug')('esMappingGenerator')
const _ = require('lodash')
const async = require('async-q')
const ElasticGraph = require('../../index')
const es = new ElasticGraph(process.argv[2])
const configs = es.config
const aggs = require('./setAggregations')
module.exports = function(entityType) {
const entitySchema = configs.schema[entityType]
const entityLanguages = configs.common.supportedLanguages
const mapping = initialMapping(entityType)
const entityProperties = mapping.mappings[entityType].properties
const fields = _.keys(entitySchema)
_.each(fields, function(field) {
const type = entitySchema[field].type
if (entitySchema[field].multiLingual && !entitySchema[field].isRelationship) {
_.forEach(entityLanguages, function(language) {
if (entitySchema[field].autoSuggestion) {
_.set(entityProperties, [language ,'properties', field] , {
type: 'string',
fields: {
[field]: {
type: fieldType(type),
analyzer: 'standard'//language
},
suggest: {
type: fieldType(type),
store: false,
analyzer: 'autocomplete',
search_analyzer: 'standard'
}
}
})
} else {
_.set(entityProperties, [language, 'properties', field], {
type: fieldType(type),
analyzer: 'standard'//language
})
}
})
} else if (entitySchema[field].autoSuggestion && !entitySchema[field].isRelationship) {
_.set(entityProperties, [field], {
type: 'string',
fields: {
[field]: {
type: fieldType(type),
analyzer: 'standard'//'english'
},
suggest: {
type: fieldType(type),
store: false,
analyzer: 'autocomplete',
search_analyzer: 'standard'
}
}
})
} else if (_.isArray(type) && _.isPlainObject(type[0])) {
entityProperties[field] = {
dynamic: true,
//type: 'Object', If specified, throws error in es 2.1.
properties: {}
}
const nestedProperties = entityProperties[field].properties
_.forEach(_.keys(entitySchema[field].type[0]), function(nestedField) {
nestedProperties[nestedField] = {
type: fieldType(entitySchema[field].type[0][nestedField].type)
}
})
} else if (entitySchema[field].isRelationship) {
mapping.mappings[entityType].properties[field] = {
type: 'object'
}
if (entitySchema[field].autoSuggestion) {
let fieldVal = {
type: "string",
store: false,
analyzer: "autocomplete",
search_analyzer: "standard"
}
let suggestionPath = entitySchema[field].suggestionPath.split('.')
suggestionPath.unshift(field)
aggs.setMappingAtPath(mapping.mappings[entityType].properties, suggestionPath, entityType, entitySchema, configs, 'suggest', fieldVal)
}
} else {
mapping.mappings[entityType].properties[field] = {
type: fieldType(type)
}
}
})
debug(entityType, JSON.stringify(mapping))
return mapping
}
function fieldType(type) {
if (type === String || _.isArray(type) && type[0] === String) {
return 'string'
} else if (type === Date || type === 'date') {
return 'date'
} else if (type === Boolean) {
return 'boolean'
} else if (type == Number) {
return 'float'
} else if (type === Object) {
return 'object'
} else {
return 'object'
}
}
function langMapping(mapping, entityType, entityLanguages) {
debug(mapping, entityLanguages)
if (!mapping.mappings[entityType].properties[entityLanguages[0]]) {
const langMapping = _.reduce(entityLanguages, function(result, language) {
result[language] = {
properties: {}
}
return result
}, {})
mapping.mappings[entityType].properties = langMapping
}
return mapping
}
function initialMapping(entityType) {
const mapping = {
mappings: {
[entityType]: {
dynamic: true,
properties: {}
}
},
settings: {
analysis: {
filter: {
autocomplete_filter: {
type: 'edge_ngram',
min_gram: 1,
max_gram: 20
}
},
analyzer: {
autocomplete: {
type: 'custom',
tokenizer: 'standard',
filter: [
'lowercase',
'autocomplete_filter'
]
}
}
}
}
}
return mapping
}
if (require.main === module) {
// run mapping generator on all entities mentions in configs.
const toRecreateIndices = process.argv[4] && process.argv[4].split(',') || _.keys(configs.schema)
const mappingsOfEntities = _.reduce(toRecreateIndices, function(result, entityType) {
result[entityType] = module.exports(entityType)
return result
}, {})
if (process.argv[3] === 'recreate' || process.argv[3] === 'delete') {
debug('Deleting indices one by one')
return async.eachSeries(toRecreateIndices, (et) => {
return es.indices.delete({index: et + 's'})
.then(() => {
debug('Deleted index', et + 's')
})
.catch((err) => {
if (err.status == 404) {
debug(et + 's', 'index does not exist. ignoring.')
} else {
debug('Unknown error. Please recheck for index', et + 's', err)
}
})
})
.catch(debug)
.then(() => {//. Creating again with new mapping
if (process.argv[3] !== 'recreate') {
return Q()
}
return async.eachSeries(toRecreateIndices, (et) => {
if (es.config.aggregations[et]) {
aggs.setAggregation(configs.aggregations[et], et, mappingsOfEntities[et], configs)
}
return es.indices.create({
index: et + 's',
body: mappingsOfEntities[et]
})
.then(() => {
debug('Created index', et + 's')
})
.catch((err) => {
debug('Error in creating index', et + 's', err, 'Mapping:', JSON.stringify(mappingsOfEntities[et]))
})
})
.catch((err) => {
debug('Error in creating indices', err)
})
})
.then(() => {
debug('Done')
} )
} else {
debug(JSON.stringify(mappingsOfEntities), 'Simply printed the mapping')
}
}
|
mastersilv3r/epicsearch
|
lib/mappingGenerator/esMappingGenerator.js
|
JavaScript
|
mit
| 6,532 |
import reducer from "../src/reducers/championships"
import * as types from "../src/actions/types"
const defaultModel1 = {
name: "Main Title",
male: false,
}
const defaultModel2 = {
name: "Secondary Title",
male: true,
}
const action = {
type: types.RESET,
payload: [],
}
describe("given a championships reducer", () => {
let activeReducer
before(() => (activeReducer = reducer(undefined, action)))
it("should return the initial state", () => {
expect(activeReducer).to.be.empty
})
describe("and a collection is passed in", () => {
before(() => {
action.type = types.CREATE_CHAMPIONSHIP
action.payload = defaultModel1
activeReducer = reducer(activeReducer, action)
action.payload = defaultModel2
activeReducer = reducer(activeReducer, action)
})
it("should now have two in the collection", () => {
expect(activeReducer.length).to.equal(2)
})
it("should have a red championship", () => {
expect(activeReducer[0].id).to.not.be.null
expect(activeReducer[0].male).to.equal(defaultModel1.male)
})
it("should have a blue championship", () => {
expect(activeReducer[1].male).to.equal(defaultModel2.male)
})
describe("and delete request is called", () => {
before(() => {
action.payload = activeReducer[0].id
action.type = types.DELETE_CHAMPIONSHIP
activeReducer = reducer(activeReducer, action)
})
it("should have only one championship remaining", () => {
expect(activeReducer.length).to.equal(1)
})
})
describe("and an update is called", () => {
let newName = "Jarrod"
before(() => {
action.payload = activeReducer[0]
action.type = types.UPDATE_CHAMPIONSHIP
action.payload.name = newName
activeReducer = reducer(activeReducer, action)
})
it("should still only have one championship", () => {
expect(activeReducer.length).to.equal(1)
})
it("should update the name on that one item", () => {
expect(activeReducer[0].name).to.equal(newName)
})
})
describe("and reset is called", () => {
before(() => {
action.type = types.RESET
activeReducer = reducer(activeReducer, action)
})
it("should have NO items in the collection", () => {
expect(activeReducer).to.have.length(0)
})
})
})
})
|
azz0r/universe-sim-manager
|
test/championships.reducer.spec.js
|
JavaScript
|
mit
| 2,425 |
---
layout: post
category : interop
tagline: ""
tags : [cpp csharp]
---
{% include JB/setup %}
## I guarantee this will come in handy some day
<https://github.com/Marqin/simpleCoreCLRHost>
This C++ app allows to run custom C# method from compiled C# .dll on Linux and OS X using coreCLR. In our example that C# method runs C++ class methods on C++ objects using pointers and delegates. It's code is based on example from coreCLR and was done with big help from @janvorli, who patiently answered my questions.
|
faizanvahevaria/chrisamow.github.io
|
_posts/2016-10-28-cpp-invoke-coreCLR-linux.md
|
Markdown
|
mit
| 523 |
const s = require('shelljs');
s.rm('-rf', 'build');
s.mkdir('build');
s.cp('.env', 'build/.env');
s.cp('-R', 'public', 'build/public');
s.mkdir('-p', 'build/server/common/swagger');
s.cp('server/common/swagger/Api.yaml', 'build/server/common/swagger/Api.yaml');
|
scottbea/SimpleApiNode
|
build.js
|
JavaScript
|
mit
| 263 |
package com.viesis.viescraft.common.entity.airshipitems.v3;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.init.SoundEvents;
import net.minecraft.util.EnumParticleTypes;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.world.World;
import com.viesis.viescraft.common.entity.airshipcolors.v3.EntityAirshipV3Orange;
import com.viesis.viescraft.common.entity.airshipitems.EntityItemAirshipCore;
public class EntityItemAirshipV3Orange extends EntityItemAirshipCore {
public EntityItemAirshipV3Orange(World worldIn)
{
super(worldIn);
}
public EntityItemAirshipV3Orange(World worldIn, EntityLivingBase entity)
{
super(worldIn, entity);
}
public EntityItemAirshipV3Orange(World worldIn, double x, double y, double z)
{
super(worldIn, x, y, z);
}
@Override
protected void onImpact(RayTraceResult result)
{
if (!this.worldObj.isRemote)
{
this.playSound(SoundEvents.ENTITY_GENERIC_EXPLODE, 0.5F, 0.4F / .5F * 0.4F + 0.8F);
this.worldObj.spawnEntityInWorld(new EntityAirshipV3Orange(this.worldObj, this.posX, this.posY + 0.5F, this.posZ));
this.setDead();
}
else
{
for (int ii = 0; ii < 10; ++ii)
{
int d = random.nextInt(100) + 1;
this.worldObj.spawnParticle(EnumParticleTypes.EXPLOSION_LARGE,
this.posX + this.worldObj.rand.nextFloat() * this.width * 2.0F - this.width,
this.posY + 0.5D,
this.posZ + this.worldObj.rand.nextFloat() * this.width * 2.0F - this.width,
0.0D, 0.0D, 0.0D, new int[0]);
if (d <= 2)
{
this.worldObj.spawnParticle(EnumParticleTypes.EXPLOSION_LARGE,
this.posX + this.worldObj.rand.nextFloat() * this.width * 2.0F - this.width,
this.posY + 0.5D,
this.posZ + this.worldObj.rand.nextFloat() * this.width * 2.0F - this.width,
0.0D, 0.0D, 0.0D, new int[0]);
}
if (d <= 15)
{
this.worldObj.spawnParticle(EnumParticleTypes.EXPLOSION_NORMAL,
this.posX + this.worldObj.rand.nextFloat() * this.width * 2.0F - this.width,
this.posY + 0.5D,
this.posZ + this.worldObj.rand.nextFloat() * this.width * 2.0F - this.width,
0.0D, 0.25D, 0.0D, new int[0]);
}
if (d <= 25)
{
this.worldObj.spawnParticle(EnumParticleTypes.SMOKE_NORMAL,
this.posX + this.worldObj.rand.nextFloat() * this.width * 2.0F - this.width,
this.posY + 0.5D,
this.posZ + this.worldObj.rand.nextFloat() * this.width * 2.0F - this.width,
0.0D, 0.0D, 0.0D, new int[0]);
}
}
}
}
}
|
Weisses/Ebonheart-Mods
|
ViesCraft/Archived/zzz - PreCapabilities - src/main/java/com/viesis/viescraft/common/entity/airshipitems/v3/EntityItemAirshipV3Orange.java
|
Java
|
mit
| 2,673 |
return function test() {
console.log('executed');
window.close();
};
|
bebraw/libumd
|
tests/data/browser.js
|
JavaScript
|
mit
| 78 |
import notify from 'osg/notify';
import utils from 'osg/utils';
import BoundingBox from 'osg/BoundingBox';
import { vec3, mat4 } from 'osg/glMatrix';
var BoundingSphere = function() {
this._center = vec3.create();
this._radius = -1.0;
};
utils.createPrototypeObject(
BoundingSphere,
{
init: function() {
vec3.init(this._center);
this._radius = -1.0;
},
valid: function() {
return this._radius >= 0.0;
},
set: function(center, radius) {
this._center = center;
this._radius = radius;
},
center: function() {
return this._center;
},
radius: function() {
return this._radius;
},
radius2: function() {
return this._radius * this._radius;
},
volume: function() {
var r = this._radius;
return r * r * r * Math.PI * 4 / 3;
},
copy: function(other) {
this._radius = other._radius;
vec3.copy(this._center, other._center);
},
copyBoundingBox: function(box) {
box.center(this._center);
this._radius = box.radius();
},
expandByBoundingBox: (function() {
var v = vec3.create();
var newbb = new BoundingBox();
return function(bb) {
if (!bb.valid()) return;
if (!this.valid()) {
this.copyBoundingBox(bb);
return;
}
vec3.copy(newbb._min, bb._min);
vec3.copy(newbb._max, bb._max);
for (var i = 0; i < 8; i++) {
vec3.sub(v, bb.corner(i, v), this._center); // get the direction vector from corner
vec3.normalize(v, v); // normalise it.
vec3.scaleAndAdd(v, this._center, v, -this._radius); // move the vector in the opposite direction distance radius.
newbb.expandByVec3(v); // add it into the new bounding box.
}
newbb.center(this._center);
this._radius = newbb.radius();
};
})(),
expandByvec3: function(v) {
notify.warn('deprecated, use expandByVec3');
this.expandByVec3(v);
},
expandByVec3: (function() {
var dv = vec3.create();
return function(v) {
if (this.valid()) {
vec3.sub(dv, v, this.center(dv));
var r = vec3.length(dv);
if (r > this.radius()) {
var dr = (r - this.radius()) * 0.5;
this._center[0] += dv[0] * (dr / r);
this._center[1] += dv[1] * (dr / r);
this._center[2] += dv[2] * (dr / r);
this._radius += dr;
}
} else {
this._center[0] = v[0];
this._center[1] = v[1];
this._center[2] = v[2];
this._radius = 0.0;
}
};
})(),
expandRadiusBySphere: function(sh) {
if (sh.valid()) {
if (this.valid()) {
var r = vec3.distance(this._center, sh._center) + sh._radius;
if (r > this._radius) {
this._radius = r;
}
// else do nothing as vertex is within sphere.
} else {
vec3.copy(this._center, sh._center);
this._radius = sh._radius;
}
}
},
expandByBoundingSphere: function(sh) {
// ignore operation if incomming BoundingSphere is invalid.
if (!sh.valid()) {
return;
}
// This sphere is not set so use the inbound sphere
if (!this.valid()) {
this._center[0] = sh._center[0];
this._center[1] = sh._center[1];
this._center[2] = sh._center[2];
this._radius = sh.radius();
return;
}
// Calculate d == The distance between the sphere centers
var d = vec3.distance(sh.center(), this.center());
// New sphere is already inside this one
if (d + sh.radius() <= this.radius()) {
return;
}
// New sphere completely contains this one
if (d + this.radius() <= sh.radius()) {
this._center[0] = sh._center[0];
this._center[1] = sh._center[1];
this._center[2] = sh._center[2];
this._radius = sh._radius;
return;
}
// Build a new sphere that completely contains the other two:
//
// The center point lies halfway along the line between the furthest
// points on the edges of the two spheres.
//
// Computing those two points is ugly - so we'll use similar triangles
var newRadius = (this.radius() + d + sh.radius()) * 0.5;
var ratio = (newRadius - this.radius()) / d;
this._center[0] += (sh._center[0] - this._center[0]) * ratio;
this._center[1] += (sh._center[1] - this._center[1]) * ratio;
this._center[2] += (sh._center[2] - this._center[2]) * ratio;
this._radius = newRadius;
},
contains: function(v) {
if (!this.valid()) return false;
return vec3.sqrDist(this.center(), v) <= this.radius2();
},
intersects: function(bs) {
if (!this.valid() || !bs.valid()) return false;
var r = this.radius() + bs.radius();
return vec3.sqrDist(bs.center(), this.center()) <= r * r;
},
transformMat4: (function() {
var scaleVec = vec3.create();
return function(out, matrix) {
if (!this.valid()) return out;
if (out._center !== this._center) {
vec3.copy(out._center, this._center);
out._radius = this._radius;
}
var sphCenter = out._center;
var sphRadius = out._radius;
mat4.getSqrScale(scaleVec, matrix);
var scale = Math.sqrt(Math.max(Math.max(scaleVec[0], scaleVec[1]), scaleVec[2]));
sphRadius = sphRadius * scale;
out._radius = sphRadius;
vec3.transformMat4(sphCenter, sphCenter, matrix);
return out;
};
})()
},
'osg',
'BoundingSphere'
);
export default BoundingSphere;
|
jtorresfabra/osgjs
|
sources/osg/BoundingSphere.js
|
JavaScript
|
mit
| 6,862 |
const Project = require('../constructors/Project.js');
const ANNProject = require('../constructors/ANNProject.js');
const Synaptic = require('synaptic');
const Architect = Synaptic.Architect;
const Layer = Synaptic.Layer;
const Network = Synaptic.Network;
const Trainer = Synaptic.Trainer;
// ProjectController is responsible for creating and terminating
// projects. It also routes incoming socket messages to the appropriate
// Project object.
class ProjectController {
constructor(db, io) {
// Stores all Project objects in existence. It has the following form:
// { projectId1: Project1,
// projectId2: Project2 }
this.allProjects = {};
this.pendingProjects = {};
this.pendingProjects['0'] = {
projectId: '0',
title: 'My Project',
dataSet: '[0, 1, 2, 3]',
generateDataSet: '',
mapData: '(val) => {return val;}',
reduceResults: '(results) => {return results;}'
};
// Time between database backups
this.backUpTime = 10000;
/***************************************************
// Query database for projects, intialize a Project
// for each entry, and populate this.allProjects obj
***************************************************/
db.Project.findAll({}).then((projects) => {
projects.forEach((project) => {
let data = project.dataValues;
let options = {
projectType: data.projectType,
title: data.title,
complete: data.complete,
projectTime: data.projectTime,
dataSet: data.dataSet,
generateDataSet: data.generateDataSet,
completedJobs: JSON.parse(data.completedJobs),
mapData: data.mapData,
reduceResults: data.reduceResults,
finalResult: JSON.parse(data.finalResult),
inputLayer: data.inputLayer ? data.inputLayer : 0,
hiddenLayer: data.hiddenLayer ? JSON.parse(data.hiddenLayer) : '',
outputLayer: data.outputLayer ? data.outputLayer : 0,
trainerOptions: data.trainerOptions ? JSON.parse(data.trainerOptions) : ''
};
if (data.projectType === 'ANN') {
this.allProjects[data.projectId] = new ANNProject(options, data.projectId, io);
} else {
this.allProjects[data.projectId] = new Project(options, data.projectId, io);
}
});
/***************************************************
// Iterate over projects in this.allProjects object
// and save to the database once per minute
***************************************************/
setInterval((() => {
return () => {
// First clear out the database
db.Project.destroy({
where: {}
// Then resave all projects
}).then(() => {
for (var obj in this.allProjects) {
let project = this.allProjects[obj];
db.Project.create({
projectId: project.projectId,
projectType: project.projectType,
title: project.title,
complete: project.complete,
projectTime: project.projectTime,
dataSet: project.dataSet,
generateDataSet: project.generateDataSet,
completedJobs: JSON.stringify(project.completedJobs),
mapData: project.mapData,
reduceResults: project.reduceResults,
finalResult: JSON.stringify(project.finalResult),
inputLayer: project.inputLayer ? project.inputLayer : 0,
hiddenLayer: project.hiddenLayer ? JSON.stringify(project.hiddenLayer) : '',
outputLayer: project.outputLayer ? project.outputLayer : 0,
trainerOptions: project.trainerOptions ? JSON.stringify(project.trainerOptions) : ''
});
}
});
};
})(), this.backUpTime);
});
/***************************************************
// Query database for pending projects and populate
// the this.pendingProjects object
***************************************************/
db.PendingProject.findAll({}).then((pendingProjects) => {
pendingProjects.forEach((pending) => {
let data = pending.dataValues;
let options = {
projectId: data.projectId,
title: data.title,
dataSet: data.dataSet,
generateDataSet: data.generateDataSet,
mapData: data.mapData,
reduceResults: data.reduceResults
};
this.pendingProjects[data.projectId] = options;
});
// **************************************************
// // Iterate over projects in this.allProjects object
// // and save to the database once per minute
// **************************************************
setInterval((() => {
return () => {
// First clear out the database
db.PendingProject.destroy({
where: {}
// Then resave all projects
}).then(() => {
for (var obj in this.pendingProjects) {
let pending = this.pendingProjects[obj];
db.PendingProject.create({
projectId: pending.projectId,
title: pending.title,
dataSet: pending.dataSet,
generateDataSet: pending.generateDataSet,
mapData: pending.mapData,
reduceResults: pending.reduceResults
});
}
});
};
})(), this.backUpTime);
});
// Keeps a record of all Worker instances in existence.
// Socket id is used to log workers because the Worker object
// uses socket id as the worker id. The ledger stores the project id
// rather than a reference to the Worker object itself.
// It has the following form:
// { socketId1: projectId,
// socketId2: projectId }
this.allWorkers = {};
this.io = io;
}
/*
======================
SOCKETROUTES.JS EVENTS
======================
*/
userDisconnect(socketId) {
// Identifies the project that the disconnected user was contributing to
// and calls the removeWorker method for that project
if (this.allWorkers[socketId] !== undefined) {
console.log('Removing user from global workers list:', socketId);
this.allProjects[this.allWorkers[socketId]].removeWorker(socketId);
delete this.allWorkers[socketId];
return socketId;
} else {
// User not found
console.log('Project controller could not find that user', socketId);
return false;
}
}
userReady(readyMessage, callback) {
// Passes the new user's socket connection to the appropriate Project,
// which will then create a new Worker for that user and assign it
// an available job
const project = this.allProjects[readyMessage.projectId];
console.log('USER READY FOR:', project.projectType);
if (project) {
// Creates a new Worker in the appropriate Project
const newWorker = project.createWorker(readyMessage);
// Create a record of the new Worker in the allWorkers ledger
this.allWorkers[newWorker.workerId] = project.projectId;
// Assign the new worker as many jobs as the worker can handle
for (var i = 0; i < newWorker.maxJobs; i++) {
const newJob = project.assignJob(newWorker)
if (newJob) {
callback(newJob);
}
}
} else {
console.log('Error in userReady: Project does not exist');
}
}
userJobDone(job, callback) {
// The Job object will be returned from the client with the .result
// field populated.
let projectComplete = false;
const project = this.allProjects[job.projectId];
const worker = project.workers[job.workerId];
if (project && worker) {
// // Check first whether project and worker associated with job exists
// // then pass the job object to the appropriate project object
// console.log('User ' + job.workerId + ' completed a job: ' + job);
// projectComplete = this.allProjects[job.projectId].handleResult(job);
projectComplete = project.handleResult(job);
if (projectComplete) {
project.completeProject();
this.completeProject();
} else {
// Assign jobs to the worker
const newJob = project.assignJob(worker);
if (newJob) {
callback(newJob);
}
}
} else {
if (!project) {
console.log('Error in userJobDone: project does not exist');
}
if (!worker) {
console.log('Error in userJobDone: worker does not exist');
}
}
}
/*
NEURAL NETWORK HANDLERS
*/
updateANN(doneJob) {
console.log('Updating partial networks');
const partialNetwork = doneJob.result.trainedNetwork;
const project = this.allProjects[doneJob.projectId];
let networksSynchronized = false;
project.partialNetworks.push(partialNetwork);
project.workers[doneJob.workerId].isBusy = false;
// Check if all workers are busy
let readyToSync = true;
for (let worker in project.workers) {
if (project.workers[worker].isBusy === true) {
console.log('There are still busy workers in this project');
readyToSync = false;
}
}
if (!readyToSync) {
console.log('Not ready to sync');
return networksSynchronized;
}
if (readyToSync) {
const trainedNetwork = this.syncNetworks(project.partialNetworks);
const result = project.testNetwork(trainedNetwork);
// evaluate the error rate and continue is necessary
// otherwise complete project
if (result.error < project.trainerOptions.error) {
console.log('Desired error rate reached. Training complete.');
console.log('Final error rate:', result.error);
this.completeProject(result);
} else {
console.log('Error rate too high - continuing training:', result.error);
project.updateNetwork(trainedNetwork);
project.partialNetworks = [];
networksSynchronized = true;
return networksSynchronized;
}
}
}
syncNetworks(partialNetworks) {
console.log(`Synchronizing ${partialNetworks.length} networks`);
for (var i = 1; i < partialNetworks.length; i++) {
for (var j = 0; j < partialNetworks[0].connections.length; j++) {
partialNetworks[0].connections[j].weight =
partialNetworks[0].connections[j].weight +
partialNetworks[i].connections[j].weight;
}
}
console.log('Reconciled the weights of partial networks');
return partialNetworks[0];
}
restartANN(projectId, ANNJobCallback) {
console.log('Resetting ANN project');
const project = this.allProjects[projectId];
project.resetTrainingSet();
project.completedJobs = [];
console.log('Reinitialized jobs:', project.availableJobs.length);
for (var key in project.workers) {
const worker = project.workers[key];
worker.currentJob = [];
for (var i = 0; i < worker.maxJobs; i++) {
project.workers[key].currentJob = [];
ANNJobCallback(key, project.assignJob(project.workers[key]) );
}
}
}
/*
PROJECT MANAGEMENT METHODS
*/
createProject(options) {
// Create a new instance of Project with the pass-in options parameters
// Assign a project ID to the new Project and create a new Project
const projectId = 'project' + Object.keys(this.allProjects).length;
let newProject;
if (options.projectType === 'ANN') {
newProject = new ANNProject(options, projectId);
} else {
newProject = new Project(options, projectId);
}
// Store the newly created project in the allProjects object
this.allProjects[projectId] = newProject;
return projectId;
}
pendProject(options) {
// Add to list of pending projects
const id = Object.keys(this.pendingProjects).length;
this.pendingProjects[id] = options;
return true;
}
removePendingProject(projectId) {
delete this.pendingProjects[projectId];
return true;
}
getPendingProjects() {
return this.pendingProjects;
}
// Returns status of projects to all connected users
getUpdateAllProjects() {
let allProjectsUpdate = [];
// Initialize project update information
for (var key in this.allProjects) {
const project = this.allProjects[key];
const completedJobs = [];
project.completedJobs.map( (item) => {
completedJobs.push(item);
});
// WorkersList: [ Worker1, Worker2 ]
const workersList = [];
for (var k in project.workers) {
workersList.push({
workerId: project.workers[k].workerId,
projectId: project.workers[k].projectId,
jobId: project.workers[k].currentJob === null ? null : project.workers[k].currentJob.jobId
});
}
const finalResult = [];
finalResult.push(project.finalResult);
allProjectsUpdate.push({
projectId: project.projectId,
projectType: project.projectType,
title: project.title,
availableJobsNum: project.availableJobs.length,
jobsLength: project.jobsLength,
completedJobs: completedJobs,
workers: workersList,
finalResult: project.finalResult,
complete: project.complete,
projectTime: project.projectTime
});
}
return allProjectsUpdate;
}
completeProject(finalResult) {
console.log('Project done. Final result:', finalResult);
}
}
module.exports = ProjectController;
|
clayhan/rally
|
server/controllers/projectController.js
|
JavaScript
|
mit
| 13,671 |
export default {
ESC: 27,
PAGE_DOWN: 34,
PAGE_UP: 33,
CURSOR_UP: 38,
CURSOR_DOWN: 40,
CURSOR_LEFT: 37,
CURSOR_RIGHT: 39
};
|
kalendaro/calendula
|
src/js/lib/keycodes.js
|
JavaScript
|
mit
| 151 |
package com.rarchives.ripme.tst.ripper.rippers;
import java.io.IOException;
import java.net.URL;
import com.rarchives.ripme.ripper.rippers.FivehundredpxRipper;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
public class FivehundredpxRipperTest extends RippersTest {
@Test @Disabled("Ripper is broken. See https://github.com/RipMeApp/ripme/issues/438")
public void test500pxAlbum() throws IOException {
FivehundredpxRipper ripper = new FivehundredpxRipper(new URL("https://marketplace.500px.com/alexander_hurman"));
testRipper(ripper);
}
}
|
rephormat/ripme
|
src/test/java/com/rarchives/ripme/tst/ripper/rippers/FivehundredpxRipperTest.java
|
Java
|
mit
| 596 |
<!doctype html>
<html>
<title>npm-stop</title>
<meta http-equiv="content-type" value="text/html;utf-8">
<link rel="stylesheet" type="text/css" href="../../static/style.css">
<link rel="canonical" href="https://www.npmjs.org/doc/api/npm-stop.html">
<script async=true src="../../static/toc.js"></script>
<body>
<div id="wrapper">
<h1><a href="../api/npm-stop.html">npm-stop</a></h1> <p>Stop a package</p>
<h2 id="synopsis">SYNOPSIS</h2>
<pre><code>npm.commands.stop(packages, callback)
</code></pre><h2 id="description">DESCRIPTION</h2>
<p>This runs a package's "stop" script, if one was provided.</p>
<p>npm can run stop on multiple packages. Just specify multiple packages
in the <code>packages</code> parameter.</p>
</div>
<table border=0 cellspacing=0 cellpadding=0 id=npmlogo>
<tr><td style="width:180px;height:10px;background:rgb(237,127,127)" colspan=18> </td></tr>
<tr><td rowspan=4 style="width:10px;height:10px;background:rgb(237,127,127)"> </td><td style="width:40px;height:10px;background:#fff" colspan=4> </td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=4> </td><td style="width:40px;height:10px;background:#fff" colspan=4> </td><td rowspan=4 style="width:10px;height:10px;background:rgb(237,127,127)"> </td><td colspan=6 style="width:60px;height:10px;background:#fff"> </td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=4> </td></tr>
<tr><td colspan=2 style="width:20px;height:30px;background:#fff" rowspan=3> </td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=3> </td><td style="width:10px;height:10px;background:#fff" rowspan=3> </td><td style="width:20px;height:10px;background:#fff" rowspan=4 colspan=2> </td><td style="width:10px;height:20px;background:rgb(237,127,127)" rowspan=2> </td><td style="width:10px;height:10px;background:#fff" rowspan=3> </td><td style="width:20px;height:10px;background:#fff" rowspan=3 colspan=2> </td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=3> </td><td style="width:10px;height:10px;background:#fff" rowspan=3> </td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=3> </td></tr>
<tr><td style="width:10px;height:10px;background:#fff" rowspan=2> </td></tr>
<tr><td style="width:10px;height:10px;background:#fff"> </td></tr>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
<p id="footer">npm-stop — [email protected]</p>
|
wuguanghai45/snpm
|
node_modules/npm.old/html/doc/api/npm-stop.html
|
HTML
|
mit
| 2,909 |
# Stores Spree PAYONE preferences.
#
# The expectation is that this is created once and stored in
# the spree environment.
module Spree
AppConfiguration.class_eval do
preference :payone_merchant_id, :string
preference :payone_payment_portal_id, :string
preference :payone_payment_portal_key, :string
preference :payone_sub_account_id, :string
preference :payone_test_mode, :boolean, :default => true
preference :payone_engine_host, :string, :default => 'localhost:3000'
preference :payone_db_logging_enabled, :boolean, :default => true
preference :payone_file_logging_enabled, :boolean, :default => true
preference :payone_logger_filepath, :string, :default => 'log/spree_payone.log'
end
end
|
asharma-ror/payone
|
app/models/spree/app_configuration_decorator.rb
|
Ruby
|
mit
| 735 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public partial class IOperationTests : SemanticModelTestBase
{
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")]
public void ParameterReference_TupleExpression()
{
string source = @"
class Class1
{
public void M(int x, int y)
{
var tuple = /*<bind>*/(x, x + y)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x, System.Int32)) (Syntax: '(x, x + y)')
NaturalType: (System.Int32 x, System.Int32)
Elements(2):
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x + y')
Left:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
Right:
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y')
";
var expectedDiagnostics = new[] {
// file.cs(6,13): warning CS0219: The variable 'tuple' is assigned but its value is never used
// var tuple = /*<bind>*/(x, x + y)/*</bind>*/;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "tuple").WithArguments("tuple").WithLocation(6, 13)
};
VerifyOperationTreeAndDiagnosticsForTest<TupleExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")]
public void ParameterReference_TupleDeconstruction()
{
string source = @"
class Point
{
public int X { get; }
public int Y { get; }
public Point(int x, int y)
{
X = x;
Y = y;
}
public void Deconstruct(out int x, out int y)
{
x = X;
y = Y;
}
}
class Class1
{
public void M(Point point)
{
/*<bind>*/var (x, y) = point/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int32 x, System.Int32 y)) (Syntax: 'var (x, y) = point')
Left:
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: (System.Int32 x, System.Int32 y)) (Syntax: 'var (x, y)')
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x, System.Int32 y)) (Syntax: '(x, y)')
NaturalType: (System.Int32 x, System.Int32 y)
Elements(2):
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'y')
Right:
IParameterReferenceOperation: point (OperationKind.ParameterReference, Type: Point) (Syntax: 'point')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")]
public void ParameterReference_AnonymousObjectCreation()
{
string source = @"
class Class1
{
public void M(int x, string y)
{
var v = /*<bind>*/new { Amount = x, Message = ""Hello"" + y }/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 Amount, System.String Message>) (Syntax: 'new { Amoun ... ello"" + y }')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'Amount = x')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 Amount, System.String Message>.Amount { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'Amount')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 Amount, System.String Message>, IsImplicit) (Syntax: 'new { Amoun ... ello"" + y }')
Right:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'Message = ""Hello"" + y')
Left:
IPropertyReferenceOperation: System.String <anonymous type: System.Int32 Amount, System.String Message>.Message { get; } (OperationKind.PropertyReference, Type: System.String) (Syntax: 'Message')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 Amount, System.String Message>, IsImplicit) (Syntax: 'new { Amoun ... ello"" + y }')
Right:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '""Hello"" + y')
Left:
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""Hello"") (Syntax: '""Hello""')
Right:
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.String) (Syntax: 'y')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<AnonymousObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")]
public void ParameterReference_QueryExpression()
{
string source = @"
using System.Linq;
using System.Collections.Generic;
struct Customer
{
public string Name { get; set; }
public string Address { get; set; }
}
class Class1
{
public void M(List<Customer> customers)
{
var result = /*<bind>*/from cust in customers
select cust.Name/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable<System.String>) (Syntax: 'from cust i ... t cust.Name')
Expression:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.String> System.Linq.Enumerable.Select<Customer, System.String>(this System.Collections.Generic.IEnumerable<Customer> source, System.Func<Customer, System.String> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.String>, IsImplicit) (Syntax: 'select cust.Name')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from cust in customers')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<Customer>, IsImplicit) (Syntax: 'from cust in customers')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: customers (OperationKind.ParameterReference, Type: System.Collections.Generic.List<Customer>) (Syntax: 'customers')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'cust.Name')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<Customer, System.String>, IsImplicit) (Syntax: 'cust.Name')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'cust.Name')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'cust.Name')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'cust.Name')
ReturnedValue:
IPropertyReferenceOperation: System.String Customer.Name { get; set; } (OperationKind.PropertyReference, Type: System.String) (Syntax: 'cust.Name')
Instance Receiver:
IParameterReferenceOperation: cust (OperationKind.ParameterReference, Type: Customer) (Syntax: 'cust')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")]
public void ParameterReference_ObjectAndCollectionInitializer()
{
string source = @"
using System.Collections.Generic;
internal class Class
{
public int X { get; set; }
public List<int> Y { get; set; }
public Dictionary<int, int> Z { get; set; }
public Class C { get; set; }
public void M(int x, int y, int z)
{
var c = /*<bind>*/new Class() { X = x, Y = { x, y, 3 }, Z = { { x, y } }, C = { X = z } }/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IObjectCreationOperation (Constructor: Class..ctor()) (OperationKind.ObjectCreation, Type: Class) (Syntax: 'new Class() ... { X = z } }')
Arguments(0)
Initializer:
IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: Class) (Syntax: '{ X = x, Y ... { X = z } }')
Initializers(4):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = x')
Left:
IPropertyReferenceOperation: System.Int32 Class.X { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: Class, IsImplicit) (Syntax: 'X')
Right:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
IMemberInitializerOperation (OperationKind.MemberInitializer, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'Y = { x, y, 3 }')
InitializedMember:
IPropertyReferenceOperation: System.Collections.Generic.List<System.Int32> Class.Y { get; set; } (OperationKind.PropertyReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'Y')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: Class, IsImplicit) (Syntax: 'Y')
Initializer:
IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: System.Collections.Generic.List<System.Int32>) (Syntax: '{ x, y, 3 }')
Initializers(3):
IInvocationOperation ( void System.Collections.Generic.List<System.Int32>.Add(System.Int32 item)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'x')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: System.Collections.Generic.List<System.Int32>, IsImplicit) (Syntax: 'Y')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: item) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x')
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IInvocationOperation ( void System.Collections.Generic.List<System.Int32>.Add(System.Int32 item)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'y')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: System.Collections.Generic.List<System.Int32>, IsImplicit) (Syntax: 'Y')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: item) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'y')
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IInvocationOperation ( void System.Collections.Generic.List<System.Int32>.Add(System.Int32 item)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '3')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: System.Collections.Generic.List<System.Int32>, IsImplicit) (Syntax: 'Y')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: item) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '3')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IMemberInitializerOperation (OperationKind.MemberInitializer, Type: System.Collections.Generic.Dictionary<System.Int32, System.Int32>) (Syntax: 'Z = { { x, y } }')
InitializedMember:
IPropertyReferenceOperation: System.Collections.Generic.Dictionary<System.Int32, System.Int32> Class.Z { get; set; } (OperationKind.PropertyReference, Type: System.Collections.Generic.Dictionary<System.Int32, System.Int32>) (Syntax: 'Z')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: Class, IsImplicit) (Syntax: 'Z')
Initializer:
IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: System.Collections.Generic.Dictionary<System.Int32, System.Int32>) (Syntax: '{ { x, y } }')
Initializers(1):
IInvocationOperation ( void System.Collections.Generic.Dictionary<System.Int32, System.Int32>.Add(System.Int32 key, System.Int32 value)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '{ x, y }')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: System.Collections.Generic.Dictionary<System.Int32, System.Int32>, IsImplicit) (Syntax: 'Z')
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: key) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x')
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'y')
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IMemberInitializerOperation (OperationKind.MemberInitializer, Type: Class) (Syntax: 'C = { X = z }')
InitializedMember:
IPropertyReferenceOperation: Class Class.C { get; set; } (OperationKind.PropertyReference, Type: Class) (Syntax: 'C')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: Class, IsImplicit) (Syntax: 'C')
Initializer:
IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: Class) (Syntax: '{ X = z }')
Initializers(1):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = z')
Left:
IPropertyReferenceOperation: System.Int32 Class.X { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: Class, IsImplicit) (Syntax: 'X')
Right:
IParameterReferenceOperation: z (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'z')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")]
public void ParameterReference_DelegateCreationExpressionWithLambdaArgument()
{
string source = @"
using System;
class Class
{
// Used parameter methods
public void UsedParameterMethod1(Action a)
{
Action a2 = /*<bind>*/new Action(() =>
{
a();
})/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'new Action( ... })')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: '() => ... }')
IBlockOperation (2 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a();')
Expression:
IInvocationOperation (virtual void System.Action.Invoke()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'a()')
Instance Receiver:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Action) (Syntax: 'a')
Arguments(0)
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '{ ... }')
ReturnedValue:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")]
public void ParameterReference_DelegateCreationExpressionWithMethodArgument()
{
string source = @"
using System;
class Class
{
public delegate void Delegate(int x, int y);
public void Method(Delegate d)
{
var a = /*<bind>*/new Delegate(Method2)/*</bind>*/;
}
public void Method2(int x, int y)
{
}
}
";
string expectedOperationTree = @"
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: Class.Delegate) (Syntax: 'new Delegate(Method2)')
Target:
IMethodReferenceOperation: void Class.Method2(System.Int32 x, System.Int32 y) (OperationKind.MethodReference, Type: null) (Syntax: 'Method2')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Class, IsImplicit) (Syntax: 'Method2')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")]
public void ParameterReference_DelegateCreationExpressionWithInvalidArgument()
{
string source = @"
using System;
class Class
{
public delegate void Delegate(int x, int y);
public void Method(int x)
{
var a = /*<bind>*/new Delegate(x)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IInvalidOperation (OperationKind.Invalid, Type: Class.Delegate, IsInvalid) (Syntax: 'new Delegate(x)')
Children(1):
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'x')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0149: Method name expected
// var a = /*<bind>*/new Delegate(x)/*</bind>*/;
Diagnostic(ErrorCode.ERR_MethodNameExpected, "x").WithLocation(10, 40)
};
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")]
public void ParameterReference_DynamicCollectionInitializer()
{
string source = @"
using System.Collections.Generic;
internal class Class
{
public dynamic X { get; set; }
public void M(int x, int y)
{
var c = new Class() /*<bind>*/{ X = { { x, y } } }/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: Class) (Syntax: '{ X = { { x, y } } }')
Initializers(1):
IMemberInitializerOperation (OperationKind.MemberInitializer, Type: dynamic) (Syntax: 'X = { { x, y } }')
InitializedMember:
IPropertyReferenceOperation: dynamic Class.X { get; set; } (OperationKind.PropertyReference, Type: dynamic) (Syntax: 'X')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: Class, IsImplicit) (Syntax: 'X')
Initializer:
IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: dynamic) (Syntax: '{ { x, y } }')
Initializers(1):
IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: System.Void) (Syntax: '{ x, y }')
Expression:
IDynamicMemberReferenceOperation (Member Name: ""Add"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: null, IsImplicit) (Syntax: 'X')
Type Arguments(0)
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: dynamic, IsImplicit) (Syntax: 'X')
Arguments(2):
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y')
ArgumentNames(0)
ArgumentRefKinds(0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<InitializerExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")]
public void ParameterReference_NameOfExpression()
{
string source = @"
class Class1
{
public string M(int x)
{
return /*<bind>*/nameof(x)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
INameOfOperation (OperationKind.NameOf, Type: System.String, Constant: ""x"") (Syntax: 'nameof(x)')
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")]
public void ParameterReference_PointerIndirectionExpression()
{
string source = @"
class Class1
{
public unsafe int M(int *x)
{
return /*<bind>*/*x/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IOperation: (OperationKind.None, Type: null) (Syntax: '*x')
Children(1):
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32*) (Syntax: 'x')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0227: Unsafe code may only appear if compiling with /unsafe
// public unsafe int M(int *x)
Diagnostic(ErrorCode.ERR_IllegalUnsafe, "M").WithLocation(4, 23)
};
VerifyOperationTreeAndDiagnosticsForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")]
public void ParameterReference_FixedLocalInitializer()
{
string source = @"
using System.Collections.Generic;
internal class Class
{
public unsafe void M(int[] array)
{
fixed (int* /*<bind>*/p = array/*</bind>*/)
{
*p = 1;
}
}
}
";
string expectedOperationTree = @"
IVariableDeclaratorOperation (Symbol: System.Int32* p) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'p = array')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= array')
IOperation: (OperationKind.None, Type: null, IsImplicit) (Syntax: 'array')
Children(1):
IParameterReferenceOperation: array (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'array')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0227: Unsafe code may only appear if compiling with /unsafe
// public unsafe void M(int[] array)
Diagnostic(ErrorCode.ERR_IllegalUnsafe, "M").WithLocation(6, 24)
};
VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")]
public void ParameterReference_RefTypeOperator()
{
string source = @"
class Class1
{
public System.Type M(System.TypedReference x)
{
return /*<bind>*/__reftype(x)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IOperation: (OperationKind.None, Type: null) (Syntax: '__reftype(x)')
Children(1):
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.TypedReference) (Syntax: 'x')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<RefTypeExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")]
public void ParameterReference_MakeRefOperator()
{
string source = @"
class Class1
{
public void M(System.Type x)
{
var y = /*<bind>*/__makeref(x)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IOperation: (OperationKind.None, Type: null) (Syntax: '__makeref(x)')
Children(1):
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Type) (Syntax: 'x')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<MakeRefExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")]
public void ParameterReference_RefValueOperator()
{
string source = @"
class Class1
{
public void M(System.TypedReference x)
{
var y = /*<bind>*/__refvalue(x, int)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IOperation: (OperationKind.None, Type: null) (Syntax: '__refvalue(x, int)')
Children(1):
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.TypedReference) (Syntax: 'x')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<RefValueExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")]
public void ParameterReference_DynamicIndexerAccess()
{
string source = @"
class Class1
{
public void M(dynamic d, int x)
{
var /*<bind>*/y = d[x]/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IVariableDeclaratorOperation (Symbol: dynamic y) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'y = d[x]')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= d[x]')
IDynamicIndexerAccessOperation (OperationKind.DynamicIndexerAccess, Type: dynamic) (Syntax: 'd[x]')
Expression:
IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd')
Arguments(1):
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
ArgumentNames(0)
ArgumentRefKinds(0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")]
public void ParameterReference_DynamicMemberAccess()
{
string source = @"
class Class1
{
public void M(dynamic x, int y)
{
var z = /*<bind>*/x.M(y)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'x.M(y)')
Expression:
IDynamicMemberReferenceOperation (Member Name: ""M"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: dynamic) (Syntax: 'x.M')
Type Arguments(0)
Instance Receiver:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'x')
Arguments(1):
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y')
ArgumentNames(0)
ArgumentRefKinds(0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")]
public void ParameterReference_DynamicInvocation()
{
string source = @"
class Class1
{
public void M(dynamic x, int y)
{
var z = /*<bind>*/x(y)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'x(y)')
Expression:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'x')
Arguments(1):
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y')
ArgumentNames(0)
ArgumentRefKinds(0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")]
public void ParameterReference_DynamicObjectCreation()
{
string source = @"
internal class Class
{
public Class(Class x) { }
public Class(string x) { }
public void M(dynamic x)
{
var c = /*<bind>*/new Class(x)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDynamicObjectCreationOperation (OperationKind.DynamicObjectCreation, Type: Class) (Syntax: 'new Class(x)')
Arguments(1):
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'x')
ArgumentNames(0)
ArgumentRefKinds(0)
Initializer:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")]
public void ParameterReference_StackAllocArrayCreation()
{
string source = @"
using System.Collections.Generic;
internal class Class
{
public unsafe void M(int x)
{
int* block = /*<bind>*/stackalloc int[x]/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IOperation: (OperationKind.None, Type: null) (Syntax: 'stackalloc int[x]')
Children(1):
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0227: Unsafe code may only appear if compiling with /unsafe
// public unsafe void M(int x)
Diagnostic(ErrorCode.ERR_IllegalUnsafe, "M").WithLocation(6, 24)
};
VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")]
public void ParameterReference_InterpolatedStringExpression()
{
string source = @"
using System;
internal class Class
{
public void M(string x, int y)
{
Console.WriteLine(/*<bind>*/$""String {x,20} and {y:D3} and constant {1}""/*</bind>*/);
}
}
";
string expectedOperationTree = @"
IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""String {x ... nstant {1}""')
Parts(6):
IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'String ')
Text:
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""String "", IsImplicit) (Syntax: 'String ')
IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{x,20}')
Expression:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.String) (Syntax: 'x')
Alignment:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20')
FormatString:
null
IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: ' and ')
Text:
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "" and "", IsImplicit) (Syntax: ' and ')
IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{y:D3}')
Expression:
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y')
Alignment:
null
FormatString:
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""D3"") (Syntax: ':D3')
IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: ' and constant ')
Text:
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "" and constant "", IsImplicit) (Syntax: ' and constant ')
IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{1}')
Expression:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Alignment:
null
FormatString:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<InterpolatedStringExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")]
public void ParameterReference_ThrowExpression()
{
string source = @"
using System;
internal class Class
{
public void M(string x)
{
var y = x ?? /*<bind>*/throw new ArgumentNullException(nameof(x))/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IThrowOperation (OperationKind.Throw, Type: null) (Syntax: 'throw new A ... (nameof(x))')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, IsImplicit) (Syntax: 'new Argumen ... (nameof(x))')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IObjectCreationOperation (Constructor: System.ArgumentNullException..ctor(System.String paramName)) (OperationKind.ObjectCreation, Type: System.ArgumentNullException) (Syntax: 'new Argumen ... (nameof(x))')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: paramName) (OperationKind.Argument, Type: null) (Syntax: 'nameof(x)')
INameOfOperation (OperationKind.NameOf, Type: System.String, Constant: ""x"") (Syntax: 'nameof(x)')
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.String) (Syntax: 'x')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Initializer:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ThrowExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")]
public void ParameterReference_PatternSwitchStatement()
{
string source = @"
internal class Class
{
public void M(int x)
{
switch (x)
{
/*<bind>*/case var y when (x >= 10):
break;/*</bind>*/
}
}
}
";
string expectedOperationTree = @"
ISwitchCaseOperation (1 case clauses, 1 statements) (OperationKind.SwitchCase, Type: null) (Syntax: 'case var y ... break;')
Locals: Local_1: System.Int32 y
Clauses:
IPatternCaseClauseOperation (Label Id: 0) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null) (Syntax: 'case var y ... (x >= 10):')
Pattern:
IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'var y') (InputType: System.Int32, DeclaredSymbol: System.Int32 y, MatchesNull: True)
Guard:
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'x >= 10')
Left:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
Body:
IBranchOperation (BranchKind.Break, Label Id: 1) (OperationKind.Branch, Type: null) (Syntax: 'break;')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<SwitchSectionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")]
public void ParameterReference_DefaultPatternSwitchStatement()
{
string source = @"
internal class Class
{
public void M(int x)
{
switch (x)
{
case var y when (x >= 10):
break;
/*<bind>*/default:/*</bind>*/
break;
}
}
}
";
string expectedOperationTree = @"
IDefaultCaseClauseOperation (Label Id: 0) (CaseKind.Default) (OperationKind.CaseClause, Type: null) (Syntax: 'default:')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<DefaultSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")]
public void ParameterReference_UserDefinedLogicalConditionalOperator()
{
string source = @"
class A<T>
{
public static bool operator true(A<T> o) { return true; }
public static bool operator false(A<T> o) { return false; }
}
class B : A<object>
{
public static B operator &(B x, B y) { return x; }
}
class C : B
{
public static C operator |(C x, C y) { return x; }
}
class P
{
static void M(C x, C y)
{
if (/*<bind>*/x && y/*</bind>*/)
{
}
}
}
";
string expectedOperationTree = @"
IBinaryOperation (BinaryOperatorKind.ConditionalAnd) (OperatorMethod: B B.op_BitwiseAnd(B x, B y)) (OperationKind.Binary, Type: B) (Syntax: 'x && y')
Left:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: B, IsImplicit) (Syntax: 'x')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: C) (Syntax: 'x')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: B, IsImplicit) (Syntax: 'y')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: C) (Syntax: 'y')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")]
[ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)]
public void ParameterReference_NoPiaObjectCreation()
{
var sources0 = @"
using System;
using System.Runtime.InteropServices;
[assembly: ImportedFromTypeLib(""_.dll"")]
[assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")]
[ComImport()]
[Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58277"")]
[CoClass(typeof(C))]
public interface I
{
int P { get; set; }
}
[Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58278"")]
public class C
{
public C(object o)
{
}
}
";
var sources1 = @"
struct S
{
public I F(object x)
{
return /*<bind>*/new I(x)/*</bind>*/;
}
}
";
var compilation0 = CreateCompilation(sources0);
compilation0.VerifyDiagnostics();
var compilation1 = CreateEmptyCompilation(
sources1,
references: new[] { MscorlibRef, SystemRef, compilation0.EmitToImageReference(embedInteropTypes: true) });
string expectedOperationTree = @"
INoPiaObjectCreationOperation (OperationKind.None, Type: I, IsInvalid) (Syntax: 'new I(x)')
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// (6,25): error CS1729: 'I' does not contain a constructor that takes 1 arguments
// return /*<bind>*/new I(x)/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "(x)").WithArguments("I", "1").WithLocation(6, 25)
};
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(compilation1, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")]
public void ParameterReference_ArgListOperator()
{
string source = @"
using System;
class C
{
static void Method(int x, bool y)
{
M(1, /*<bind>*/__arglist(x, y)/*</bind>*/);
}
static void M(int x, __arglist)
{
}
}
";
string expectedOperationTree = @"
IOperation: (OperationKind.None, Type: null) (Syntax: '__arglist(x, y)')
Children(2):
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'y')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(19790, "https://github.com/dotnet/roslyn/issues/19790")]
public void ParameterReference_IsPatternExpression()
{
string source = @"
class Class1
{
public void Method1(object x)
{
if (/*<bind>*/x is int y/*</bind>*/) { }
}
}
";
string expectedOperationTree = @"
IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'x is int y')
Value:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'x')
Pattern:
IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'int y') (InputType: System.Object, DeclaredSymbol: System.Int32 y, MatchesNull: False)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(19902, "https://github.com/dotnet/roslyn/issues/19902")]
public void ParameterReference_LocalFunctionStatement()
{
string source = @"
using System;
using System.Collections.Generic;
class Class
{
static IEnumerable<T> MyIterator<T>(IEnumerable<T> source, Func<T, bool> predicate)
{
/*<bind>*/IEnumerable<T> Iterator()
{
foreach (var element in source)
if (predicate(element))
yield return element;
}/*</bind>*/
return Iterator();
}
}
";
string expectedOperationTree = @"
ILocalFunctionOperation (Symbol: System.Collections.Generic.IEnumerable<T> Iterator()) (OperationKind.LocalFunction, Type: null) (Syntax: 'IEnumerable ... }')
IBlockOperation (2 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'foreach (va ... rn element;')
Locals: Local_1: T element
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: T element) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'var')
Initializer:
null
Collection:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<T>, IsImplicit) (Syntax: 'source')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: source (OperationKind.ParameterReference, Type: System.Collections.Generic.IEnumerable<T>) (Syntax: 'source')
Body:
IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'if (predica ... rn element;')
Condition:
IInvocationOperation (virtual System.Boolean System.Func<T, System.Boolean>.Invoke(T arg)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'predicate(element)')
Instance Receiver:
IParameterReferenceOperation: predicate (OperationKind.ParameterReference, Type: System.Func<T, System.Boolean>) (Syntax: 'predicate')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: arg) (OperationKind.Argument, Type: null) (Syntax: 'element')
ILocalReferenceOperation: element (OperationKind.LocalReference, Type: T) (Syntax: 'element')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
WhenTrue:
IReturnOperation (OperationKind.YieldReturn, Type: null) (Syntax: 'yield return element;')
ReturnedValue:
ILocalReferenceOperation: element (OperationKind.LocalReference, Type: T) (Syntax: 'element')
WhenFalse:
null
NextVariables(0)
IReturnOperation (OperationKind.YieldBreak, Type: null, IsImplicit) (Syntax: '{ ... }')
ReturnedValue:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<LocalFunctionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
}
}
|
abock/roslyn
|
src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IParameterReferenceExpression.cs
|
C#
|
mit
| 54,357 |
/**
* \file
*
* \brief Metering Application Emulator for Base Node
*
* Copyright (c) 2014 Atmel Corporation. All rights reserved.
*
* \asf_license_start
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. The name of Atmel may not be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* 4. This software may only be redistributed and used in connection with an
* Atmel microcontroller product.
*
* THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
* EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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.
*
* \asf_license_stop
*
*
*/
/* System includes */
/**
* Support and FAQ: visit <a href="http://www.atmel.com/design-support/">Atmel Support</a>
*/
#include <stdio.h>
#include <string.h>
/* Prime includes */
#include "asf.h"
/* Application includes */
#include "app_emu_common.h"
#include "conf_app_emu.h"
extern uint32_t ul_tens_of_ms;
/* *** Declarations ************************************************************
**/
/* Tasks priorities */
#define TASK_APPEMU_LAYER_PRIO (tskIDLE_PRIORITY + 1)
/* Stack definitions */
#define TASK_APPEMU_LAYER_STACK (configMINIMAL_STACK_SIZE * 4)
/* Main Task Period */
#define APPEMU_TIMER_RATE (5 / portTICK_RATE_MS)
/* Update Timer Period */
#define UPDATE_APPEMU_TIMER_RATE (1 / portTICK_RATE_MS)
#define MAX_TBL_NODE_NUM 64
#define IDCHAR_BASE '5'
#define IDCHAR_SERVICE '6'
#define IDCHAR_CON_BASE '7'
#define IDCHAR_CON_SERVICE '8'
/* Modulation scheme of the payload: Differential BPSK */
#define PROTOCOL_DBPSK 0x00
/* Modulation scheme of the payload: Differential QPSK */
#define PROTOCOL_DQPSK 0x01
/* Modulation scheme of the payload: Differential 8PSK */
#define PROTOCOL_D8PSK 0x02
/* Modulation scheme of the payload: Differential BPSK with Convolutional Coding */
#define PROTOCOL_DBPSK_VTB 0x04
/* Modulation scheme of the payload: Differential QPSK with Convolutional Coding */
#define PROTOCOL_DQPSK_VTB 0x05
/* Modulation scheme of the payload: Differential 8PSK with Convolutional Coding */
#define PROTOCOL_D8PSK_VTB 0x06
/* Time from the last connection detected to start test */
#define TIMETO_START_TEST 500L /* 75 seconds in 10ms. */
#define TIMETO_REG_CHEK 100 /* 1 second in 10ms. */
/* Value of the Register Devices list */
#define MLME_LIST_REG_DEVICES 0x50
/* Values of communications */
#define MLME_LIST_PHY_COMM 0x57
/* Maximum test defined */
#define NUM_TEST 10 /* Tecnalia 20130502 */
/* Retries for a test */
#define NUM_RETRIES 3
#define VTB(A) (A & 0x04)
#define MOD(A) (A & 0x03)
#define _getTimeMs() (ul_tens_of_ms * 10)
/* State of machine state _get_registered_nodes */
enum {
MLME_SEND_REQUEST,
MLME_WAIT_ANSWER
};
/* State of appemu_Process */
enum {
APPEMU_WAIT_NEW_CONNECTIONS,
APPEMU_GET_NODES_REGISTERED,
APPEMU_WAITTO_START_TEST,
/* All test states must be listed under APPEMU_START_TEST (to reject
* connections during test) */
APPEMU_START_TEST,
APPEMU_WAIT_RECEIVED_TXCODING,
APPEMU_BUILD_MESSAGE_TEST,
APPEMU_SEND_MESSAGE_TEST,
APPEMU_WAIT_CONFIRM_MESSAGE_TEST,
APPEMU_WAIT_RECEIVE_MESSAGE_TEST,
APPEMU_RETRY_MESSAGE_TEST,
APPEMU_END_TEST_NODE,
APPEMU_DISCONNECT_NODES
};
/* *** Static Variables ********************************************************
**/
/* Definition of the stored fields required by appEmu */
typedef struct {
uint16_t us_handler; /* Handler of the connection */
uint8_t puc_mac_addr[PRIME_MAC_LENGTH]; /* Mac address of the connected node */
uint32_t ul_nid; /* NID of the node */
uint8_t puc_serial[SERIAL_SIZE + 1]; /* String with the serial number */
uint32_t ul_start_time_test; /* Ini of the test in Hundred of miliseconds, since base node is started */
uint32_t pul_round_trip[NUM_TEST]; /* Time from a petition is done until the answer is received */
uint8_t puc_success_attempt[NUM_TEST]; /* Number of successfully attempt */
uint8_t uc_rx_coding; /* Reception scheme */
uint8_t uc_tx_coding; /* Transmission scheme */
uint8_t uc_app_emu_coding; /* Transmission mode */
} test_node;
/* Definition of the test */
typedef struct {
uint8_t uc_test_number; /* Step of the test, to fill up the message */
uint16_t us_bytes_sent; /* Bytes sent by the Base Node */
uint16_t us_bytes_expected; /* Bytes expected in the answer */
} test_info;
typedef struct {
uint8_t uc_n_attempts;
uint32_t ul_round_trip_time;
} type_result;
typedef struct {
uint32_t ul_nid;
uint8_t puc_serial[SERIAL_SIZE + 1];
uint32_t ul_start_time;
type_result step_result[N_LENGTHS_TEST];
} type_report;
typedef struct {
uint8_t puc_serial[SERIAL_SIZE + 1];
} type_meter_serial;
/* Test battery to execute */
static test_info p_conf_test [NUM_TEST + 1] = {
{2, 24, 36},
{3, 24, 31},
{4, 75, 138},
{4, 16, 52},
{5, 17, 17},
{5, 29, 29},
{5, 65, 65},
{5, 137, 137},
{5, 209, 209},
{5, 281, 281},
/* End of table */
{0xff, 0, 0}
};
/* Array with the test node */
test_node p_node[MAX_TBL_NODE_NUM];
/* State of the proccess _get_registered_nodes */
static uint8_t uc_get_nodes_st;
/* State of the proccess _info_tx_coding */
static uint8_t uc_info_tx_coding_st;
/* State of the proccess appemu_Process */
static uint8_t uc_app_emu_st;
/* Pointer to the new command */
static MacSapCallBack *p_counter_new_cmd;
/* Temporal storage for the last command extracted */
static MacSapCallBack tmp_new_cmd;
/* Number of connections opened */
static uint16_t us__num_connections;
/* Number of nodes register in the base node */
static uint16_t us__num_nodes_registered;
/* Device under test */
static uint16_t us__dut;
/* Number of test en execution */
static uint16_t us__numTest;
/* Number of attempt for the current test */
static uint8_t uc__num_attempt;
/* String where the time is stored */
static char pc_time_stamp[TIMESTAMP_SIZE + 1];
/* Var where the payload is built */
static uint8_t puc_request[MAX_COUNTER_DATA_SIZE + 1];
/* Boolean to get registered nodes */
static Bool b_check_reg;
extern uint32_t ul_time_app_emu;
extern uint32_t ul_mili_seconds;
static uint8_t _most_robust_scheme_mode(uint8_t uc_sch1, uint8_t uc_sch2);
void appemu_init(void);
/* ************************************************************************** */
/** @brief give us the time in hundreds of Miliseconds, take into acount
* if the counter has been reset
* @param ul_end_time
* @param ul_ini_time
*
* @return Real value in tenths of seconds
*
**************************************************************************/
static uint32_t _get_round_trip(uint32_t ul_end_time, uint32_t ul_ini_time)
{
uint32_t ul_result;
if (ul_end_time < ul_ini_time) {
ul_result = ul_end_time + (0xffffffff - ul_ini_time);
} else {
ul_result = ul_end_time - ul_ini_time;
}
return ul_result;
}
/* ************************************************************************** */
/** @brief This function updates the var us__num_nodes_registered
* calling the MLME interface
**************************************************************************/
static void _update_nid(MlmeRegDevice *p_dev)
{
uint8_t i;
for (i = 0; i < us__num_connections; i++) {
if (memcmp(&p_node[i].puc_mac_addr[0], &p_dev->mac[0], PRIME_MAC_LENGTH) == 0) {
/* Update NID */
p_node[i].ul_nid = ((uint32_t)p_dev->sid & 0x000000ff) << 14;
p_node[i].ul_nid |= ((uint32_t)p_dev->lnid & 0x00003fff);
}
}
}
/* ************************************************************************** */
/** @brief This function updates the var uc_tx_coding and uc_rx_coding
* from structure Nodes
* @param pr_comm pointer to MlmePhyCommDevice
**************************************************************************/
static void _update_tx_rx_coding(MlmePhyCommDevice *pr_comm)
{
uint8_t i;
for (i = 0; i < us__num_connections; i++) {
if (memcmp(&p_node[i].puc_mac_addr[0], &pr_comm->eui48[0], PRIME_MAC_LENGTH) == 0) {
/* Update uc_tx_coding */
p_node[i].uc_tx_coding = pr_comm->txCodingMod;
p_node[i].uc_rx_coding = pr_comm->rxCodingMod;
}
}
}
/* ************************************************************************** */
/** @brief This function updates the var uc_tx_coding and uc_rx_coding
* from structure Nodes
**************************************************************************/
static void _fill_tx_rx_coding_undirect_nodes(void)
{
uint8_t i;
for (i = 0; i < us__num_connections; i++) {
if (p_node[i].uc_rx_coding == 0) {
/* Update uc_tx_coding */
p_node[i].uc_tx_coding = PROTOCOL_DBPSK_VTB;
p_node[i].uc_rx_coding = PROTOCOL_DBPSK_VTB;
}
}
}
/* ************************************************************************** */
/** @brief it choose the most robust mode to transmit to node
**************************************************************************/
static void _choose_app_emu_coding(void)
{
uint8_t i;
for (i = 0; i < us__num_connections; i++) {
p_node[i].uc_app_emu_coding = _most_robust_scheme_mode(p_node[i].uc_rx_coding,
p_node[i].uc_tx_coding);
#ifdef APPEMU_DEBUG
printf("%s\tModeAppEmu:%hu\n", p_node[i].puc_serial,
(uint16_t)p_node[i].uc_app_emu_coding);
#endif
}
}
/* ************************************************************************** */
/** @brief Prints the shcemes for all the nodes, ONLY in debug mode
**************************************************************************/
#ifdef _CS_DEBUG_
static void _print_all_schemes(void)
{
uint8_t i;
for (i = 0; i < us__num_connections; i++) {
#ifdef APPEMU_DEBUG
printf("%s\trxCoding:%u\ttxCoding:%u\n", p_node[i].puc_serial,
(uint16_t)p_node[i].uc_rx_coding,
(uint16_t)p_node[i].uc_tx_coding);
#endif
}
}
#endif
/* ************************************************************************** */
/** @brief This function updates the var us__num_nodes_registered
*
* @return 1 when it finishes
* 0 In other case
*
* This function updates the us__num_nodes_registered calling the MLME
* interface
**************************************************************************/
static int _get_registered_nodes(void)
{
MlmeListGetRegDevices list;
int i;
int result = 0;
switch (uc_get_nodes_st) {
case MLME_SEND_REQUEST:
#ifdef APPEMU_DEBUG
printf("Getting MLME_LIST_REG_DEVICES\n");
#endif
if (prime_MLME_LIST_GET_request(MLME_LIST_REG_DEVICES) == 0) {
us__num_nodes_registered = 0;
uc_get_nodes_st = MLME_WAIT_ANSWER;
}
break;
case MLME_WAIT_ANSWER:
if (prime_MLME_callback((uint8_t *)&list)) {
/* Check that is a valid answer */
if ((list.cmd == PRIME_MLME_LIST_GET_CONFIRM) &&
(list.pibAttrib == MLME_LIST_REG_DEVICES)) {
for (i = 0; i < list.numItems; i++) {
/* Updates the NID for the connected nodes */
_update_nid(&list.dev[i]);
}
us__num_nodes_registered += list.numItems;
}
/* Next time we start againg in MLMEGET_SEND_REQUEST or
* retry now */
if (list.isLast) {
#ifdef APPEMU_DEBUG
printf("End list get MLME_LIST_REG_DEVICES\n");
#endif
uc_get_nodes_st = MLME_SEND_REQUEST;
if (list.result == PRIME_MLME_RESULT_SUCCESS) {
result = 1;
}
}
}
break;
}
return result;
}
/* ************************************************************************** */
/** @brief This function updates the var us__num_nodes_registered
*
* @return 1 when it finishes
* 0 In other case
*
* This function updates the us__num_nodes_registered calling the MLME
* interface
**************************************************************************/
static int _info_tx_coding(void)
{
MlmeListGetPhyCommTable list;
int i;
int result = 0;
switch (uc_info_tx_coding_st) {
case MLME_SEND_REQUEST:
#ifdef APPEMU_DEBUG
printf("Getting MLME_LIST_PHY_COMM\n");
#endif
if (prime_MLME_LIST_GET_request(MLME_LIST_PHY_COMM) == 0) {
us__num_nodes_registered = 0;
uc_info_tx_coding_st = MLME_WAIT_ANSWER;
}
break;
case MLME_WAIT_ANSWER:
if (prime_MLME_callback((uint8_t *)&list)) {
/* Check that is a valid answer */
if ((list.cmd == PRIME_MLME_LIST_GET_CONFIRM) &&
(list.pibAttrib == MLME_LIST_PHY_COMM)) {
for (i = 0; i < list.numItems; i++) {
/* Updates the NID for the connected nodes */
_update_tx_rx_coding(&list.dev[i]);
}
us__num_nodes_registered += list.numItems;
}
/* Next time we start againg in MLMEGET_SEND_REQUEST or
* retry now */
if (list.isLast) {
#ifdef APPEMU_DEBUG
printf("End list get MLME_LIST_PHY_COMM\n");
#endif
uc_info_tx_coding_st = MLME_SEND_REQUEST;
/* Fill up the rest of nodes */
_fill_tx_rx_coding_undirect_nodes();
_choose_app_emu_coding();
#ifdef _CS_DEBUG_
_print_all_schemes();
#endif
result = 1;
}
}
break;
}
return result;
}
/* ************************************************************************** */
/** @brief It decides if a new incomming connection has to be aceppted or
* rejected
*
* @param p_cmd pointer to the incomming message
*
* It is based in two criteria, first, if the node has already an open
* connection
* Second if the test has already started. In these two cases the connection is
* rejected. It will be aceppted in other case
**************************************************************************/
static void _check_new_connections(MacSapCallBack *p_cmd)
{
uint16_t i;
for (i = 0; i < us__num_connections; i++) {
if (memcmp(&p_node[i].puc_mac_addr[0], &p_cmd->macAddr[0], PRIME_MAC_LENGTH) == 0) {
break;
}
}
/* There was a connection previously open or we are in the middle of
* test */
if (uc_app_emu_st >= APPEMU_START_TEST) {
if (i < us__num_connections) {
p_node[i].us_handler = CON_HANDLER_INIT_VALUE;
p_node[i].puc_serial[0] = '\0';
p_node[i].ul_start_time_test = 0;
}
#ifdef APPEMU_DEBUG
printf("Rejecting connection with node %hu\n", i + 1);
#endif
prime_MAC_ESTABLISH_response(p_cmd->handler, PRIME_MACSAP_RESULT_REJECT, NULL, 0);
} else {
#ifdef APPEMU_DEBUG
printf("Accepting connection with node %hu\n", i + 1);
#endif
prime_MAC_ESTABLISH_response(p_cmd->handler, PRIME_MACSAP_RESULT_ACCEPT, NULL, 0);
p_node[i].us_handler = p_cmd->handler;
memcpy(&p_node[i].puc_serial[0], &p_cmd->buf[0], p_cmd->bufLength);
memcpy(&p_node[i].puc_mac_addr[0], &p_cmd->macAddr[0], PRIME_MAC_LENGTH);
/* Only increment connections if it is a new connection */
if (i == us__num_connections) {
us__num_connections++;
}
}
}
/* ************************************************************************** */
/** @brief Sends the results of the tests in the node dut
*
* @param us_dut Device under Test
**************************************************************************/
static void _send_result_node(uint16_t us_dut)
{
uint8_t i;
static uint8_t msg[1024];
#ifdef __GNUC__
sprintf((char *)msg, "%08lx,%s,%lu \n",
p_node[us_dut].ul_nid,
p_node[us_dut].puc_serial,
p_node[us_dut].ul_start_time_test);
#endif
#ifdef __ICCARM__
sprintf((char *)msg, "%08x,%s,%u \n",
p_node[us_dut].ul_nid,
p_node[us_dut].puc_serial,
p_node[us_dut].ul_start_time_test);
#endif
for (i = 0; i < NUM_TEST; i++) {
#ifdef __GNUC__
sprintf((char *)&msg[ strlen((char *)msg)], ",%hu,%lu \n",
(uint16_t)p_node[us_dut].puc_success_attempt[i],
p_node[us_dut].pul_round_trip[i]);
#endif
#ifdef __ICCARM__
sprintf((char *)&msg[ strlen((char *)msg)], ",%hu,%u \n",
(uint16_t)p_node[us_dut].puc_success_attempt[i],
p_node[us_dut].pul_round_trip[i]);
#endif
}
sprintf((char *)&msg[strlen((char *)msg)], "%c%c \n", 10, 13);
printf("%s", msg);
}
/* ************************************************************************** */
/** @brief Most robust Scheme module between the two given
*
* @param uc_sch1 modulation scheme 1
* @param uc_sch2 modulation scheme 2
*
* @return Most robust Scheme module between the two given
**************************************************************************/
static uint8_t _most_robust_scheme_mode(uint8_t uc_sch1, uint8_t uc_sch2)
{
uint8_t mostRobustMode;
if (VTB(uc_sch1) != VTB(uc_sch2)) {
if (VTB(uc_sch1)) {
mostRobustMode = uc_sch1;
} else {
mostRobustMode = uc_sch2;
}
} else {
if (uc_sch1 < uc_sch2) {
mostRobustMode = uc_sch1;
} else {
mostRobustMode = uc_sch2;
}
}
return mostRobustMode;
}
/* ************************************************************************** */
/** @brief Get length of the transmission
*
* @param us_dut
* @param pus_num_test
* @param pus_len_rx
*
* @return transmission length
*
**************************************************************************/
static uint16_t _get_length_transmission(uint16_t us_dut,
uint16_t *pus_num_test, uint16_t *pus_len_rx)
{
uint16_t us_len_tx;
if (p_conf_test[*pus_num_test].uc_test_number < 5) {
us_len_tx = p_conf_test[*pus_num_test].us_bytes_sent;
*pus_len_rx = p_conf_test[*pus_num_test].us_bytes_expected;
} else { /* Test Number == 5, adapt transmission and reception */
if ((MOD(p_node[us_dut].uc_app_emu_coding) == PROTOCOL_D8PSK) &&
(p_conf_test[*pus_num_test].us_bytes_expected == 17)) {
*pus_num_test = *pus_num_test + 1;
}
if (VTB(p_node[us_dut].uc_app_emu_coding)) {
us_len_tx = p_conf_test[*pus_num_test].us_bytes_sent;
} else {
us_len_tx = (p_conf_test[*pus_num_test].us_bytes_sent + 1);
}
*pus_len_rx = us_len_tx;
}
return us_len_tx;
}
/* ************************************************************************** */
/** @brief End test with current node
*
* Check if dut is the last one and then change state machine to disconnect
* all nodes
**************************************************************************/
static void _end_dut(void)
{
if (++us__dut >= us__num_connections) {
#ifdef APPEMU_DEBUG
printf("Disconnecting %i nodes\n", us__num_connections);
#endif
us__dut = 0;
uc_app_emu_st = APPEMU_DISCONNECT_NODES;
} else {
uc_app_emu_st = APPEMU_START_TEST;
}
}
/* *** Public Functions ******************************************************
**/
/* ************************************************************************** */
/** @brief Init application emulation
*
* This function initializes the application
**************************************************************************/
void appemu_init(void)
{
uint8_t mac[6];
mac[0] = 0x00;
mac[1] = 0x01;
mac[2] = 0x02;
mac[3] = 0x03;
mac[4] = 0x04;
mac[5] = 0x05;
app_emu_init_random(mac);
}
/* ************************************************************************** */
/** @brief Start application emulation
*
* This function initializes variables for application
**************************************************************************/
void app_emu_start()
{
uint16_t i;
/* Init appemu Vars */
uc_get_nodes_st = MLME_SEND_REQUEST;
uc_info_tx_coding_st = MLME_SEND_REQUEST;
uc_app_emu_st = APPEMU_WAIT_NEW_CONNECTIONS;
us__num_connections = 0;
us__num_nodes_registered = 0;
b_check_reg = false;
for (i = 0; i < MAX_TBL_NODE_NUM; i++) {
p_node[i].us_handler = CON_HANDLER_INIT_VALUE;
p_node[i].puc_mac_addr[0] = '\0';
p_node[i].ul_nid = 0;
p_node[i].puc_serial[0] = '\0';
p_node[i].ul_start_time_test = 0;
memset(p_node[i].pul_round_trip, 0, NUM_TEST);
memset(p_node[i].puc_success_attempt, 0, NUM_TEST);
p_node[i].uc_rx_coding = PROTOCOL_DBPSK_VTB;
p_node[i].uc_tx_coding = PROTOCOL_DBPSK_VTB;
p_node[i].uc_app_emu_coding = PROTOCOL_DBPSK_VTB;
}
}
/* ************************************************************************** */
/** @brief app Emu main proccess
*
*
**************************************************************************/
void app_emu_process()
{
Bool b_new_command = false;
static uint16_t us_length_transmission;
static uint16_t us_length_reception;
/* Reception of Mac primitives */
if (prime_MAC_callback(&tmp_new_cmd, GENERIC_CALLBACK_HANDLER, GENERIC_CALLBACK_TYPE)) {
p_counter_new_cmd = &tmp_new_cmd;
b_new_command = true;
/* New connection checking if there is new nodw or not */
switch (p_counter_new_cmd->command) {
case PRIME_MACSAP_ESTABLISH_INDICATION:
#ifdef APPEMU_DEBUG
printf("<- ESTABLISH_indication()\n");
#endif
_check_new_connections(p_counter_new_cmd);
b_check_reg = true;
b_new_command = false;
break;
case PRIME_MACSAP_RELEASE_INDICATION:
if (p_counter_new_cmd->answer == PRIME_MACSAP_RESULT_ERROR) {
#ifdef APPEMU_DEBUG
printf( "APPEMU abnormally aborted with node %hu\n", us__dut);
#endif
_end_dut();
} else {
prime_MAC_RELEASE_response(p_counter_new_cmd->handler, PRIME_MACSAP_RESULT_ACCEPT);
}
break;
case PRIME_MACSAP_RELEASE_CONFIRM:
#ifdef APPEMU_DEBUG
printf("Release confirm %hu with node %hu\n",
(uint16_t)p_counter_new_cmd->errorType,
us__dut);
#endif
if (p_counter_new_cmd->errorType != PRIME_MACSAP_ERROR_TIMEOUT) {
#ifdef APPEMU_DEBUG
printf("APPEMU closed with node %hu\n", us__dut);
#endif
}
break;
}
}
if (b_check_reg) {
if (_get_registered_nodes()) {
b_check_reg = false;
}
}
switch (uc_app_emu_st) {
case APPEMU_WAIT_NEW_CONNECTIONS:
if (us__num_connections) {
ul_time_app_emu = TIMETO_START_TEST;
uc_app_emu_st = APPEMU_WAITTO_START_TEST;
}
break;
case APPEMU_WAITTO_START_TEST:
if (!ul_time_app_emu) {
us__dut = 0;
uc_app_emu_st = APPEMU_START_TEST;
}
break;
case APPEMU_START_TEST:
#ifdef APPEMU_DEBUG
printf("---INIT TEST : %i nodes connected---\n", us__num_connections);
printf("Getting information for transmission Schemes\n");
#endif
uc_app_emu_st = APPEMU_WAIT_RECEIVED_TXCODING;
break;
case APPEMU_WAIT_RECEIVED_TXCODING:
if (_info_tx_coding()) {
us__numTest = 0;
p_node[us__dut].ul_start_time_test = _getTimeMs();
uc_app_emu_st = APPEMU_BUILD_MESSAGE_TEST;
}
break;
case APPEMU_BUILD_MESSAGE_TEST:
uc__num_attempt = 1;
app_emu_build_timestamp(pc_time_stamp);
us_length_transmission = _get_length_transmission(us__dut, &us__numTest, &us_length_reception);
app_emu_fill_string((char *)puc_request, us_length_transmission, DW_MSG,
p_conf_test[us__numTest].uc_test_number, pc_time_stamp);
uc_app_emu_st = APPEMU_SEND_MESSAGE_TEST;
ul_time_app_emu = 0;
break;
case APPEMU_SEND_MESSAGE_TEST:
if (p_node[us__dut].us_handler == CON_HANDLER_INIT_VALUE) {
_end_dut();
} else {
#ifdef APPEMU_DEBUG
printf("-> Sending data to node %hu...\n", us__dut + 1);
#endif
prime_MAC_DATA_request(p_node[us__dut].us_handler, puc_request, us_length_transmission, 1);
#ifdef APPEMU_DEBUG
printf("%s: Test:%i\tAttempt:%i\tSent:%i\t\n",
p_node[us__dut].puc_serial,
(uint16_t)us__numTest,
(uint16_t)uc__num_attempt,
(uint16_t)p_conf_test[us__numTest].us_bytes_sent);
#endif
p_node[us__dut].pul_round_trip[us__numTest] = _getTimeMs();
p_node[us__dut].puc_success_attempt[us__numTest] = uc__num_attempt;
uc_app_emu_st = APPEMU_WAIT_CONFIRM_MESSAGE_TEST;
ul_time_app_emu = TIME_REPEAT;
}
break;
case APPEMU_WAIT_CONFIRM_MESSAGE_TEST:
if (b_new_command) {
b_new_command = false;
if (p_counter_new_cmd->command == PRIME_MACSAP_DATA_CONFIRM) {
if (p_counter_new_cmd->answer == PRIME_MACSAP_RESULT_SUCCESS) {
uc_app_emu_st = APPEMU_WAIT_RECEIVE_MESSAGE_TEST;
} else {
switch (p_counter_new_cmd->errorType) {
case PRIME_MACSAP_ERROR_TIMEOUT:
#ifdef APPEMU_DEBUG
printf("Timeout. Retrying page...\n");
#endif
uc_app_emu_st = APPEMU_RETRY_MESSAGE_TEST;
break;
case PRIME_MACSAP_ERROR_TX_BUSY:
case PRIME_MACSAP_ERROR_NO_ACKED:
#ifdef APPEMU_DEBUG
printf("ARQ transmission error %hu. Retrying packet...\n",
(uint16_t)p_counter_new_cmd->errorType);
#endif
uc_app_emu_st = APPEMU_RETRY_MESSAGE_TEST;
break;
case PRIME_MACSAP_ERROR_INVALID_HANDLER:
#ifdef APPEMU_DEBUG
printf("Warning: Invalid Handler %hu %hu\n",
p_counter_new_cmd->handler, (uint16_t)p_counter_new_cmd->type);
#endif
if (p_counter_new_cmd->handler == p_node[us__dut].us_handler) {
_end_dut();
} else {
uc_app_emu_st = APPEMU_RETRY_MESSAGE_TEST;
}
break;
case PRIME_MACSAP_ERROR_NOT_REGISTERED:
default:
#ifdef APPEMU_DEBUG
printf("ErrorType %hu\n",
(uint16_t)(p_counter_new_cmd->errorType));
#endif
_end_dut();
break;
}
}
}
}
if (!ul_time_app_emu) {
uc_app_emu_st = APPEMU_RETRY_MESSAGE_TEST;
}
break;
case APPEMU_WAIT_RECEIVE_MESSAGE_TEST:
if (b_new_command) {
b_new_command = false;
if ((p_counter_new_cmd->command == PRIME_MACSAP_DATA_INDICATION) &&
(p_counter_new_cmd->handler == p_node[us__dut].us_handler)) {
/* It is the expected message */
if (p_counter_new_cmd->bufLength == us_length_reception) {
/* Good message, Next Test */
p_node[us__dut].pul_round_trip[us__numTest] = _get_round_trip(_getTimeMs(), p_node[us__dut].pul_round_trip[us__numTest]);
/* check it is not the last test of the node */
#ifdef APPEMU_DEBUG
printf( "<- Received data from node %hu ... OK\n", us__dut + 1);
printf("Received:%i\n", p_conf_test[us__numTest].us_bytes_expected);
#endif
if (p_conf_test[++us__numTest].uc_test_number != 0xFF) {
uc_app_emu_st = APPEMU_BUILD_MESSAGE_TEST;
} else {
uc_app_emu_st = APPEMU_END_TEST_NODE;
}
} else {
/* Bad message, Retry */
uc_app_emu_st = APPEMU_RETRY_MESSAGE_TEST;
#ifdef APPEMU_DEBUG
printf( "<- Received data from node %hu ... FAIL\n", us__dut + 1);
#endif
}
}
}
if (!ul_time_app_emu) {
uc_app_emu_st = APPEMU_RETRY_MESSAGE_TEST;
}
break;
case APPEMU_RETRY_MESSAGE_TEST:
#ifdef APPEMU_DEBUG
printf("Received:FAIL\n");
#endif
if (uc__num_attempt++ < NUM_RETRIES) {
uc_app_emu_st = APPEMU_SEND_MESSAGE_TEST;
} else {
/* Test Fail, next test */
#ifdef APPEMU_DEBUG
printf("---TEST FAILED---\n");
#endif
p_node[us__dut].pul_round_trip[us__numTest] = 0;
p_node[us__dut].puc_success_attempt[us__numTest] = 0;
/* check it is not the last test of the node */
if (p_conf_test[++us__numTest].uc_test_number != 0xFF) {
uc_app_emu_st = APPEMU_BUILD_MESSAGE_TEST;
} else {
uc_app_emu_st = APPEMU_END_TEST_NODE;
}
}
break;
case APPEMU_END_TEST_NODE:
/* Send through serial line test results */
#ifdef APPEMU_DEBUG
printf("TEST RESULT [%s]:\n", p_node[us__dut].puc_serial);
#endif
_send_result_node(us__dut);
_end_dut();
break;
case APPEMU_DISCONNECT_NODES:
#ifdef APPEMU_DEBUG
printf("Closing connection with node %hu\n", us__dut + 1);
#endif
prime_MAC_RELEASE_request(p_node[us__dut].us_handler);
p_node[us__dut].us_handler = CON_HANDLER_INIT_VALUE;
p_node[us__dut].puc_serial[0] = '\0';
p_node[us__dut].ul_start_time_test = 0;
if (++us__dut >= us__num_connections) {
#ifdef APPEMU_DEBUG
printf("All nodes disconnected: Restart\n");
#endif
us__num_connections = 0;
uc_app_emu_st = APPEMU_WAIT_NEW_CONNECTIONS;
}
break;
}
}
|
femtoio/femto-usb-blink-example
|
blinky/blinky/asf-3.21.0/thirdparty/prime/apps/prime_base_appemu/app_emu_base.c
|
C
|
mit
| 28,759 |
<!doctype html>
<!--[if lt IE 7]><html class="no-js lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]-->
<!--[if (IE 7)&!(IEMobile)]><html class="no-js lt-ie9 lt-ie8" lang="en"><![endif]-->
<!--[if (IE 8)&!(IEMobile)]><html class="no-js lt-ie9" lang="en"><![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en"><!--<![endif]-->
<head>
{% include head.html %}
</head>
<body id="post" {% if page.image.feature %}class="feature"{% endif %}>
{% include browser-upgrade.html %}
{% include header.html %}
<div id="main" role="main">
<article class="hentry hentry-dark">
<div class="entry-content">
{% if page.image.feature %}
<div class="entry-image-index">
<img src="{{ site.url }}/images/{{ page.image.feature }}" alt="{{ page.title }}">
{% if page.image.credit %}<div class="image-credit">Image source: <a target="_blank" href="{{ page.image.creditlink }}">{{ page.image.credit }}</a></div><!-- /.image-credit -->{% endif %}
</div>
{% endif %}
<h1 class="post-title entry-title">{{ page.title }}</h1>
{{ content }}
<footer class="entry-meta">
<span class="entry-tags">{% for tag in page.tags %}<a href="{{ site.url }}/tags#{{ tag }}" title="Pages tagged {{ tag }}" class="tag"><span class="term">{{ tag }}</span></a>{% unless forloop.last %}{% endunless %}{% endfor %}</span>
{% if page.modified %}<span>Updated on <span class="entry-date date updated"><time datetime="{{ page.modified }}">{{ page.modified | date: "%B %d, %Y" }}</time></span></span>
{% endif %}
<span class="author vcard"><span class="fn">{% if page.author.name %}{{ page.author.name }}{% else %}{{ site.owner.name }}{% endif %}</span></span>
{% if page.share != false %}{% include social-share.html %}{% endif %}
</footer>
</div><!-- /.entry-content -->
{% include author.html %}
{% if page.comments != false and site.disqus_shortname %}<section id="disqus_thread"></section><!-- /#disqus_thread -->{% endif %}
{% if site.related_posts.size > 0 %}{% include read-more.html %}{% endif %}
</article>
</div><!-- /#main -->
{% include scripts.html %}
<div class="footer-wrapper">
<footer role="contentinfo">
{% include footer.html %}
</footer>
</div><!-- /.footer-wrapper -->
</body>
</html>
|
skhu-sw/blog
|
_layouts/dark-post.html
|
HTML
|
mit
| 2,315 |
use std::io;
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use ogg::{OggTrackBuf};
use super::super::{RequestType, Request};
use ::proto::{self, Deserialize, Serialize};
/// Skips to the end of the currently playing track
#[derive(Clone)]
pub struct ReplaceFallbackRequest {
pub track: OggTrackBuf,
pub metadata: Option<Vec<(String, String)>>,
}
impl Deserialize for ReplaceFallbackRequest {
fn read(buf: &mut io::Cursor<Vec<u8>>) -> io::Result<Self> {
try!(proto::expect_type(buf, proto::TYPE_STRUCT));
let field_count = try!(buf.read_u32::<BigEndian>());
let mut track: Option<Vec<u8>> = None;
let mut metadata: Option<Vec<(String, String)>> = None;
for _ in 0..field_count {
let field_name: String = try!(Deserialize::read(buf));
match &field_name[..] {
"track" => {
track = Some(try!(Deserialize::read(buf)));
},
"metadata" => {
metadata = Some(try!(Deserialize::read(buf)));
}
_ => try!(proto::skip_entity(buf)),
}
}
let track = match track {
Some(track) => track,
None => return Err(io::Error::new(io::ErrorKind::Other, "missing field: track")),
};
let track = try!(OggTrackBuf::new(track)
.map_err(|_| io::Error::new(io::ErrorKind::Other, "invalid ogg")));
Ok(ReplaceFallbackRequest {
track: track,
metadata: metadata,
})
}
}
impl Serialize for ReplaceFallbackRequest {
fn write(&self, buf: &mut io::Cursor<Vec<u8>>) -> io::Result<()> {
try!(buf.write_u16::<BigEndian>(proto::TYPE_STRUCT));
let length = if self.metadata.is_some() { 2 } else { 1 };
try!(buf.write_u32::<BigEndian>(length));
try!(Serialize::write("track", buf));
try!(Serialize::write(self.track.as_u8_slice(), buf));
if let Some(ref metadata) = self.metadata {
try!(Serialize::write("metadata", buf));
try!(Serialize::write(&metadata[..], buf));
}
Ok(())
}
}
impl Request for ReplaceFallbackRequest {
type Value = ();
type Error = ReplaceFallbackError;
fn req_type(&self) -> RequestType {
RequestType::ReplaceFallback
}
}
pub type ReplaceFallbackResult = Result<(), ReplaceFallbackError>;
#[derive(Debug, Clone)]
pub enum ReplaceFallbackError {
InvalidTrack = 1,
BadSampleRate = 2,
Full = 3,
}
impl ReplaceFallbackError {
pub fn to_u32(&self) -> u32 {
self.clone() as u32
}
pub fn from_u32(val: u32) -> Option<ReplaceFallbackError> {
match val {
1 => Some(ReplaceFallbackError::InvalidTrack),
2 => Some(ReplaceFallbackError::BadSampleRate),
3 => Some(ReplaceFallbackError::Full),
_ => None
}
}
}
impl Deserialize for ReplaceFallbackError {
fn read(buf: &mut io::Cursor<Vec<u8>>) -> io::Result<Self> {
let num: u32 = try!(Deserialize::read(buf));
ReplaceFallbackError::from_u32(num)
.ok_or_else(|| {
io::Error::new(io::ErrorKind::Other, "unexpected ReplaceFallbackError value")
})
}
}
impl Serialize for ReplaceFallbackError {
fn write(&self, buf: &mut io::Cursor<Vec<u8>>) -> io::Result<()> {
try!(Serialize::write(&self.to_u32(), buf));
Ok(())
}
}
|
infinityb/ireul
|
ireul_interface/src/proxy/track/replace_fallback.rs
|
Rust
|
mit
| 3,489 |
/**
*
*/
package net.jsunit;
class MockMessageReceiver implements MessageReceiver {
public String message;
public void messageReceived(String message) {
this.message = message;
}
}
|
wesmaldonado/test-driven-javascript-example-application
|
public/js-common/jsunit/java/tests_core/net/jsunit/MockMessageReceiver.java
|
Java
|
mit
| 220 |
TEST vuln-44.attack
This test checks for the vulnerability in webgoat titled Off-by-One Overflows under the Buffer Overflows section.
It will return a
- 1 (error) if the vulnerability is present
- 0 (success) if the vulnerability is fixed (aka not present)
This test assumes 3 things:
(1) That the python package Requests is installed
```
$ sudo apt-get install python-pip; sudo pip install requests
```
(2) Gauntlt is being run from the base of the repo. For example, if you cloned the repo into /home/hacker,
the current working directory when running gauntlet should be /home/hacker/gauntlt-demo/
(3) There is a local proxy running on 127.0.0.1:8888
Testing vuln-44 can be done outside of Gauntlt by navigating to the webgoat/vuln-44 directory and running:
```
$ python attack.py
```
This Gauntlt test was written by Patrick Aupperle and Ousek Son from team Admin on Thu, 10 Dec 2015
|
gauntlt/gauntlt-demo
|
examples/webgoat/vuln-44/README.md
|
Markdown
|
mit
| 933 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.5.0_06) on Mon Mar 27 19:55:48 EST 2006 -->
<TITLE>
Uses of Interface Environment
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
parent.document.title="Uses of Interface Environment";
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../Environment.html" title="interface in <Unnamed>"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../index.html?class-useEnvironment.html" target="_top"><B>FRAMES</B></A>
<A HREF="Environment.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Interface<br>Environment</B></H2>
</CENTER>
<A NAME=""><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../Environment.html" title="interface in <Unnamed>">Environment</A> in <A HREF="../package-summary.html"><Unnamed></A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Classes in <A HREF="../package-summary.html"><Unnamed></A> that implement <A HREF="../Environment.html" title="interface in <Unnamed>">Environment</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../BoundedEnv.html" title="class in <Unnamed>">BoundedEnv</A></B></CODE>
<BR>
Dean Attali<br>
March 10, 2006<br><br>
This class is a modified version of the BoundedEnv from the
Marine Biologist Simulation</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../SquareEnvironment.html" title="class in <Unnamed>">SquareEnvironment</A></B></CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../Environment.html" title="interface in <Unnamed>"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../index.html?class-useEnvironment.html" target="_top"><B>FRAMES</B></A>
<A HREF="Environment.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
</BODY>
</HTML>
|
vivekbhanot/vivekbhanot.github.io
|
files/java/Scrabble/doc/class-use/Environment.html
|
HTML
|
mit
| 6,591 |
require 'data/rating'
class Topic
include DataMapper::Resource
property :id, Serial
property :name, String
property :description, String
remix n, My::Nested::Remixable::Rating,
:as => :ratings_for_topic,
:model => "Rating"
end
|
datamapper/dm-is-remixable
|
spec/data/topic.rb
|
Ruby
|
mit
| 250 |
---
title: Obelisk
repo: BennyHallett/obelisk
homepage: https://github.com/BennyHallett/obelisk
language:
- Elixir
license:
- MIT
templates:
- EEx
- Haml
description: Static Site Generator written in Elixir.
---
Obelisk is a static site generator written in [Elixir Programming Language](http://elixir-lang.org).
#### Goals
- **Fast**. Static websites can take a long time to generate when they start to grow large. obelisk should take advantage of Elixir's processes to increase this speed.
- **Simple, Obvious.** It should be very straight forward to add new content and modify the way that your site works.
- **Templatable.** It should be possible to store templates in github repos and reference them directly, allowing modification of the look and feel of a site instantaneously with no manual installation.
|
netlify/staticgen
|
content/projects/obelisk.md
|
Markdown
|
mit
| 824 |
/*
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2020, assimp team
All rights reserved.
Redistribution and use of this software 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.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
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.
----------------------------------------------------------------------
*/
/** @file glTFAsset.h
* Declares a glTF class to handle gltf/glb files
*
* glTF Extensions Support:
* KHR_binary_glTF: full
* KHR_materials_common: full
*/
#ifndef GLTFASSET_H_INC
#define GLTFASSET_H_INC
#ifndef ASSIMP_BUILD_NO_GLTF_IMPORTER
#include <assimp/Exceptional.h>
#include <map>
#include <string>
#include <list>
#include <vector>
#include <algorithm>
#include <stdexcept>
#define RAPIDJSON_HAS_STDSTRING 1
#include <rapidjson/rapidjson.h>
#include <rapidjson/document.h>
#include <rapidjson/error/en.h>
#ifdef ASSIMP_API
# include <memory>
# include <assimp/DefaultIOSystem.h>
# include <assimp/ByteSwapper.h>
#else
# include <memory>
# define AI_SWAP4(p)
# define ai_assert
#endif
#if _MSC_VER > 1500 || (defined __GNUC___)
# define ASSIMP_GLTF_USE_UNORDERED_MULTIMAP
# else
# define gltf_unordered_map map
#endif
#ifdef ASSIMP_GLTF_USE_UNORDERED_MULTIMAP
# include <unordered_map>
# if _MSC_VER > 1600
# define gltf_unordered_map unordered_map
# else
# define gltf_unordered_map tr1::unordered_map
# endif
#endif
#include "glTF/glTFCommon.h"
namespace glTF
{
using glTFCommon::shared_ptr;
using glTFCommon::IOSystem;
using glTFCommon::IOStream;
using rapidjson::Value;
using rapidjson::Document;
class Asset;
class AssetWriter;
struct BufferView; // here due to cross-reference
struct Texture;
struct Light;
struct Skin;
using glTFCommon::vec3;
using glTFCommon::vec4;
using glTFCommon::mat4;
//! Magic number for GLB files
#define AI_GLB_MAGIC_NUMBER "glTF"
#ifdef ASSIMP_API
#include <assimp/Compiler/pushpack1.h>
#endif
//! For the KHR_binary_glTF extension (binary .glb file)
//! 20-byte header (+ the JSON + a "body" data section)
struct GLB_Header
{
uint8_t magic[4]; //!< Magic number: "glTF"
uint32_t version; //!< Version number (always 1 as of the last update)
uint32_t length; //!< Total length of the Binary glTF, including header, scene, and body, in bytes
uint32_t sceneLength; //!< Length, in bytes, of the glTF scene
uint32_t sceneFormat; //!< Specifies the format of the glTF scene (see the SceneFormat enum)
} PACK_STRUCT;
#ifdef ASSIMP_API
#include <assimp/Compiler/poppack1.h>
#endif
//! Values for the GLB_Header::sceneFormat field
enum SceneFormat
{
SceneFormat_JSON = 0
};
//! Values for the mesh primitive modes
enum PrimitiveMode
{
PrimitiveMode_POINTS = 0,
PrimitiveMode_LINES = 1,
PrimitiveMode_LINE_LOOP = 2,
PrimitiveMode_LINE_STRIP = 3,
PrimitiveMode_TRIANGLES = 4,
PrimitiveMode_TRIANGLE_STRIP = 5,
PrimitiveMode_TRIANGLE_FAN = 6
};
//! Values for the Accessor::componentType field
enum ComponentType
{
ComponentType_BYTE = 5120,
ComponentType_UNSIGNED_BYTE = 5121,
ComponentType_SHORT = 5122,
ComponentType_UNSIGNED_SHORT = 5123,
ComponentType_UNSIGNED_INT = 5125,
ComponentType_FLOAT = 5126
};
inline unsigned int ComponentTypeSize(ComponentType t)
{
switch (t) {
case ComponentType_SHORT:
case ComponentType_UNSIGNED_SHORT:
return 2;
case ComponentType_UNSIGNED_INT:
case ComponentType_FLOAT:
return 4;
case ComponentType_BYTE:
case ComponentType_UNSIGNED_BYTE:
return 1;
default:
std::string err = "GLTF: Unsupported Component Type ";
err += t;
throw DeadlyImportError(err);
}
}
//! Values for the BufferView::target field
enum BufferViewTarget
{
BufferViewTarget_NONE = 0,
BufferViewTarget_ARRAY_BUFFER = 34962,
BufferViewTarget_ELEMENT_ARRAY_BUFFER = 34963
};
//! Values for the Sampler::magFilter field
enum SamplerMagFilter
{
SamplerMagFilter_Nearest = 9728,
SamplerMagFilter_Linear = 9729
};
//! Values for the Sampler::minFilter field
enum SamplerMinFilter
{
SamplerMinFilter_Nearest = 9728,
SamplerMinFilter_Linear = 9729,
SamplerMinFilter_Nearest_Mipmap_Nearest = 9984,
SamplerMinFilter_Linear_Mipmap_Nearest = 9985,
SamplerMinFilter_Nearest_Mipmap_Linear = 9986,
SamplerMinFilter_Linear_Mipmap_Linear = 9987
};
//! Values for the Sampler::wrapS and Sampler::wrapT field
enum SamplerWrap
{
SamplerWrap_Clamp_To_Edge = 33071,
SamplerWrap_Mirrored_Repeat = 33648,
SamplerWrap_Repeat = 10497
};
//! Values for the Texture::format and Texture::internalFormat fields
enum TextureFormat
{
TextureFormat_ALPHA = 6406,
TextureFormat_RGB = 6407,
TextureFormat_RGBA = 6408,
TextureFormat_LUMINANCE = 6409,
TextureFormat_LUMINANCE_ALPHA = 6410
};
//! Values for the Texture::target field
enum TextureTarget
{
TextureTarget_TEXTURE_2D = 3553
};
//! Values for the Texture::type field
enum TextureType
{
TextureType_UNSIGNED_BYTE = 5121,
TextureType_UNSIGNED_SHORT_5_6_5 = 33635,
TextureType_UNSIGNED_SHORT_4_4_4_4 = 32819,
TextureType_UNSIGNED_SHORT_5_5_5_1 = 32820
};
//! Values for the Accessor::type field (helper class)
class AttribType
{
public:
enum Value
{ SCALAR, VEC2, VEC3, VEC4, MAT2, MAT3, MAT4 };
private:
static const size_t NUM_VALUES = static_cast<size_t>(MAT4)+1;
struct Info
{ const char* name; unsigned int numComponents; };
template<int N> struct data
{ static const Info infos[NUM_VALUES]; };
public:
inline static Value FromString(const char* str)
{
for (size_t i = 0; i < NUM_VALUES; ++i) {
if (strcmp(data<0>::infos[i].name, str) == 0) {
return static_cast<Value>(i);
}
}
return SCALAR;
}
inline static const char* ToString(Value type)
{
return data<0>::infos[static_cast<size_t>(type)].name;
}
inline static unsigned int GetNumComponents(Value type)
{
return data<0>::infos[static_cast<size_t>(type)].numComponents;
}
};
// must match the order of the AttribTypeTraits::Value enum!
template<int N> const AttribType::Info
AttribType::data<N>::infos[AttribType::NUM_VALUES] = {
{ "SCALAR", 1 }, { "VEC2", 2 }, { "VEC3", 3 }, { "VEC4", 4 }, { "MAT2", 4 }, { "MAT3", 9 }, { "MAT4", 16 }
};
//! A reference to one top-level object, which is valid
//! until the Asset instance is destroyed
template<class T>
class Ref
{
std::vector<T*>* vector;
unsigned int index;
public:
Ref() : vector(0), index(0) {}
Ref(std::vector<T*>& vec, unsigned int idx) : vector(&vec), index(idx) {}
inline unsigned int GetIndex() const
{ return index; }
operator bool() const
{ return vector != 0; }
T* operator->()
{ return (*vector)[index]; }
T& operator*()
{ return *((*vector)[index]); }
};
//! Helper struct to represent values that might not be present
template<class T>
struct Nullable
{
T value;
bool isPresent;
Nullable() : isPresent(false) {}
Nullable(T& val) : value(val), isPresent(true) {}
};
//! Base class for all glTF top-level objects
struct Object
{
std::string id; //!< The globally unique ID used to reference this object
std::string name; //!< The user-defined name of this object
//! Objects marked as special are not exported (used to emulate the binary body buffer)
virtual bool IsSpecial() const
{ return false; }
virtual ~Object() {}
//! Maps special IDs to another ID, where needed. Subclasses may override it (statically)
static const char* TranslateId(Asset& /*r*/, const char* id)
{ return id; }
};
//
// Classes for each glTF top-level object type
//
//! A typed view into a BufferView. A BufferView contains raw binary data.
//! An accessor provides a typed view into a BufferView or a subset of a BufferView
//! similar to how WebGL's vertexAttribPointer() defines an attribute in a buffer.
struct Accessor : public Object
{
Ref<BufferView> bufferView; //!< The ID of the bufferView. (required)
unsigned int byteOffset; //!< The offset relative to the start of the bufferView in bytes. (required)
unsigned int byteStride; //!< The stride, in bytes, between attributes referenced by this accessor. (default: 0)
ComponentType componentType; //!< The datatype of components in the attribute. (required)
unsigned int count; //!< The number of attributes referenced by this accessor. (required)
AttribType::Value type; //!< Specifies if the attribute is a scalar, vector, or matrix. (required)
std::vector<double> max; //!< Maximum value of each component in this attribute.
std::vector<double> min; //!< Minimum value of each component in this attribute.
unsigned int GetNumComponents();
unsigned int GetBytesPerComponent();
unsigned int GetElementSize();
inline uint8_t* GetPointer();
template<class T>
bool ExtractData(T*& outData);
void WriteData(size_t count, const void* src_buffer, size_t src_stride);
//! Helper class to iterate the data
class Indexer
{
friend struct Accessor;
Accessor& accessor;
uint8_t* data;
size_t elemSize, stride;
Indexer(Accessor& acc);
public:
//! Accesses the i-th value as defined by the accessor
template<class T>
T GetValue(int i);
//! Accesses the i-th value as defined by the accessor
inline unsigned int GetUInt(int i)
{
return GetValue<unsigned int>(i);
}
inline bool IsValid() const
{
return data != 0;
}
};
inline Indexer GetIndexer()
{
return Indexer(*this);
}
Accessor() {}
void Read(Value& obj, Asset& r);
};
//! A buffer points to binary geometry, animation, or skins.
struct Buffer : public Object
{
/********************* Types *********************/
public:
enum Type
{
Type_arraybuffer,
Type_text
};
/// \struct SEncodedRegion
/// Descriptor of encoded region in "bufferView".
struct SEncodedRegion
{
const size_t Offset;///< Offset from begin of "bufferView" to encoded region, in bytes.
const size_t EncodedData_Length;///< Size of encoded region, in bytes.
uint8_t* const DecodedData;///< Cached encoded data.
const size_t DecodedData_Length;///< Size of decoded region, in bytes.
const std::string ID;///< ID of the region.
/// \fn SEncodedRegion(const size_t pOffset, const size_t pEncodedData_Length, uint8_t* pDecodedData, const size_t pDecodedData_Length, const std::string pID)
/// Constructor.
/// \param [in] pOffset - offset from begin of "bufferView" to encoded region, in bytes.
/// \param [in] pEncodedData_Length - size of encoded region, in bytes.
/// \param [in] pDecodedData - pointer to decoded data array.
/// \param [in] pDecodedData_Length - size of encoded region, in bytes.
/// \param [in] pID - ID of the region.
SEncodedRegion(const size_t pOffset, const size_t pEncodedData_Length, uint8_t* pDecodedData, const size_t pDecodedData_Length, const std::string pID)
: Offset(pOffset), EncodedData_Length(pEncodedData_Length), DecodedData(pDecodedData), DecodedData_Length(pDecodedData_Length), ID(pID)
{}
/// \fn ~SEncodedRegion()
/// Destructor.
~SEncodedRegion() { delete [] DecodedData; }
};
/******************* Variables *******************/
//std::string uri; //!< The uri of the buffer. Can be a filepath, a data uri, etc. (required)
size_t byteLength; //!< The length of the buffer in bytes. (default: 0)
//std::string type; //!< XMLHttpRequest responseType (default: "arraybuffer")
Type type;
/// \var EncodedRegion_Current
/// Pointer to currently active encoded region.
/// Why not decoding all regions at once and not to set one buffer with decoded data?
/// Yes, why not? Even "accessor" point to decoded data. I mean that fields "byteOffset", "byteStride" and "count" has values which describes decoded
/// data array. But only in range of mesh while is active parameters from "compressedData". For another mesh accessors point to decoded data too. But
/// offset is counted for another regions is encoded.
/// Example. You have two meshes. For every of it you have 4 bytes of data. That data compressed to 2 bytes. So, you have buffer with encoded data:
/// M1_E0, M1_E1, M2_E0, M2_E1.
/// After decoding you'll get:
/// M1_D0, M1_D1, M1_D2, M1_D3, M2_D0, M2_D1, M2_D2, M2_D3.
/// "accessors" must to use values that point to decoded data - obviously. So, you'll expect "accessors" like
/// "accessor_0" : { byteOffset: 0, byteLength: 4}, "accessor_1" : { byteOffset: 4, byteLength: 4}
/// but in real life you'll get:
/// "accessor_0" : { byteOffset: 0, byteLength: 4}, "accessor_1" : { byteOffset: 2, byteLength: 4}
/// Yes, accessor of next mesh has offset and length which mean: current mesh data is decoded, all other data is encoded.
/// And when before you start to read data of current mesh (with encoded data ofcourse) you must decode region of "bufferView", after read finished
/// delete encoding mark. And after that you can repeat process: decode data of mesh, read, delete decoded data.
///
/// Remark. Encoding all data at once is good in world with computers which do not has RAM limitation. So, you must use step by step encoding in
/// exporter and importer. And, thanks to such way, there is no need to load whole file into memory.
SEncodedRegion* EncodedRegion_Current;
private:
shared_ptr<uint8_t> mData; //!< Pointer to the data
bool mIsSpecial; //!< Set to true for special cases (e.g. the body buffer)
size_t capacity = 0; //!< The capacity of the buffer in bytes. (default: 0)
/// \var EncodedRegion_List
/// List of encoded regions.
std::list<SEncodedRegion*> EncodedRegion_List;
/******************* Functions *******************/
public:
Buffer();
~Buffer();
void Read(Value& obj, Asset& r);
bool LoadFromStream(IOStream& stream, size_t length = 0, size_t baseOffset = 0);
/// \fn void EncodedRegion_Mark(const size_t pOffset, const size_t pEncodedData_Length, uint8_t* pDecodedData, const size_t pDecodedData_Length, const std::string& pID)
/// Mark region of "bufferView" as encoded. When data is request from such region then "bufferView" use decoded data.
/// \param [in] pOffset - offset from begin of "bufferView" to encoded region, in bytes.
/// \param [in] pEncodedData_Length - size of encoded region, in bytes.
/// \param [in] pDecodedData - pointer to decoded data array.
/// \param [in] pDecodedData_Length - size of encoded region, in bytes.
/// \param [in] pID - ID of the region.
void EncodedRegion_Mark(const size_t pOffset, const size_t pEncodedData_Length, uint8_t* pDecodedData, const size_t pDecodedData_Length, const std::string& pID);
/// \fn void EncodedRegion_SetCurrent(const std::string& pID)
/// Select current encoded region by ID. \sa EncodedRegion_Current.
/// \param [in] pID - ID of the region.
void EncodedRegion_SetCurrent(const std::string& pID);
/// \fn bool ReplaceData(const size_t pBufferData_Offset, const size_t pBufferData_Count, const uint8_t* pReplace_Data, const size_t pReplace_Count)
/// Replace part of buffer data. Pay attention that function work with original array of data (\ref mData) not with encoded regions.
/// \param [in] pBufferData_Offset - index of first element in buffer from which new data will be placed.
/// \param [in] pBufferData_Count - count of bytes in buffer which will be replaced.
/// \param [in] pReplace_Data - pointer to array with new data for buffer.
/// \param [in] pReplace_Count - count of bytes in new data.
/// \return true - if successfully replaced, false if input arguments is out of range.
bool ReplaceData(const size_t pBufferData_Offset, const size_t pBufferData_Count, const uint8_t* pReplace_Data, const size_t pReplace_Count);
size_t AppendData(uint8_t* data, size_t length);
void Grow(size_t amount);
uint8_t* GetPointer()
{ return mData.get(); }
void MarkAsSpecial()
{ mIsSpecial = true; }
bool IsSpecial() const
{ return mIsSpecial; }
std::string GetURI()
{ return std::string(this->id) + ".bin"; }
static const char* TranslateId(Asset& r, const char* id);
};
//! A view into a buffer generally representing a subset of the buffer.
struct BufferView : public Object
{
Ref<Buffer> buffer; //! The ID of the buffer. (required)
size_t byteOffset; //! The offset into the buffer in bytes. (required)
size_t byteLength; //! The length of the bufferView in bytes. (default: 0)
BufferViewTarget target; //! The target that the WebGL buffer should be bound to.
void Read(Value& obj, Asset& r);
};
struct Camera : public Object
{
enum Type
{
Perspective,
Orthographic
};
Type type;
union
{
struct {
float aspectRatio; //!<The floating - point aspect ratio of the field of view. (0 = undefined = use the canvas one)
float yfov; //!<The floating - point vertical field of view in radians. (required)
float zfar; //!<The floating - point distance to the far clipping plane. (required)
float znear; //!< The floating - point distance to the near clipping plane. (required)
} perspective;
struct {
float xmag; //! The floating-point horizontal magnification of the view. (required)
float ymag; //! The floating-point vertical magnification of the view. (required)
float zfar; //! The floating-point distance to the far clipping plane. (required)
float znear; //! The floating-point distance to the near clipping plane. (required)
} ortographic;
};
Camera() {}
void Read(Value& obj, Asset& r);
};
//! Image data used to create a texture.
struct Image : public Object
{
std::string uri; //! The uri of the image, that can be a file path, a data URI, etc.. (required)
Ref<BufferView> bufferView;
std::string mimeType;
int width, height;
private:
std::unique_ptr<uint8_t[]> mData;
size_t mDataLength;
public:
Image();
void Read(Value& obj, Asset& r);
inline bool HasData() const
{ return mDataLength > 0; }
inline size_t GetDataLength() const
{ return mDataLength; }
inline const uint8_t* GetData() const
{ return mData.get(); }
inline uint8_t* StealData();
inline void SetData(uint8_t* data, size_t length, Asset& r);
};
//! Holds a material property that can be a texture or a color
struct TexProperty
{
Ref<Texture> texture;
vec4 color;
};
//! The material appearance of a primitive.
struct Material : public Object
{
//Ref<Sampler> source; //!< The ID of the technique.
//std::gltf_unordered_map<std::string, std::string> values; //!< A dictionary object of parameter values.
//! Techniques defined by KHR_materials_common
enum Technique
{
Technique_undefined = 0,
Technique_BLINN,
Technique_PHONG,
Technique_LAMBERT,
Technique_CONSTANT
};
TexProperty ambient;
TexProperty diffuse;
TexProperty specular;
TexProperty emission;
bool doubleSided;
bool transparent;
float transparency;
float shininess;
Technique technique;
Material() { SetDefaults(); }
void Read(Value& obj, Asset& r);
void SetDefaults();
};
//! A set of primitives to be rendered. A node can contain one or more meshes. A node's transform places the mesh in the scene.
struct Mesh : public Object
{
typedef std::vector< Ref<Accessor> > AccessorList;
struct Primitive
{
PrimitiveMode mode;
struct Attributes {
AccessorList position, normal, texcoord, color, joint, jointmatrix, weight;
} attributes;
Ref<Accessor> indices;
Ref<Material> material;
};
/// \struct SExtension
/// Extension used for mesh.
struct SExtension
{
/// \enum EType
/// Type of extension.
enum EType
{
#ifdef ASSIMP_IMPORTER_GLTF_USE_OPEN3DGC
Compression_Open3DGC,///< Compression of mesh data using Open3DGC algorithm.
#endif
Unknown
};
EType Type;///< Type of extension.
/// \fn SExtension
/// Constructor.
/// \param [in] pType - type of extension.
SExtension(const EType pType)
: Type(pType)
{}
virtual ~SExtension() {
// empty
}
};
#ifdef ASSIMP_IMPORTER_GLTF_USE_OPEN3DGC
/// \struct SCompression_Open3DGC
/// Compression of mesh data using Open3DGC algorithm.
struct SCompression_Open3DGC : public SExtension
{
using SExtension::Type;
std::string Buffer;///< ID of "buffer" used for storing compressed data.
size_t Offset;///< Offset in "bufferView" where compressed data are stored.
size_t Count;///< Count of elements in compressed data. Is always equivalent to size in bytes: look comments for "Type" and "Component_Type".
bool Binary;///< If true then "binary" mode is used for coding, if false - "ascii" mode.
size_t IndicesCount;///< Count of indices in mesh.
size_t VerticesCount;///< Count of vertices in mesh.
// AttribType::Value Type;///< Is always "SCALAR".
// ComponentType Component_Type;///< Is always "ComponentType_UNSIGNED_BYTE" (5121).
/// \fn SCompression_Open3DGC
/// Constructor.
SCompression_Open3DGC()
: SExtension(Compression_Open3DGC) {
// empty
}
virtual ~SCompression_Open3DGC() {
// empty
}
};
#endif
std::vector<Primitive> primitives;
std::list<SExtension*> Extension;///< List of extensions used in mesh.
Mesh() {}
/// \fn ~Mesh()
/// Destructor.
~Mesh() { for(std::list<SExtension*>::iterator it = Extension.begin(), it_end = Extension.end(); it != it_end; it++) { delete *it; }; }
/// \fn void Read(Value& pJSON_Object, Asset& pAsset_Root)
/// Get mesh data from JSON-object and place them to root asset.
/// \param [in] pJSON_Object - reference to pJSON-object from which data are read.
/// \param [out] pAsset_Root - reference to root asset where data will be stored.
void Read(Value& pJSON_Object, Asset& pAsset_Root);
#ifdef ASSIMP_IMPORTER_GLTF_USE_OPEN3DGC
/// \fn void Decode_O3DGC(const SCompression_Open3DGC& pCompression_Open3DGC, Asset& pAsset_Root)
/// Decode part of "buffer" which encoded with Open3DGC algorithm.
/// \param [in] pCompression_Open3DGC - reference to structure which describe encoded region.
/// \param [out] pAsset_Root - reference to root assed where data will be stored.
void Decode_O3DGC(const SCompression_Open3DGC& pCompression_Open3DGC, Asset& pAsset_Root);
#endif
};
struct Node : public Object
{
std::vector< Ref<Node> > children;
std::vector< Ref<Mesh> > meshes;
Nullable<mat4> matrix;
Nullable<vec3> translation;
Nullable<vec4> rotation;
Nullable<vec3> scale;
Ref<Camera> camera;
Ref<Light> light;
std::vector< Ref<Node> > skeletons; //!< The ID of skeleton nodes. Each of which is the root of a node hierarchy.
Ref<Skin> skin; //!< The ID of the skin referenced by this node.
std::string jointName; //!< Name used when this node is a joint in a skin.
Ref<Node> parent; //!< This is not part of the glTF specification. Used as a helper.
Node() {}
void Read(Value& obj, Asset& r);
};
struct Program : public Object
{
Program() {}
void Read(Value& obj, Asset& r);
};
struct Sampler : public Object
{
SamplerMagFilter magFilter; //!< The texture magnification filter. (required)
SamplerMinFilter minFilter; //!< The texture minification filter. (required)
SamplerWrap wrapS; //!< The texture wrapping in the S direction. (required)
SamplerWrap wrapT; //!< The texture wrapping in the T direction. (required)
Sampler() {}
void Read(Value& obj, Asset& r);
void SetDefaults();
};
struct Scene : public Object
{
std::vector< Ref<Node> > nodes;
Scene() {}
void Read(Value& obj, Asset& r);
};
struct Shader : public Object
{
Shader() {}
void Read(Value& obj, Asset& r);
};
struct Skin : public Object
{
Nullable<mat4> bindShapeMatrix; //!< Floating-point 4x4 transformation matrix stored in column-major order.
Ref<Accessor> inverseBindMatrices; //!< The ID of the accessor containing the floating-point 4x4 inverse-bind matrices.
std::vector<Ref<Node>> jointNames; //!< Joint names of the joints (nodes with a jointName property) in this skin.
std::string name; //!< The user-defined name of this object.
Skin() {}
void Read(Value& obj, Asset& r);
};
struct Technique : public Object
{
struct Parameters
{
};
struct States
{
};
struct Functions
{
};
Technique() {}
void Read(Value& obj, Asset& r);
};
//! A texture and its sampler.
struct Texture : public Object
{
Ref<Sampler> sampler; //!< The ID of the sampler used by this texture. (required)
Ref<Image> source; //!< The ID of the image used by this texture. (required)
//TextureFormat format; //!< The texture's format. (default: TextureFormat_RGBA)
//TextureFormat internalFormat; //!< The texture's internal format. (default: TextureFormat_RGBA)
//TextureTarget target; //!< The target that the WebGL texture should be bound to. (default: TextureTarget_TEXTURE_2D)
//TextureType type; //!< Texel datatype. (default: TextureType_UNSIGNED_BYTE)
Texture() {}
void Read(Value& obj, Asset& r);
};
//! A light (from KHR_materials_common extension)
struct Light : public Object
{
enum Type
{
Type_undefined,
Type_ambient,
Type_directional,
Type_point,
Type_spot
};
Type type;
vec4 color;
float distance;
float constantAttenuation;
float linearAttenuation;
float quadraticAttenuation;
float falloffAngle;
float falloffExponent;
Light() {}
void Read(Value& obj, Asset& r);
void SetDefaults();
};
struct Animation : public Object
{
struct AnimSampler {
std::string id; //!< The ID of this sampler.
std::string input; //!< The ID of a parameter in this animation to use as key-frame input.
std::string interpolation; //!< Type of interpolation algorithm to use between key-frames.
std::string output; //!< The ID of a parameter in this animation to use as key-frame output.
};
struct AnimChannel {
std::string sampler; //!< The ID of one sampler present in the containing animation's samplers property.
struct AnimTarget {
Ref<Node> id; //!< The ID of the node to animate.
std::string path; //!< The name of property of the node to animate ("translation", "rotation", or "scale").
} target;
};
struct AnimParameters {
Ref<Accessor> TIME; //!< Accessor reference to a buffer storing a array of floating point scalar values.
Ref<Accessor> rotation; //!< Accessor reference to a buffer storing a array of four-component floating-point vectors.
Ref<Accessor> scale; //!< Accessor reference to a buffer storing a array of three-component floating-point vectors.
Ref<Accessor> translation; //!< Accessor reference to a buffer storing a array of three-component floating-point vectors.
};
// AnimChannel Channels[3]; //!< Connect the output values of the key-frame animation to a specific node in the hierarchy.
// AnimParameters Parameters; //!< The samplers that interpolate between the key-frames.
// AnimSampler Samplers[3]; //!< The parameterized inputs representing the key-frame data.
std::vector<AnimChannel> Channels; //!< Connect the output values of the key-frame animation to a specific node in the hierarchy.
AnimParameters Parameters; //!< The samplers that interpolate between the key-frames.
std::vector<AnimSampler> Samplers; //!< The parameterized inputs representing the key-frame data.
Animation() {}
void Read(Value& obj, Asset& r);
};
//! Base class for LazyDict that acts as an interface
class LazyDictBase
{
public:
virtual ~LazyDictBase() {}
virtual void AttachToDocument(Document& doc) = 0;
virtual void DetachFromDocument() = 0;
virtual void WriteObjects(AssetWriter& writer) = 0;
};
template<class T>
class LazyDict;
//! (Implemented in glTFAssetWriter.h)
template<class T>
void WriteLazyDict(LazyDict<T>& d, AssetWriter& w);
//! Manages lazy loading of the glTF top-level objects, and keeps a reference to them by ID
//! It is the owner the loaded objects, so when it is destroyed it also deletes them
template<class T>
class LazyDict : public LazyDictBase
{
friend class Asset;
friend class AssetWriter;
typedef typename std::gltf_unordered_map< std::string, unsigned int > Dict;
std::vector<T*> mObjs; //! The read objects
Dict mObjsById; //! The read objects accessible by id
const char* mDictId; //! ID of the dictionary object
const char* mExtId; //! ID of the extension defining the dictionary
Value* mDict; //! JSON dictionary object
Asset& mAsset; //! The asset instance
void AttachToDocument(Document& doc);
void DetachFromDocument();
void WriteObjects(AssetWriter& writer)
{ WriteLazyDict<T>(*this, writer); }
Ref<T> Add(T* obj);
public:
LazyDict(Asset& asset, const char* dictId, const char* extId = 0);
~LazyDict();
Ref<T> Get(const char* id);
Ref<T> Get(unsigned int i);
Ref<T> Get(const std::string& pID) { return Get(pID.c_str()); }
Ref<T> Create(const char* id);
Ref<T> Create(const std::string& id)
{ return Create(id.c_str()); }
inline unsigned int Size() const
{ return unsigned(mObjs.size()); }
inline T& operator[](size_t i)
{ return *mObjs[i]; }
};
struct AssetMetadata
{
std::string copyright; //!< A copyright message suitable for display to credit the content creator.
std::string generator; //!< Tool that generated this glTF model.Useful for debugging.
bool premultipliedAlpha; //!< Specifies if the shaders were generated with premultiplied alpha. (default: false)
struct {
std::string api; //!< Specifies the target rendering API (default: "WebGL")
std::string version; //!< Specifies the target rendering API (default: "1.0.3")
} profile; //!< Specifies the target rendering API and version, e.g., WebGL 1.0.3. (default: {})
std::string version; //!< The glTF format version (should be 1.0)
void Read(Document& doc);
AssetMetadata()
: premultipliedAlpha(false)
, version("")
{
}
};
//
// glTF Asset class
//
//! Root object for a glTF asset
class Asset
{
typedef std::gltf_unordered_map<std::string, int> IdMap;
template<class T>
friend class LazyDict;
friend struct Buffer; // To access OpenFile
friend class AssetWriter;
private:
IOSystem* mIOSystem;
std::string mCurrentAssetDir;
size_t mSceneLength;
size_t mBodyOffset, mBodyLength;
std::vector<LazyDictBase*> mDicts;
IdMap mUsedIds;
Ref<Buffer> mBodyBuffer;
Asset(Asset&);
Asset& operator=(const Asset&);
public:
//! Keeps info about the enabled extensions
struct Extensions
{
bool KHR_binary_glTF;
bool KHR_materials_common;
} extensionsUsed;
AssetMetadata asset;
// Dictionaries for each type of object
LazyDict<Accessor> accessors;
LazyDict<Animation> animations;
LazyDict<Buffer> buffers;
LazyDict<BufferView> bufferViews;
LazyDict<Camera> cameras;
LazyDict<Image> images;
LazyDict<Material> materials;
LazyDict<Mesh> meshes;
LazyDict<Node> nodes;
//LazyDict<Program> programs;
LazyDict<Sampler> samplers;
LazyDict<Scene> scenes;
//LazyDict<Shader> shaders;
LazyDict<Skin> skins;
//LazyDict<Technique> techniques;
LazyDict<Texture> textures;
LazyDict<Light> lights; // KHR_materials_common ext
Ref<Scene> scene;
public:
Asset(IOSystem* io = 0)
: mIOSystem(io)
, asset()
, accessors (*this, "accessors")
, animations (*this, "animations")
, buffers (*this, "buffers")
, bufferViews (*this, "bufferViews")
, cameras (*this, "cameras")
, images (*this, "images")
, materials (*this, "materials")
, meshes (*this, "meshes")
, nodes (*this, "nodes")
//, programs (*this, "programs")
, samplers (*this, "samplers")
, scenes (*this, "scenes")
//, shaders (*this, "shaders")
, skins (*this, "skins")
//, techniques (*this, "techniques")
, textures (*this, "textures")
, lights (*this, "lights", "KHR_materials_common")
{
memset(&extensionsUsed, 0, sizeof(extensionsUsed));
}
//! Main function
void Load(const std::string& file, bool isBinary = false);
//! Enables the "KHR_binary_glTF" extension on the asset
void SetAsBinary();
//! Search for an available name, starting from the given strings
std::string FindUniqueID(const std::string& str, const char* suffix);
Ref<Buffer> GetBodyBuffer()
{ return mBodyBuffer; }
private:
void ReadBinaryHeader(IOStream& stream);
void ReadExtensionsUsed(Document& doc);
IOStream* OpenFile(std::string path, const char* mode, bool absolute = false);
};
}
// Include the implementation of the methods
#include "glTFAsset.inl"
#endif // ASSIMP_BUILD_NO_GLTF_IMPORTER
#endif // GLTFASSET_H_INC
|
Bloodknight/Torque3D
|
Engine/lib/assimp/code/glTF/glTFAsset.h
|
C
|
mit
| 38,517 |
//-----------------------------------------------------------------------
// <copyright file="ClientContextTests.server.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: https://cslanet.com
// </copyright>
// <summary>no summary</summary>
//-----------------------------------------------------------------------
using System.Configuration;
using System.Security.Principal;
using Csla.Security;
using Csla.Testing.Business.ApplicationContext;
#if NUNIT
using NUnit.Framework;
using TestClass = NUnit.Framework.TestFixtureAttribute;
using TestInitialize = NUnit.Framework.SetUpAttribute;
using TestCleanup = NUnit.Framework.TearDownAttribute;
using TestMethod = NUnit.Framework.TestAttribute;
using TestSetup = NUnit.Framework.SetUpAttribute;
#elif MSTEST
using Microsoft.VisualStudio.TestTools.UnitTesting;
#endif
namespace Csla.Test.Silverlight.ApplicationContext
{
//[TestClass]
public partial class ClientContextTests
{
[TestMethod]
[TestCategory("SkipWhenLiveUnitTesting")]
public void ServerShouldReceiveClientContextValue()
{
var context = GetContext();
Csla.ApplicationContext.User = new UnauthenticatedPrincipal();
Csla.ApplicationContext.DataPortalProxy = "Csla.Testing.Business.TestProxies.AppDomainProxy, Csla.Testing.Business";
var verifier = new ClientContextBOVerifier(true);
//This is what we are transferring
Csla.ApplicationContext.ClientContext["MSG"] = ContextMessageValues.INITIAL_VALUE;
verifier.Name = "justin";
var result = verifier.Save();
context.Assert.AreEqual(ContextMessageValues.INITIAL_VALUE, result.ReceivedContextValue);
context.Assert.Success();
context.Complete();
}
}
}
|
jonnybee/csla
|
Source/Csla.test/Silverlight/ApplicationContext/ClientContextTests.server.cs
|
C#
|
mit
| 1,763 |
class ChallengeDecorator < Draper::Decorator
include Sprockets::Helpers::RailsHelper
delegate_all
def value
title
end
def url
Rails.application.routes.url_helpers.challenge_path(id)
end
def sub
"By; #{supervisor.decorate.fullname}"
end
def type
'C'
end
def img
ActionController::Base.helpers.image_path("fav64.png")
end
def as_json(options={})
super(
options.merge(
:root => false,
:only => [],
:methods => [:url, :value, :sub, :img, :type]
)
)
end
def implied_state
if declined?
"declined"
else
state
end
end
def human_readable_start_date
if start_date.present?
start_date.strftime("%d-%m-%Y")
else
"TBC."
end
end
def human_readable_end_date
if end_date.present?
end_date.strftime("%d-%m-%Y")
else
"TBC."
end
end
def current_user_enrolled?
participants.exists? h.current_user
end
def warn_current_user_enrollment?
upcoming? && !current_user_enrolled? && days_till_start < 10
end
def location
if object.location.blank?
"TBA"
else
object.location
end
end
def supervisor
if object.supervisor.present?
object.supervisor.decorate
else
nil
end
end
def day_of_week
if start_date.present?
start_date.strftime("%A")
else
"TBC"
end
end
def from_till
("From " + h.content_tag(:span, human_readable_start_date, :id => 'start_date') + " till " + h.content_tag(:span, human_readable_end_date, :id => 'end_date')).html_safe
end
def human_date_string
(day_of_week.pluralize + " " + from_till.downcase).html_safe
end
def days_total
if start_date.present? && end_date.present?
startd = start_date.to_date
endd = end_date.to_date
(endd - startd).to_i
end
end
def days_till_end
if start_date.present? && end_date.present? && running?
today = Date.today
endd = end_date.to_date
(endd - today).to_i
else
0
end
end
def days_till_start
if start_date.present? && end_date.present? && upcoming?
today = Date.today
startd = start_date.to_date
(startd - today).to_i + 1
else
0
end
end
def days_till_enrollment_closes
days_till_start
end
def percentage_date
if start_date.present? && end_date.present? && running?
today = Date.today
startd = start_date.to_date
endd = end_date.to_date
((((today - startd) / (endd - startd)) * 100 ).to_i).to_s + "%"
elsif start_date.present? && end_date.present? && upcoming?
"0%"
else
"100%"
end
end
def activity_text
h.link_to title, object
end
end
|
rbecheras/challengesplatform
|
app/decorator/challenge_decorator.rb
|
Ruby
|
mit
| 2,756 |
{% extends 'interface/base.html' %}
{% load staticfiles %}
{% block head %}
{{ block.super }}
{% endblock head %}
{% block header %}
{{ block.super }}
{% endblock header %}
{% block content %}
<div id = "results_list" class = "col-xs-8 col-md-8 text-center">
<ul>
<h2>{{ current_league.name }} week {{week}} Leaderboard : </h2>
{% for team in team_weekly_record_list %}
<li><a href = "{% url 'interface:team_view' league_slug=current_league.slug team_slug=team.0.slug %}">{{ team.0.name }}</a>:  {{ team.1 }}</li>
{% endfor %}
</ul>
</div>
{% endblock content %}
|
ConnorH2582/pickem_football
|
pickem_football/interface/templates/interface/leagueweek.html
|
HTML
|
mit
| 714 |
'use strict';
var pluginName = 'babel-plugin-react-hot';
var pluginPath = typeof __dirname === 'undefined' ? pluginName : __dirname;
var makeHotName = 'makeHot';
var makeHotPath = pluginPath+'/makeHot.js';
var reactName = 'React';
var reactPath = 'react';
var mountName = 'ReactMount';
var mountPath = 'react/lib/ReactMount';
function isRenderMethod (member) {
return member.kind === 'method' &&
member.key.name === 'render';
}
exports = module.exports = transform;
function transform (babel) {
var t = babel.types;
return new babel.Transformer(pluginName, {
/**
* ES6 ReactComponent
*/
ClassDeclaration: function (node, parent, scope, file) {
var hasRenderMethod = node.body.body.filter(isRenderMethod).length > 0;
if (!hasRenderMethod) {
return;
}
var makeHot = file.addImport(makeHotPath, makeHotName);
var React = file.addImport(reactPath, reactName);
var mount = file.addImport(mountPath, mountName);
node.decorators = node.decorators || [];
node.decorators.push(
t.decorator(
t.callExpression(
makeHot,
[
React,
mount,
t.literal(file.opts._address || file.opts.filename),
t.literal(node.id.name)
]
)
)
);
},
/**
* ReactClassComponent
*/
CallExpression: function (node, parent, scope, file) {
var callee = this.get('callee');
if (node._hotDecorated || !callee.matchesPattern('React.createClass')) {
return;
}
var makeHot = file.addImport(makeHotPath, makeHotName);
var React = file.addImport(reactPath, reactName);
var mount = file.addImport(mountPath, mountName);
node._hotDecorated = true;
return t.callExpression(
t.callExpression(
makeHot,
[
React,
mount,
t.literal(file.opts._address || file.opts.filename),
t.literal(parent && parent.id && parent.id.name || null)
]
),
[node]
);
}
});
}
|
tmbtech/babel-plugin-react-hot
|
index.js
|
JavaScript
|
mit
| 2,154 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Destrier.Redis.Core
{
public enum RedisKeyType
{
None = 0,
String = 1,
Set = 2,
List = 3,
ZSet = 4,
Hash = 5
}
}
|
ClothesHorse/Destrier
|
Destrier.Redis/Core/RedisKeyType.cs
|
C#
|
mit
| 273 |
// Copyright (c) 2007-2017 ppy Pty Ltd <[email protected]>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using osu.Framework.Extensions.TypeExtensions;
using System;
using System.Collections.Generic;
namespace osu.Framework.Graphics.Transforms
{
public abstract class Transform
{
internal ulong TransformID;
public Easing Easing;
public abstract ITransformable TargetTransformable { get; }
public double StartTime { get; internal set; }
public double EndTime { get; internal set; }
public bool IsLooping { get; internal set; }
public double LoopDelay { get; internal set; }
public abstract string TargetMember { get; }
public abstract void Apply(double time);
public abstract void ReadIntoStartValue();
internal bool HasStartValue;
public Action OnComplete;
public Action OnAbort;
public Transform Clone() => (Transform)MemberwiseClone();
public static readonly IComparer<Transform> COMPARER = new TransformTimeComparer();
private class TransformTimeComparer : IComparer<Transform>
{
public int Compare(Transform x, Transform y)
{
if (x == null) throw new ArgumentNullException(nameof(x));
if (y == null) throw new ArgumentNullException(nameof(y));
int compare = x.StartTime.CompareTo(y.StartTime);
if (compare != 0) return compare;
compare = x.TransformID.CompareTo(y.TransformID);
return compare;
}
}
}
public abstract class Transform<TValue> : Transform
{
public TValue StartValue { get; protected set; }
public TValue EndValue { get; protected internal set; }
}
public abstract class Transform<TValue, T> : Transform<TValue>
where T : ITransformable
{
public override ITransformable TargetTransformable => Target;
public T Target { get; internal set; }
public sealed override void Apply(double time) => Apply(Target, time);
public sealed override void ReadIntoStartValue() => ReadIntoStartValue(Target);
protected abstract void Apply(T d, double time);
protected abstract void ReadIntoStartValue(T d);
public override string ToString() => $"{typeof(Transform<TValue, T>).ReadableName()} => {Target} {StartTime}:{StartValue}-{EndTime}:{EndValue}";
}
}
|
paparony03/osu-framework
|
osu.Framework/Graphics/Transforms/Transform.cs
|
C#
|
mit
| 2,604 |
/*
* Copyright 2019 Valve Software
*
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <dlfcn.h>
char *g_errstr = NULL;
static void *g_libgtk = NULL;
// Function pointer typedefs
extern "C"
{
#define HOOK_FUNC( _ret, _func, _args, ... ) typedef _ret ( _func ## _t )( __VA_ARGS__ );
#define HOOK_FUNCV( _ret, _func, _args, ... ) typedef _ret ( _func ## _t )( __VA_ARGS__ );
#include "hook_gtk3_funcs.inl"
#undef HOOK_FUNC
#undef HOOK_FUNCV
}
// Function pointers struct
struct
{
#define HOOK_FUNC( _ret, _func, _args, ... ) _func ## _t *_func;
#define HOOK_FUNCV( _ret, _func, _args, ... ) _func ## _t *_func;
#include "hook_gtk3_funcs.inl"
#undef HOOK_FUNC
#undef HOOK_FUNCV
} g_gtk;
// Init function pointers struct
static const char *hook_gtk3_init()
{
const char *fail_func = NULL;
// Already loaded?
if ( g_libgtk )
return NULL;
// Already error'd out?
if ( g_errstr )
return g_errstr;
// Try to load gtk3 dso
g_libgtk = dlopen( "libgtk-3.so.0", RTLD_NOW | RTLD_GLOBAL );
if ( !g_libgtk )
g_libgtk = dlopen( "libgtk-3.so", RTLD_NOW | RTLD_GLOBAL );
if ( !g_libgtk )
{
if (-1 == asprintf( &g_errstr, "dlopen( libgtk-3.so ) failed: %s\n", dlerror() ))
g_errstr = NULL;
return g_errstr;
}
// Get addresses of gtk3 functions
#define DLSYM_FUNC( _func ) \
{ \
g_gtk._func = ( _func ## _t * )dlsym( g_libgtk, #_func ); \
if ( !g_gtk._func ) \
{ \
fail_func = #_func; \
break; \
} \
}
#define HOOK_FUNC( _ret, _func, _args, ... ) DLSYM_FUNC( _func )
#define HOOK_FUNCV( _ret, _func, _args, ... ) DLSYM_FUNC( _func )
do
{
#include "hook_gtk3_funcs.inl"
} while ( 0 );
#undef HOOK_FUNC
#undef HOOK_FUNCV
// Error out and free library if any dlsym calls failed
if ( fail_func )
{
if (-1 == asprintf( &g_errstr, "dlsym( %s ) failed: %s\n", fail_func, dlerror() ))
g_errstr = NULL;
dlclose( g_libgtk );
g_libgtk = NULL;
}
return g_errstr;
}
#define g_type_check_instance_cast g_gtk.g_type_check_instance_cast
#define gtk_dialog_run g_gtk.gtk_dialog_run
#define gtk_dialog_get_type g_gtk.gtk_dialog_get_type
#define gtk_init_check g_gtk.gtk_init_check
#define gtk_events_pending g_gtk.gtk_events_pending
#define gtk_main_iteration g_gtk.gtk_main_iteration
#define gtk_widget_destroy g_gtk.gtk_widget_destroy
#define gtk_file_chooser_get_type g_gtk.gtk_file_chooser_get_type
#define gtk_file_chooser_set_filename g_gtk.gtk_file_chooser_set_filename
#define gtk_file_chooser_set_current_name g_gtk.gtk_file_chooser_set_current_name
#define gtk_file_chooser_set_do_overwrite_confirmation g_gtk.gtk_file_chooser_set_do_overwrite_confirmation
#define gtk_file_chooser_get_filename g_gtk.gtk_file_chooser_get_filename
#define gtk_file_chooser_dialog_new g_gtk.gtk_file_chooser_dialog_new
#define gtk_file_chooser_add_filter g_gtk.gtk_file_chooser_add_filter
#define gtk_file_filter_new g_gtk.gtk_file_filter_new
#define gtk_file_filter_set_name g_gtk.gtk_file_filter_set_name
#define gtk_file_filter_add_pattern g_gtk.gtk_file_filter_add_pattern
|
mikesart/gpuvis
|
src/hook_gtk3.h
|
C
|
mit
| 5,009 |
<footer>
<div class="container-fluid">
<div class="container footer-page">
<div class="row">
<p class="text-center"><?=$this->pocore()->call->posetting[0]['value'];?> © 2013-<?=date('Y');?>. All Rights Reserved.</p>
</div>
</div>
</div>
</footer>
|
PopojiCMS/PopojiCMS
|
po-content/themes/member/footer.php
|
PHP
|
mit
| 267 |
'''
'''
import cv
def count_cameras():
for i in range(10):
temp_camera = cv.CreateCameraCapture(i-1)
temp_frame = cv.QueryFrame(temp_camera)
del(temp_camera)
if temp_frame==None:
del(temp_frame)
return i-1
if __name__ == '__main__':
count_cameras()
|
moriarty/csci-homework
|
4155/assignments/countcams.py
|
Python
|
mit
| 312 |
# == Schema Information
#
# Table name: docs
#
# id :integer not null, primary key
# title :string
# body :text
# keywords :string
# title_tag :string
# meta_description :string
# category_id :integer
# user_id :integer
# active :boolean default(TRUE)
# rank :integer
# permalink :string
# version :integer
# front_page :boolean default(FALSE)
# cheatsheet :boolean default(FALSE)
# points :integer default(0)
# created_at :datetime not null
# updated_at :datetime not null
#
class DocsController < ApplicationController
before_action :authenticate_user!, :except => ['show', 'home']
before_action :verify_admin, :only => ['new', 'edit', 'update', 'create', 'destroy']
layout 'admin', :only => ['new', 'edit', 'update', 'create']
#before_filter :get_tags
#before_filter :set_docs, :only => 'show'
#after_filter :view_causes_vote, :only => 'show'
# GET /docs/1
# GET /docs/1.xml
def show
@doc = Doc.where(id: params[:id]).active.first
unless @doc.nil?
@meta_description = @doc.meta_description
@keywords = @doc.keywords
@page_title = @doc.title
@custom_title = @doc.title_tag.blank? ? @page_title : @doc.title_tag
@title_tag = "#{Settings.site_name}: #{@custom_title}"
add_breadcrumb t(:knowledgebase, default: "Knowledgebase"), categories_path
add_breadcrumb @doc.category.name, category_path(@doc.category) if @doc.category.name
add_breadcrumb @doc.title
respond_to do |format|
format.html # show.html.erb
end
else
redirect_to root_url
end
end
# GET /docs/new
# GET /docs/new.xml
def new
@doc = Doc.new
@doc.category_id = params[:category_id]
@post = Post.where(id: params[:post_id]).first if current_user.admin == true
@categories = Category.alpha
respond_to do |format|
format.html
end
end
# GET /docs/1/edit
def edit
@doc = Doc.find(params[:id])
@category = Category.where(id: params[:category_id]).first
@categories = Category.alpha
end
# POST /docs
# POST /docs.xml
def create
@doc = Doc.new(doc_params)
@doc.user_id = current_user.id
respond_to do |format|
if @doc.save
#@doc.tag_list = params[:tags]
#@doc.save
format.html { redirect_to(admin_articles_path(@doc.category.id)) }
else
format.html { render :action => "new" }
end
end
end
# PUT /docs/1
# PUT /docs/1.xml
def update
unless params['lang'].nil?
I18n.locale = params['lang']
end
@doc = Doc.where(id: params[:id]).first
respond_to do |format|
if @doc.update_attributes(doc_params)
format.html { redirect_to(admin_articles_path(@doc.category.id)) }
else
format.html { render :action => "edit", :id => @doc }
end
end
end
# DELETE /docs/1
# DELETE /docs/1.xml
def destroy
@doc = Doc.find(params[:id])
@doc.destroy
respond_to do |format|
format.js { render js:"$('#doc-#{@doc.id}').fadeOut();
Helpy.ready();
Helpy.track();" }
end
end
def set_docs
if params[:permalink]
@doc = Doc.find_by_permalink(params[:permalink])
else
# category = Category.find_by_link(params[:link])
@doc = Doc.find_by_category_id(params[:link])
end
@related = Doc.in_category(@doc.category_id)
end
def home
render(:layout => 'discussion')
end
protected
#def get_tags
# @tags = Doc.tag_counts
#end
def view_causes_vote
if user_signed_in?
@doc.votes.create unless current_user.admin?
else
@doc.votes.create
end
end
private
def doc_params
params.require(:doc).permit(:title, :body, :keywords, :title_tag, :meta_description, :category_id, :rank, :active, :front_page, :user_id, {screenshots: []})
end
end
|
Rahul2692/helpy
|
app/controllers/docs_controller.rb
|
Ruby
|
mit
| 4,038 |
The MIT License (MIT)
Copyright (c) 2014 Matthew Butler
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
|
butlermatt/puffer
|
LICENSE.md
|
Markdown
|
mit
| 1,081 |
#pragma once
#include "simlib/inplace_buff.hh"
#include "simlib/libzip.hh"
#include <set>
namespace sim {
// Holds a list of entries (full path for each)
class PackageContents {
struct Span {
size_t begin, end;
};
InplaceBuff<0> buff;
struct Comparer {
struct is_transparent;
decltype(buff)* buff_ref;
explicit Comparer(decltype(buff)& br)
: buff_ref(&br) {}
static StringView to_str(StringView str) noexcept { return str; }
[[nodiscard]] StringView to_str(Span x) const {
return {buff_ref->data() + x.begin, x.end - x.begin};
}
template <class A, class B>
bool operator()(A&& a, B&& b) const {
return to_str(a) < to_str(b);
}
};
std::set<Span, Comparer> entries{Comparer(buff)};
[[nodiscard]] StringView to_str(Span x) const {
return {buff.data() + x.begin, x.end - x.begin};
}
public:
PackageContents() = default;
PackageContents(const PackageContents&) = delete;
PackageContents(PackageContents&&) noexcept = default;
PackageContents& operator=(const PackageContents&) = delete;
PackageContents& operator=(PackageContents&&) noexcept = default;
~PackageContents() = default;
template <class... Args, std::enable_if_t<(is_string_argument<Args> and ...), int> = 0>
void add_entry(Args&&... args) {
auto prev_size = buff.size;
buff.append(std::forward<Args>(args)...);
entries.insert({prev_size, buff.size});
}
// Returns bool denoting whether the erasing took place
bool remove(const StringView& entry) {
auto it = entries.find(entry);
if (it == entries.end()) {
return false;
}
entries.erase(it);
return true;
}
void remove_with_prefix(const StringView& prefix) {
auto it = entries.lower_bound(prefix);
while (it != entries.end() and has_prefix(to_str(*it), prefix)) {
entries.erase(it++);
}
}
/// @p callback should take one argument of type StringView - it will
/// contain the entry's path
template <class Func>
void for_each_with_prefix(const StringView& prefix, Func&& callback) const {
auto it = entries.lower_bound(prefix);
while (it != entries.end()) {
StringView entry = to_str(*it);
if (not has_prefix(entry, prefix)) {
break;
}
callback(entry);
++it;
}
}
[[nodiscard]] bool exists(const StringView& entry) const {
return entries.find(entry) != entries.end();
}
/// Finds main directory (with trailing '/') if such does not exist "" is
/// returned
[[nodiscard]] StringView main_dir() const {
if (entries.empty()) {
return "";
}
StringView candidate = to_str(*entries.begin());
{
auto pos = candidate.find('/');
if (pos == StringView::npos) {
return ""; // There is no main dir
}
candidate = candidate.substr(0, pos + 1);
}
if (not has_prefix(to_str(*entries.rbegin()), candidate)) {
return ""; // There is no main dir
}
return candidate;
}
void load_from_directory(StringView pkg_path, bool retain_pkg_path_prefix = false);
void load_from_zip(FilePath pkg_path);
};
/// Finds main directory (with trailing '/') in @p pkg_path if such does not
/// exist "" is returned
std::string zip_package_main_dir(ZipFile& zip);
/// Finds main directory (with trailing '/') in @p pkg_path if such does not
/// exist "" is returned
inline std::string zip_package_main_dir(FilePath pkg_path) {
ZipFile zip(pkg_path, ZIP_RDONLY);
return zip_package_main_dir(zip);
}
} // namespace sim
|
varqox/simlib
|
include/simlib/sim/problem_package.hh
|
C++
|
mit
| 3,851 |
#include "Cone.h"
#include "GLee.h"
static float default_slices = 64;
static float default_stacks = 64;
Cone::Cone() : Cone(1.0, 1.0) {}
Cone::Cone(float base, float height) : Cone(base, height, default_slices, default_stacks) {}
Cone::Cone(float base, float height, UINT32 slices, UINT32 stacks) : base(base), height(height), slices(slices), stacks(stacks) {}
Cone::~Cone()
{
}
void Cone::render()
{
glutSolidCone(base, height, slices, stacks);
}
|
matheusvxf/Water
|
components/source/Cone.cpp
|
C++
|
mit
| 459 |
---
layout: docs
title: codegenEnumMemberf
id: interface.Facebook.HackCodegen.ICodegenFactory.codegenEnumMemberf
docid: interface.Facebook.HackCodegen.ICodegenFactory.codegenEnumMemberf
permalink: /docs/reference/interface.Facebook.HackCodegen.ICodegenFactory.codegenEnumMemberf/
---
# Facebook\\HackCodegen\\ICodegenFactory::codegenEnumMemberf()
Create an enum member using a %-placeholder format string for the constant
name
``` Hack
public function codegenEnumMemberf(
HH\Lib\Str\SprintfFormatString $format,
mixed ...$args,
): Facebook\HackCodegen\CodegenEnumMember;
```
## Parameters
+ ` HH\Lib\Str\SprintfFormatString $format `
+ ` mixed ...$args `
## Returns
* [` Facebook\HackCodegen\CodegenEnumMember `](<class.Facebook.HackCodegen.CodegenEnumMember.md>)
|
hhvm/hack-codegen
|
docs/_docs/reference/interface.Facebook.HackCodegen.ICodegenFactory.codegenEnumMemberf.md
|
Markdown
|
mit
| 791 |
# Summary
* [Http(s)](http/README.md)
* [urllib](http/urllib.md)
* [co-urllib](http/co-urllib.md)
* [digest-header](http/digest-header.md)
* [Web](web/README.md)
* [loading](web/utils/loading.md)
* [koa](web/koa/README.md)
* [koa-session](web/koa/koa-session.md)
* [koa-middlewares](web/koa/koa-middlewares.md)
* [koa-roles](web/koa/koa-roles.md)
* [connect](web/connect/README.md)
* [connect-render](web/connect/connect-render.md)
* [Utilities](utilities/README.md)
* [is-type-of](utilities/is-type-of.md)
* [utility](utilities/utility.md)
* [copy-to](utilities/copy-to.md)
* [show-methods](utilities/show-methods.md)
* [node-murmurhash](utilities/node-murmurhash.md)
* [Protocol](protocol/README.md)
* [hessian.js](protocol/hessian.js.md)
* [java.io](protocol/java.io.md)
* [binpack.js](protocol/binpack.js.md)
* [Simple Store Service](s3/README.md)
* [ali-oss](s3/ali-oss.md)
* [tfs](s3/tfs.md)
* [npm](npm/README.md)
* [cnpmjs.org](npm/cnpmjs.org.md)
* [cnpm](npm/cnpm.md)
* [tnpm](npm/tnpm.md)
|
node-modules/node-modules.github.io
|
book/SUMMARY.md
|
Markdown
|
mit
| 1,082 |
/**
* Created by maomao on 2020/4/20.
*/
Java.perform(function() {
var cn = "android.graphics.NinePatch";
var target = Java.use(cn);
if (target) {
target.isNinePatchChunk.implementation = function(dest) {
var myArray=new Array()
myArray[0] = "INTERESTED" //INTERESTED & SENSITIVE
myArray[1] = cn + "." + "isNinePatchChunk";
myArray[2] = Java.use("android.util.Log").getStackTraceString(Java.use("java.lang.Exception").$new()).split('\n\tat');
send(myArray);
return this.isNinePatchChunk.apply(this, arguments);
};
}
});
|
honeynet/droidbot
|
droidbot/resources/scripts/graphic/NinePatch.js
|
JavaScript
|
mit
| 626 |
NASM = nasm
QEMU = qemu-system-i386
QEMU_DRIVE = a
# QEMU_SPEAKER = -soundhw pcspk
NAME = floppybird
FILENAME = $(NAME).img
COM_FILENAME = flpybird.com
IMAGE = build/$(FILENAME)
ISO_IMAGE = build/iso/$(FILENAME)
ISO = build/$(NAME).iso
ISO_DIR = build/iso
COM_TARGET = build/$(COM_FILENAME)
BOOT = src/boot.asm
COM = src/com.asm
KERNEL = src/sys/rnd.asm \
src/sys/snd.asm \
src/sys/tmr.asm \
src/sys/txt.asm \
src/sys/vga.asm
GAME = src/main.asm \
src/game/background.asm \
src/game/bird.asm \
src/game/bushes.asm \
src/game/clouds.asm \
src/game/data.asm \
src/game/flats.asm \
src/game/ground.asm \
src/game/pipes.asm \
src/game/score.asm
all: $(IMAGE)
$(IMAGE): $(BOOT) $(KERNEL) $(GAME)
$(NASM) -isrc/ -f bin -o $(IMAGE) $(BOOT)
$(COM_TARGET): $(COM) $(KERNEL) $(GAME)
$(NASM) -isrc/ -DCOM -f bin -o $(COM_TARGET) $(COM)
com: $(COM_TARGET)
usb:
sudo dd if=$(IMAGE) of=/dev/sdb
floppy:
dd bs=512 count=2880 if=/dev/zero of=$(ISO_IMAGE)
dd status=noxfer conv=notrunc if=$(IMAGE) of=$(ISO_IMAGE)
iso:
$(MAKE) floppy
mkisofs -quiet -V 'FLOPPYBIRD' -input-charset iso8859-1 -o $(ISO) -b $(FILENAME) $(ISO_DIR)
qemu:
$(QEMU) $(QEMU_SPEAKER) -boot $(QEMU_DRIVE) -fd$(QEMU_DRIVE) $(IMAGE)
bochs:
bochs -q -n 'boot:floppy' 'floppy$(QEMU_DRIVE): 1_44=$(IMAGE), status=inserted'
dosbox:
dosbox -conf dosbox.conf $(COM_TARGET)
clean:
rm $(IMAGE)
rm $(ISO_IMAGE)
rm $(ISO)
rm $(COM_TARGET)
.PHONY: usb floppy iso qemu bochs dosbox clean
|
icebreaker/floppybird
|
Makefile
|
Makefile
|
mit
| 1,549 |
//
// RealmAsset.h
// ContentfulSDK
//
// Created by Boris Bügling on 08/12/14.
//
//
#import <ContentfulDeliveryAPI/CDAPersistedAsset.h>
#import <Realm/RLMObject.h>
@interface RealmAsset : RLMObject <CDAPersistedAsset>
@end
|
danieleggert/contentful.objc
|
Code/Realm/RealmAsset.h
|
C
|
mit
| 232 |
package net.sf.jabref.model.entry;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import net.sf.jabref.model.FieldChange;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class BibEntryTests {
private BibEntry keywordEntry;
private BibEntry emptyEntry;
@Before
public void setUp() {
// Default entry for most keyword and some type tests
keywordEntry = new BibEntry();
keywordEntry.setType(BibtexEntryTypes.ARTICLE);
keywordEntry.setField("keywords", "Foo, Bar");
keywordEntry.setChanged(false);
// Empty entry for some tests
emptyEntry = new BibEntry();
emptyEntry.setType("article");
emptyEntry.setChanged(false);
}
@Test
public void testDefaultConstructor() {
BibEntry entry = new BibEntry();
// we have to use `getType("misc")` in the case of biblatex mode
Assert.assertEquals("misc", entry.getType());
Assert.assertNotNull(entry.getId());
Assert.assertFalse(entry.getFieldOptional("author").isPresent());
}
@Test
public void allFieldsPresentDefault() {
BibEntry e = new BibEntry("id", BibtexEntryTypes.ARTICLE.getName());
e.setField("author", "abc");
e.setField("title", "abc");
e.setField("journal", "abc");
List<String> requiredFields = new ArrayList<>();
requiredFields.add("author");
requiredFields.add("title");
Assert.assertTrue(e.allFieldsPresent(requiredFields, null));
requiredFields.add("year");
Assert.assertFalse(e.allFieldsPresent(requiredFields, null));
}
@Test
public void allFieldsPresentOr() {
BibEntry e = new BibEntry("id", BibtexEntryTypes.ARTICLE.getName());
e.setField("author", "abc");
e.setField("title", "abc");
e.setField("journal", "abc");
List<String> requiredFields = new ArrayList<>();
// XOR required
requiredFields.add("journal/year");
Assert.assertTrue(e.allFieldsPresent(requiredFields, null));
requiredFields.add("year/address");
Assert.assertFalse(e.allFieldsPresent(requiredFields, null));
}
@Test(expected = NullPointerException.class)
public void isNullCiteKeyThrowsNPE() {
BibEntry e = new BibEntry("id", BibtexEntryTypes.ARTICLE.getName());
e.setCiteKey(null);
Assert.fail();
}
@Test
public void isEmptyCiteKey() {
BibEntry e = new BibEntry("id", BibtexEntryTypes.ARTICLE.getName());
Assert.assertFalse(e.hasCiteKey());
e.setCiteKey("");
Assert.assertFalse(e.hasCiteKey());
e.setCiteKey("key");
Assert.assertTrue(e.hasCiteKey());
e.clearField(BibEntry.KEY_FIELD);
Assert.assertFalse(e.hasCiteKey());
}
@Test
public void typeOfBibEntryIsMiscAfterSettingToNullString() {
Assert.assertEquals("article", keywordEntry.getType());
keywordEntry.setType((String) null);
Assert.assertEquals("misc", keywordEntry.getType());
}
@Test
public void typeOfBibEntryIsMiscAfterSettingToEmptyString() {
Assert.assertEquals("article", keywordEntry.getType());
keywordEntry.setType("");
Assert.assertEquals("misc", keywordEntry.getType());
}
@Test
public void getFieldOrAliasDateWithYearNumericalMonthString() {
emptyEntry.setField("year", "2003");
emptyEntry.setField("month", "3");
Assert.assertEquals(Optional.of("2003-03"), emptyEntry.getFieldOrAlias("date"));
}
@Test
public void getFieldOrAliasDateWithYearAbbreviatedMonth() {
emptyEntry.setField("year", "2003");
emptyEntry.setField("month", "#mar#");
Assert.assertEquals(Optional.of("2003-03"), emptyEntry.getFieldOrAlias("date"));
}
@Test
public void getFieldOrAliasDateWithYearAbbreviatedMonthString() {
emptyEntry.setField("year", "2003");
emptyEntry.setField("month", "mar");
Assert.assertEquals(Optional.of("2003-03"), emptyEntry.getFieldOrAlias("date"));
}
@Test
public void getFieldOrAliasDateWithOnlyYear() {
emptyEntry.setField("year", "2003");
Assert.assertEquals(Optional.of("2003"), emptyEntry.getFieldOrAlias("date"));
}
@Test
public void getFieldOrAliasYearWithDateYYYY() {
emptyEntry.setField("date", "2003");
Assert.assertEquals(Optional.of("2003"), emptyEntry.getFieldOrAlias("year"));
}
@Test
public void getFieldOrAliasYearWithDateYYYYMM() {
emptyEntry.setField("date", "2003-03");
Assert.assertEquals(Optional.of("2003"), emptyEntry.getFieldOrAlias("year"));
}
@Test
public void getFieldOrAliasYearWithDateYYYYMMDD() {
emptyEntry.setField("date", "2003-03-30");
Assert.assertEquals(Optional.of("2003"), emptyEntry.getFieldOrAlias("year"));
}
@Test
public void getFieldOrAliasMonthWithDateYYYYReturnsNull() {
emptyEntry.setField("date", "2003");
Assert.assertEquals(Optional.empty(), emptyEntry.getFieldOrAlias("month"));
}
@Test
public void getFieldOrAliasMonthWithDateYYYYMM() {
emptyEntry.setField("date", "2003-03");
Assert.assertEquals(Optional.of("3"), emptyEntry.getFieldOrAlias("month"));
}
@Test
public void getFieldOrAliasMonthWithDateYYYYMMDD() {
emptyEntry.setField("date", "2003-03-30");
Assert.assertEquals(Optional.of("3"), emptyEntry.getFieldOrAlias("month"));
}
@Test(expected = NullPointerException.class)
public void setNullField() {
emptyEntry.setField(null);
Assert.fail();
}
@Test(expected = NullPointerException.class)
public void addNullKeywordThrowsNPE() {
keywordEntry.addKeyword(null, ", ");
Assert.fail();
}
@Test(expected = NullPointerException.class)
public void putNullKeywordListThrowsNPE() {
keywordEntry.putKeywords(null, ", ");
Assert.fail();
}
@Test(expected = NullPointerException.class)
public void putNullKeywordSeparatorThrowsNPE() {
keywordEntry.putKeywords(Arrays.asList("A", "B"), null);
Assert.fail();
}
@Test
public void testGetSeparatedKeywordsAreCorrect() {
String[] expected = {"Foo", "Bar"};
Assert.assertArrayEquals(expected, keywordEntry.getKeywords().toArray());
}
@Test
public void testAddKeywordIsCorrect() {
keywordEntry.addKeyword("FooBar", ", ");
String[] expected = {"Foo", "Bar", "FooBar"};
Assert.assertArrayEquals(expected, keywordEntry.getKeywords().toArray());
}
@Test
public void testAddKeywordHasChanged() {
keywordEntry.addKeyword("FooBar", ", ");
Assert.assertTrue(keywordEntry.hasChanged());
}
@Test
public void testAddKeywordTwiceYiedsOnlyOne() {
keywordEntry.addKeyword("FooBar", ", ");
keywordEntry.addKeyword("FooBar", ", ");
String[] expected = {"Foo", "Bar", "FooBar"};
Assert.assertArrayEquals(expected, keywordEntry.getKeywords().toArray());
}
@Test
public void addKeywordIsCaseSensitive() {
keywordEntry.addKeyword("FOO", ", ");
String[] expected = {"Foo", "Bar", "FOO"};
Assert.assertArrayEquals(expected, keywordEntry.getKeywords().toArray());
}
@Test
public void testAddKeywordWithDifferentCapitalizationChanges() {
keywordEntry.addKeyword("FOO", ", ");
Assert.assertTrue(keywordEntry.hasChanged());
}
@Test
public void testAddKeywordEmptyKeywordIsNotAdded() {
keywordEntry.addKeyword("", ", ");
String[] expected = {"Foo", "Bar"};
Assert.assertArrayEquals(expected, keywordEntry.getKeywords().toArray());
}
@Test
public void testAddKeywordEmptyKeywordNotChanged() {
keywordEntry.addKeyword("", ", ");
Assert.assertFalse(keywordEntry.hasChanged());
}
@Test
public void texNewBibEntryHasNoKeywords() {
Assert.assertTrue(emptyEntry.getKeywords().isEmpty());
}
@Test
public void texNewBibEntryHasNoKeywordsEvenAfterAddingEmptyKeyword() {
emptyEntry.addKeyword("", ", ");
Assert.assertTrue(emptyEntry.getKeywords().isEmpty());
}
@Test
public void texNewBibEntryAfterAddingEmptyKeywordNotChanged() {
emptyEntry.addKeyword("", ", ");
Assert.assertFalse(emptyEntry.hasChanged());
}
@Test
public void testAddKeywordsWorksAsExpected() {
String[] expected = {"Foo", "Bar"};
emptyEntry.addKeywords(keywordEntry.getKeywords(), ", ");
Assert.assertArrayEquals(expected, emptyEntry.getKeywords().toArray());
}
@Test
public void testPutKeywordsOverwritesOldKeywords() {
keywordEntry.putKeywords(Arrays.asList("Yin", "Yang"), ", ");
String[] expected = {"Yin", "Yang"};
Assert.assertArrayEquals(expected, keywordEntry.getKeywords().toArray());
}
@Test
public void testPutKeywordsHasChanged() {
keywordEntry.putKeywords(Arrays.asList("Yin", "Yang"), ", ");
Assert.assertTrue(keywordEntry.hasChanged());
}
@Test
public void testPutKeywordsPutEmpyListErasesPreviousKeywords() {
keywordEntry.putKeywords(Collections.emptyList(), ", ");
Assert.assertTrue(keywordEntry.getKeywords().isEmpty());
}
@Test
public void testPutKeywordsPutEmpyListHasChanged() {
keywordEntry.putKeywords(Collections.emptyList(), ", ");
Assert.assertTrue(keywordEntry.hasChanged());
}
@Test
public void testPutKeywordsPutEmpyListToEmptyBibentry() {
emptyEntry.putKeywords(Collections.emptyList(), ", ");
Assert.assertTrue(emptyEntry.getKeywords().isEmpty());
}
@Test
public void testPutKeywordsPutEmpyListToEmptyBibentryNotChanged() {
emptyEntry.putKeywords(Collections.emptyList(), ", ");
Assert.assertFalse(emptyEntry.hasChanged());
}
@Test
public void putKeywordsToEmptyReturnsNoChange() {
Optional<FieldChange> change = emptyEntry.putKeywords(Collections.emptyList(),
", ");
Assert.assertEquals(Optional.empty(), change);
}
@Test
public void clearKeywordsReturnsChange() {
Optional<FieldChange> change = keywordEntry.putKeywords(Collections.emptyList(),
", ");
Assert.assertEquals(Optional.of(new FieldChange(keywordEntry, "keywords", "Foo, Bar", null)), change);
}
@Test
public void changeKeywordsReturnsChange() {
Optional<FieldChange> change = keywordEntry.putKeywords(Arrays.asList("Test", "FooTest"),
", ");
Assert.assertEquals(Optional.of(new FieldChange(keywordEntry, "keywords", "Foo, Bar", "Test, FooTest")), change);
}
@Test
public void putKeywordsToSameReturnsNoChange() {
Optional<FieldChange> change = keywordEntry.putKeywords(Arrays.asList("Foo", "Bar"),
", ");
Assert.assertEquals(Optional.empty(), change);
}
@Test
public void testGroupAndSearchHits() {
BibEntry be = new BibEntry();
be.setGroupHit(true);
Assert.assertTrue(be.isGroupHit());
be.setGroupHit(false);
Assert.assertFalse(be.isGroupHit());
be.setSearchHit(true);
Assert.assertTrue(be.isSearchHit());
be.setSearchHit(false);
Assert.assertFalse(be.isSearchHit());
}
@Test
public void testCiteKeyAndID() {
BibEntry be = new BibEntry();
Assert.assertFalse(be.hasCiteKey());
be.setField("author", "Albert Einstein");
be.setCiteKey("Einstein1931");
Assert.assertTrue(be.hasCiteKey());
Assert.assertEquals(Optional.of("Einstein1931"), be.getCiteKeyOptional());
Assert.assertEquals(Optional.of("Albert Einstein"), be.getFieldOptional("author"));
be.clearField("author");
Assert.assertEquals(Optional.empty(), be.getFieldOptional("author"));
String id = IdGenerator.next();
be.setId(id);
Assert.assertEquals(id, be.getId());
}
}
|
motokito/jabref
|
src/test/java/net/sf/jabref/model/entry/BibEntryTests.java
|
Java
|
mit
| 12,270 |
<?php
/**
* Author: Nil Portugués Calderó <[email protected]>
* Date: 9/20/14
* Time: 12:03 PM
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tests\NilPortugues\Validator\Validation\Object;
use NilPortugues\Validator\Validation\Object\ObjectValidation;
use Tests\NilPortugues\Validator\Resources\Dummy;
/**
* Class ObjectValidationTest
* @package Tests\NilPortugues\Validator\Validation\ObjectAttribute
*/
class ObjectValidationTest extends \PHPUnit_Framework_TestCase
{
/**
* @test
*/
public function itShouldCheckIfIsObject()
{
$this->assertTrue(ObjectValidation::isObject(new \stdClass()));
$this->assertFalse(ObjectValidation::isObject('a'));
}
/**
* @test
*/
public function itShouldCheckIfIsInstanceOf()
{
$this->assertTrue(ObjectValidation::isInstanceOf(new \DateTime(), 'DateTime'));
$this->assertFalse(ObjectValidation::isInstanceOf(new \stdClass(), 'DateTime'));
$this->assertFalse(ObjectValidation::isInstanceOf('a', 'DateTime'));
}
/**
* @test
*/
public function itShouldCheckIfHasProperty()
{
$dummy = new Dummy();
$this->assertTrue(ObjectValidation::hasProperty($dummy, 'userName'));
$this->assertFalse(ObjectValidation::hasProperty($dummy, 'password'));
}
/**
* @test
*/
public function itShouldCheckIfHasMethod()
{
$dummy = new Dummy();
$this->assertTrue(ObjectValidation::hasMethod($dummy, 'getUserName'));
$this->assertFalse(ObjectValidation::hasMethod($dummy, 'getPassword'));
}
/**
* @test
*/
public function itShouldCheckIfHasParentClass()
{
$this->assertTrue(ObjectValidation::hasParentClass(new Dummy()));
$this->assertFalse(ObjectValidation::hasParentClass(new \stdClass()));
}
/**
* @test
*/
public function itShouldCheckIfIsChildOf()
{
$dummy = new Dummy();
$this->assertTrue(ObjectValidation::isChildOf($dummy, 'DateTime'));
$this->assertFalse(ObjectValidation::isChildOf($dummy, 'DateTimeZone'));
}
/**
* @test
*/
public function itShouldCheckIfInheritsFrom()
{
$dummy = new Dummy();
$this->assertTrue(ObjectValidation::inheritsFrom($dummy, 'DateTime'));
$this->assertFalse(ObjectValidation::inheritsFrom($dummy, 'DateTimeZone'));
}
/**
* @test
*/
public function itShouldCheckIfHasInterface()
{
$dummy = new Dummy();
$this->assertTrue(
ObjectValidation::hasInterface(
$dummy,
'Tests\NilPortugues\Validator\Resources\DummyInterface'
)
);
$this->assertFalse(ObjectValidation::inheritsFrom($dummy, 'DateTimeZone'));
}
}
|
nilportugues/validator
|
tests/Validation/Object/ObjectValidationTest.php
|
PHP
|
mit
| 2,921 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en_US" lang="en_US">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- qtestcase.cpp -->
<title>Qt 4.8: QTouchEventSequence Class Reference</title>
<link rel="stylesheet" type="text/css" href="style/style.css" />
<script src="scripts/jquery.js" type="text/javascript"></script>
<script src="scripts/functions.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="style/superfish.css" />
<link rel="stylesheet" type="text/css" href="style/narrow.css" />
<!--[if IE]>
<meta name="MSSmartTagsPreventParsing" content="true">
<meta http-equiv="imagetoolbar" content="no">
<![endif]-->
<!--[if lt IE 7]>
<link rel="stylesheet" type="text/css" href="style/style_ie6.css">
<![endif]-->
<!--[if IE 7]>
<link rel="stylesheet" type="text/css" href="style/style_ie7.css">
<![endif]-->
<!--[if IE 8]>
<link rel="stylesheet" type="text/css" href="style/style_ie8.css">
<![endif]-->
<script src="scripts/superfish.js" type="text/javascript"></script>
<script src="scripts/narrow.js" type="text/javascript"></script>
</head>
<body class="" onload="CheckEmptyAndLoadList();">
<div class="header" id="qtdocheader">
<div class="content">
<div id="nav-logo">
<a href="index.html">Home</a></div>
<a href="index.html" class="qtref"><span>Qt Reference Documentation</span></a>
<div id="narrowsearch"></div>
<div id="nav-topright">
<ul>
<li class="nav-topright-home"><a href="http://qt.digia.com/">Qt HOME</a></li>
<li class="nav-topright-dev"><a href="http://qt-project.org/">DEV</a></li>
<li class="nav-topright-doc nav-topright-doc-active"><a href="http://qt-project.org/doc/">
DOC</a></li>
<li class="nav-topright-blog"><a href="http://blog.qt.digia.com/">BLOG</a></li>
</ul>
</div>
<div id="shortCut">
<ul>
<li class="shortCut-topleft-inactive"><span><a href="index.html">Qt 4.8</a></span></li>
<li class="shortCut-topleft-active"><a href="http://qt-project.org/doc/">ALL VERSIONS </a></li>
</ul>
</div>
<ul class="sf-menu" id="narrowmenu">
<li><a href="#">API Lookup</a>
<ul>
<li><a href="classes.html">Class index</a></li>
<li><a href="functions.html">Function index</a></li>
<li><a href="modules.html">Modules</a></li>
<li><a href="namespaces.html">Namespaces</a></li>
<li><a href="qtglobal.html">Global Declarations</a></li>
<li><a href="qdeclarativeelements.html">QML elements</a></li>
</ul>
</li>
<li><a href="#">Qt Topics</a>
<ul>
<li><a href="qt-basic-concepts.html">Programming with Qt</a></li>
<li><a href="qtquick.html">Device UIs & Qt Quick</a></li>
<li><a href="qt-gui-concepts.html">UI Design with Qt</a></li>
<li><a href="supported-platforms.html">Supported Platforms</a></li>
<li><a href="technology-apis.html">Qt and Key Technologies</a></li>
<li><a href="best-practices.html">How-To's and Best Practices</a></li>
</ul>
</li>
<li><a href="#">Examples</a>
<ul>
<li><a href="all-examples.html">Examples</a></li>
<li><a href="tutorials.html">Tutorials</a></li>
<li><a href="demos.html">Demos</a></li>
<li><a href="qdeclarativeexamples.html">QML Examples</a></li>
</ul>
</li>
</ul>
</div>
</div>
<div class="wrapper">
<div class="hd">
<span></span>
</div>
<div class="bd group">
<div class="sidebar">
<div class="searchlabel">
Search index:</div>
<div class="search" id="sidebarsearch">
<form id="qtdocsearch" action="" onsubmit="return false;">
<fieldset>
<input type="text" name="searchstring" id="pageType" value="" />
<div id="resultdialog">
<a href="#" id="resultclose">Close</a>
<p id="resultlinks" class="all"><a href="#" id="showallresults">All</a> | <a href="#" id="showapiresults">API</a> | <a href="#" id="showarticleresults">Articles</a> | <a href="#" id="showexampleresults">Examples</a></p>
<p id="searchcount" class="all"><span id="resultcount"></span><span id="apicount"></span><span id="articlecount"></span><span id="examplecount"></span> results:</p>
<ul id="resultlist" class="all">
</ul>
</div>
</fieldset>
</form>
</div>
<div class="box first bottombar" id="lookup">
<h2 title="API Lookup"><span></span>
API Lookup</h2>
<div id="list001" class="list">
<ul id="ul001" >
<li class="defaultLink"><a href="classes.html">Class index</a></li>
<li class="defaultLink"><a href="functions.html">Function index</a></li>
<li class="defaultLink"><a href="modules.html">Modules</a></li>
<li class="defaultLink"><a href="namespaces.html">Namespaces</a></li>
<li class="defaultLink"><a href="qtglobal.html">Global Declarations</a></li>
<li class="defaultLink"><a href="qdeclarativeelements.html">QML elements</a></li>
</ul>
</div>
</div>
<div class="box bottombar" id="topics">
<h2 title="Qt Topics"><span></span>
Qt Topics</h2>
<div id="list002" class="list">
<ul id="ul002" >
<li class="defaultLink"><a href="qt-basic-concepts.html">Programming with Qt</a></li>
<li class="defaultLink"><a href="qtquick.html">Device UIs & Qt Quick</a></li>
<li class="defaultLink"><a href="qt-gui-concepts.html">UI Design with Qt</a></li>
<li class="defaultLink"><a href="supported-platforms.html">Supported Platforms</a></li>
<li class="defaultLink"><a href="technology-apis.html">Qt and Key Technologies</a></li>
<li class="defaultLink"><a href="best-practices.html">How-To's and Best Practices</a></li>
</ul>
</div>
</div>
<div class="box" id="examples">
<h2 title="Examples"><span></span>
Examples</h2>
<div id="list003" class="list">
<ul id="ul003">
<li class="defaultLink"><a href="all-examples.html">Examples</a></li>
<li class="defaultLink"><a href="tutorials.html">Tutorials</a></li>
<li class="defaultLink"><a href="demos.html">Demos</a></li>
<li class="defaultLink"><a href="qdeclarativeexamples.html">QML Examples</a></li>
</ul>
</div>
</div>
</div>
<div class="wrap">
<div class="toolbar">
<div class="breadcrumb toolblock">
<ul>
<li class="first"><a href="index.html">Home</a></li>
<!-- Breadcrumbs go here -->
<li><a href="modules.html">Modules</a></li>
<li><a href="qttest.html">QtTest</a></li>
<li>QTouchEventSequence</li>
</ul>
</div>
<div class="toolbuttons toolblock">
<ul>
<li id="smallA" class="t_button">A</li>
<li id="medA" class="t_button active">A</li>
<li id="bigA" class="t_button">A</li>
<li id="print" class="t_button"><a href="javascript:this.print();">
<span>Print</span></a></li>
</ul>
</div>
</div>
<div class="content mainContent">
<div class="toc">
<h3><a name="toc">Contents</a></h3>
<ul>
<li class="level1"><a href="#public-functions">Public Functions</a></li>
<li class="level1"><a href="#details">Detailed Description</a></li>
</ul>
</div>
<h1 class="title">QTouchEventSequence Class Reference</h1>
<span class="small-subtitle">(QTest::QTouchEventSequence)<br/></span>
<!-- $$$QTouchEventSequence-brief -->
<p>The QTouchEventSequence class is used to simulate a sequence of touch events. <a href="#details">More...</a></p>
<!-- @@@QTouchEventSequence -->
<pre class="cpp"> <span class="preprocessor">#include <<a href="qtest.html">QTest</a>></span></pre><p>This class was introduced in Qt 4.6.</p>
<ul>
<li><a href="qtest-qtoucheventsequence-members.html">List of all members, including inherited members</a></li>
</ul>
<a name="public-functions"></a>
<h2>Public Functions</h2>
<table class="alignedsummary">
<tr><td class="memItemLeft rightAlign topAlign"> </td><td class="memItemRight bottomAlign"><b><a href="qtest-qtoucheventsequence.html#dtor.QTouchEventSequence">~QTouchEventSequence</a></b> ()</td></tr>
<tr><td class="memItemLeft rightAlign topAlign"> QTouchEventSequence & </td><td class="memItemRight bottomAlign"><b><a href="qtest-qtoucheventsequence.html#move">move</a></b> ( int <i>touchId</i>, const QPoint & <i>pt</i>, QWidget * <i>widget</i> = 0 )</td></tr>
<tr><td class="memItemLeft rightAlign topAlign"> QTouchEventSequence & </td><td class="memItemRight bottomAlign"><b><a href="qtest-qtoucheventsequence.html#press">press</a></b> ( int <i>touchId</i>, const QPoint & <i>pt</i>, QWidget * <i>widget</i> = 0 )</td></tr>
<tr><td class="memItemLeft rightAlign topAlign"> QTouchEventSequence & </td><td class="memItemRight bottomAlign"><b><a href="qtest-qtoucheventsequence.html#release">release</a></b> ( int <i>touchId</i>, const QPoint & <i>pt</i>, QWidget * <i>widget</i> = 0 )</td></tr>
<tr><td class="memItemLeft rightAlign topAlign"> QTouchEventSequence & </td><td class="memItemRight bottomAlign"><b><a href="qtest-qtoucheventsequence.html#stationary">stationary</a></b> ( int <i>touchId</i> )</td></tr>
</table>
<a name="details"></a>
<!-- $$$QTouchEventSequence-description -->
<div class="descr">
<h2>Detailed Description</h2>
<p>The QTouchEventSequence class is used to simulate a sequence of touch events.</p>
<p>To simulate a sequence of touch events on a specific device for a widget, call QTest::touchEvent to create a QTouchEventSequence instance. Add touch events to the sequence by calling <a href="qtest-qtoucheventsequence.html#press">press</a>(), <a href="qtest-qtoucheventsequence.html#move">move</a>(), <a href="qtest-qtoucheventsequence.html#release">release</a>() and <a href="qtest-qtoucheventsequence.html#stationary">stationary</a>(), and let the instance run out of scope to commit the sequence to the event system.</p>
<p>Example:</p>
<pre class="cpp"> <span class="type"><a href="qwidget.html">QWidget</a></span> widget;
<span class="type"><a href="qtest.html">QTest</a></span><span class="operator">::</span>touchEvent(<span class="operator">&</span>widget)
<span class="operator">.</span>press(<span class="number">0</span><span class="operator">,</span> <span class="type"><a href="qpoint.html">QPoint</a></span>(<span class="number">10</span><span class="operator">,</span> <span class="number">10</span>));
<span class="type"><a href="qtest.html">QTest</a></span><span class="operator">::</span>touchEvent(<span class="operator">&</span>widget)
<span class="operator">.</span>stationary(<span class="number">0</span>)
<span class="operator">.</span>press(<span class="number">1</span><span class="operator">,</span> <span class="type"><a href="qpoint.html">QPoint</a></span>(<span class="number">40</span><span class="operator">,</span> <span class="number">10</span>));
<span class="type"><a href="qtest.html">QTest</a></span><span class="operator">::</span>touchEvent(<span class="operator">&</span>widget)
<span class="operator">.</span>move(<span class="number">0</span><span class="operator">,</span> <span class="type"><a href="qpoint.html">QPoint</a></span>(<span class="number">12</span><span class="operator">,</span> <span class="number">12</span>))
<span class="operator">.</span>move(<span class="number">1</span><span class="operator">,</span> <span class="type"><a href="qpoint.html">QPoint</a></span>(<span class="number">45</span><span class="operator">,</span> <span class="number">5</span>));
<span class="type"><a href="qtest.html">QTest</a></span><span class="operator">::</span>touchEvent(<span class="operator">&</span>widget)
<span class="operator">.</span>release(<span class="number">0</span>)
<span class="operator">.</span>release(<span class="number">1</span>);</pre>
</div>
<!-- @@@QTouchEventSequence -->
<div class="func">
<h2>Member Function Documentation</h2>
<!-- $$$~QTouchEventSequence[overload1]$$$~QTouchEventSequence -->
<h3 class="fn"><a name="dtor.QTouchEventSequence"></a>QTouchEventSequence::<span class="name">~QTouchEventSequence</span> ()</h3>
<p>Commits this sequence of touch events and frees allocated resources.</p>
<!-- @@@~QTouchEventSequence -->
<!-- $$$move[overload1]$$$moveintconstQPoint&QWidget* -->
<h3 class="fn"><a name="move"></a><span class="type">QTouchEventSequence</span> & QTouchEventSequence::<span class="name">move</span> ( <span class="type">int</span> <i>touchId</i>, const <span class="type"><a href="qpoint.html">QPoint</a></span> & <i>pt</i>, <span class="type"><a href="qwidget.html">QWidget</a></span> * <i>widget</i> = 0 )</h3>
<p>Adds a move event for touchpoint <i>touchId</i> at position <i>pt</i> to this sequence and returns a reference to this <a href="qtest-qtoucheventsequence.html">QTouchEventSequence</a>.</p>
<p>The position <i>pt</i> is interpreted as relative to <i>widget</i>. If <i>widget</i> is the null pointer, then <i>pt</i> is interpreted as relative to the widget provided when instantiating this <a href="qtest-qtoucheventsequence.html">QTouchEventSequence</a>.</p>
<p>Simulates that the user moved the finger identified by <i>touchId</i>.</p>
<!-- @@@move -->
<!-- $$$press[overload1]$$$pressintconstQPoint&QWidget* -->
<h3 class="fn"><a name="press"></a><span class="type">QTouchEventSequence</span> & QTouchEventSequence::<span class="name">press</span> ( <span class="type">int</span> <i>touchId</i>, const <span class="type"><a href="qpoint.html">QPoint</a></span> & <i>pt</i>, <span class="type"><a href="qwidget.html">QWidget</a></span> * <i>widget</i> = 0 )</h3>
<p>Adds a press event for touchpoint <i>touchId</i> at position <i>pt</i> to this sequence and returns a reference to this <a href="qtest-qtoucheventsequence.html">QTouchEventSequence</a>.</p>
<p>The position <i>pt</i> is interpreted as relative to <i>widget</i>. If <i>widget</i> is the null pointer, then <i>pt</i> is interpreted as relative to the widget provided when instantiating this <a href="qtest-qtoucheventsequence.html">QTouchEventSequence</a>.</p>
<p>Simulates that the user pressed the touch screen or pad with the finger identified by <i>touchId</i>.</p>
<!-- @@@press -->
<!-- $$$release[overload1]$$$releaseintconstQPoint&QWidget* -->
<h3 class="fn"><a name="release"></a><span class="type">QTouchEventSequence</span> & QTouchEventSequence::<span class="name">release</span> ( <span class="type">int</span> <i>touchId</i>, const <span class="type"><a href="qpoint.html">QPoint</a></span> & <i>pt</i>, <span class="type"><a href="qwidget.html">QWidget</a></span> * <i>widget</i> = 0 )</h3>
<p>Adds a release event for touchpoint <i>touchId</i> at position <i>pt</i> to this sequence and returns a reference to this <a href="qtest-qtoucheventsequence.html">QTouchEventSequence</a>.</p>
<p>The position <i>pt</i> is interpreted as relative to <i>widget</i>. If <i>widget</i> is the null pointer, then <i>pt</i> is interpreted as relative to the widget provided when instantiating this <a href="qtest-qtoucheventsequence.html">QTouchEventSequence</a>.</p>
<p>Simulates that the user lifted the finger identified by <i>touchId</i>.</p>
<!-- @@@release -->
<!-- $$$stationary[overload1]$$$stationaryint -->
<h3 class="fn"><a name="stationary"></a><span class="type">QTouchEventSequence</span> & QTouchEventSequence::<span class="name">stationary</span> ( <span class="type">int</span> <i>touchId</i> )</h3>
<p>Adds a stationary event for touchpoint <i>touchId</i> to this sequence and returns a reference to this <a href="qtest-qtoucheventsequence.html">QTouchEventSequence</a>.</p>
<p>Simulates that the user did not move the finger identified by <i>touchId</i>.</p>
<!-- @@@stationary -->
</div>
</div>
</div>
</div>
<div class="ft">
<span></span>
</div>
</div>
<div class="footer">
<p>
<acronym title="Copyright">©</acronym> 2013 Digia Plc and/or its
subsidiaries. Documentation contributions included herein are the copyrights of
their respective owners.</p>
<br />
<p>
The documentation provided herein is licensed under the terms of the
<a href="http://www.gnu.org/licenses/fdl.html">GNU Free Documentation
License version 1.3</a> as published by the Free Software Foundation.</p>
<p>
Documentation sources may be obtained from <a href="http://www.qt-project.org">
www.qt-project.org</a>.</p>
<br />
<p>
Digia, Qt and their respective logos are trademarks of Digia Plc
in Finland and/or other countries worldwide. All other trademarks are property
of their respective owners. <a title="Privacy Policy"
href="http://en.gitorious.org/privacy_policy/">Privacy Policy</a></p>
</div>
<script src="scripts/functions.js" type="text/javascript"></script>
</body>
</html>
|
stephaneAG/PengPod700
|
QtEsrc/qt-everywhere-opensource-src-4.8.5/doc/html/qtest-qtoucheventsequence.html
|
HTML
|
mit
| 17,812 |
(function() {
var Configuration, DI, DIFactory, Database, Http, Mail, callsite, di, dir, expect, factory, path;
expect = require('chai').expect;
path = require('path');
callsite = require('callsite');
DI = require('../../lib/DI');
DIFactory = require('../../DIFactory');
Configuration = require('../../Configuration');
Http = require('../data/lib/Http');
Database = require('../data/lib/MySql');
Mail = require('../data/lib/Mail');
dir = path.resolve(__dirname + '/../data');
di = null;
factory = null;
describe('DIFactory', function() {
beforeEach(function() {
factory = new DIFactory(dir + '/config/config.json');
di = factory.create();
return di.basePath = dir;
});
describe('#constructor()', function() {
it('should resolve relative path to absolute path', function() {
factory = new DIFactory('../data/config/config.json');
expect(factory.path).to.be.equal(dir + '/config/config.json');
return expect(factory.create().parameters.language).to.be.equal('en');
});
it('should create di with custom config object', function() {
var config;
config = new Configuration;
config.addConfig('../data/config/config.json');
config.addConfig('../data/config/sections.json', 'local');
factory = new DIFactory(config);
di = factory.create();
expect(di).to.be.an["instanceof"](DI);
return expect(di.parameters.users.david).to.be.equal('divad');
});
it('should create database service from factory with list of parameters', function() {
var db;
factory = new DIFactory(dir + '/config/database.json');
di = factory.create();
db = di.get('database');
expect(db).to.be.an["instanceof"](Database);
return expect(db.parameters).to.be.eql({
host: 'localhost',
user: 'root',
password: 'toor',
database: 'application'
});
});
return it('should create service with list of parameters', function() {
var mail;
factory = new DIFactory(dir + '/config/mail.json');
di = factory.create();
mail = di.get('mail');
expect(mail).to.be.an["instanceof"](Mail);
return expect(mail.setup).to.be.eql({
type: 'SMTP',
auth: {
user: 'root',
pass: 'toor'
}
});
});
});
describe('#parameters', function() {
return it('should contain all parameters', function() {
return expect(di.parameters).to.be.eql({
language: 'en',
users: {
david: '123456',
admin: 'nimda'
},
database: {
user: 'admin',
password: 'nimda'
}
});
});
});
describe('#getParameter()', function() {
it('should throw an error if di object was not created from DIFactory', function() {
di = new DI;
return expect(function() {
return di.getParameter('buf');
}).to["throw"](Error, 'DI container was not created with DIFactory.');
});
return it('should return expanded parameter', function() {
return expect(di.getParameter('database.password')).to.be.equal('nimda');
});
});
return describe('#get()', function() {
it('should load service defined with relative path', function() {
factory = new DIFactory(dir + '/config/relative.json');
di = factory.create();
return expect(di.get('http')).to.be.an["instanceof"](Http);
});
it('should create services with derived arguments', function() {
var application;
factory = new DIFactory(dir + '/config/derivedArguments.json');
di = factory.create();
application = di.get('application');
expect(application.data).to.be.equal('hello David');
return expect(application.namespace).to.be["false"];
});
it('should create service derived from other service', function() {
factory = new DIFactory(dir + '/config/derivedService.json');
di = factory.create();
return expect(di.get('http')).to.be.an["instanceof"](Http);
});
it('should create service from exported factory function', function() {
var mail;
factory = new DIFactory(dir + '/config/factory.json');
di = factory.create();
mail = di.get('mail');
expect(mail).to.be.an["instanceof"](Mail);
expect(mail.setup).to.be.eql({
type: 'SMTP',
auth: {
user: 'root',
pass: 'toor'
}
});
return expect(mail.http).to.be.an["instanceof"](Http);
});
it('should create npm service', function() {
factory = new DIFactory(dir + '/config/nodeModules.json');
di = factory.create();
expect(di.get('callsite')).to.be.equal(callsite);
return expect(di.get('setup').callsite).to.be.equal(callsite);
});
return it('should create npm service from function factory', function() {
factory = new DIFactory(dir + '/config/nodeModules.json');
di = factory.create();
return expect(di.get('callsiteFactory')).to.be.equal(callsite);
});
});
});
}).call(this);
|
Carrooi/Node-DependencyInjection
|
test/lib/DIFactory.js
|
JavaScript
|
mit
| 5,317 |
/*
+------------------------------------------------------------------------+
| Zephir Language |
+------------------------------------------------------------------------+
| Copyright (c) 2011-2015 Zephir Team (http://www.zephir-lang.com) |
+------------------------------------------------------------------------+
| This source file is subject to the New BSD License that is bundled |
| with this package in the file docs/LICENSE.txt. |
| |
| If you did not receive a copy of the license and are unable to |
| obtain it through the world-wide-web, please send an email |
| to [email protected] so we can send you a copy immediately. |
+------------------------------------------------------------------------+
| Authors: Andres Gutierrez <[email protected]> |
| Eduar Carvajal <[email protected]> |
+------------------------------------------------------------------------+
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <php.h>
#include <ext/standard/php_string.h>
#include <ext/standard/php_math.h>
#include <ext/standard/php_rand.h>
#include "php_ext.h"
#include "kernel/main.h"
#include "kernel/memory.h"
#include "kernel/string.h"
#include "kernel/operators.h"
#include "Zend/zend_operators.h"
double zephir_sqrt(zval *op1)
{
switch (Z_TYPE_P(op1)) {
case IS_LONG:
return sqrt(Z_LVAL_P(op1));
case IS_ARRAY:
case IS_OBJECT:
case IS_RESOURCE:
zend_error(E_WARNING, "Unsupported operand types");
break;
}
return sqrt(zephir_get_numberval(op1));
}
double zephir_sin(zval *op1)
{
switch (Z_TYPE_P(op1)) {
case IS_LONG:
return sin(Z_LVAL_P(op1));
case IS_ARRAY:
case IS_OBJECT:
case IS_RESOURCE:
zend_error(E_WARNING, "Unsupported operand types");
break;
}
return sin(zephir_get_numberval(op1));
}
double zephir_asin(zval *op1)
{
switch (Z_TYPE_P(op1)) {
case IS_LONG:
return asin(Z_LVAL_P(op1));
case IS_ARRAY:
case IS_OBJECT:
case IS_RESOURCE:
zend_error(E_WARNING, "Unsupported operand types");
break;
}
return asin(zephir_get_numberval(op1));
}
double zephir_cos(zval *op1)
{
switch (Z_TYPE_P(op1)) {
case IS_LONG:
return cos(Z_LVAL_P(op1));
case IS_ARRAY:
case IS_OBJECT:
case IS_RESOURCE:
zend_error(E_WARNING, "Unsupported operand types");
break;
}
return cos(zephir_get_numberval(op1));
}
double zephir_acos(zval *op1)
{
switch (Z_TYPE_P(op1)) {
case IS_LONG:
return acos(Z_LVAL_P(op1));
case IS_ARRAY:
case IS_OBJECT:
case IS_RESOURCE:
zend_error(E_WARNING, "Unsupported operand types");
break;
}
return acos(zephir_get_numberval(op1));
}
double zephir_tan(zval *op1)
{
switch (Z_TYPE_P(op1)) {
case IS_LONG:
return tan(Z_LVAL_P(op1));
case IS_ARRAY:
case IS_OBJECT:
case IS_RESOURCE:
zend_error(E_WARNING, "Unsupported operand types");
break;
}
return tan(zephir_get_numberval(op1));
}
double zephir_floor(zval *op1)
{
switch (Z_TYPE_P(op1)) {
case IS_LONG:
return (double) Z_LVAL_P(op1);
case IS_ARRAY:
case IS_OBJECT:
case IS_RESOURCE:
zend_error(E_WARNING, "Unsupported operand types");
break;
}
return floor(zephir_get_numberval(op1));
}
double zephir_ceil(zval *op1)
{
switch (Z_TYPE_P(op1)) {
case IS_LONG:
return (double) Z_LVAL_P(op1);
case IS_ARRAY:
case IS_OBJECT:
case IS_RESOURCE:
zend_error(E_WARNING, "Unsupported operand types");
break;
}
return ceil(zephir_get_numberval(op1));
}
extern double _php_math_round(double value, int places, int mode);
void zephir_round(zval *return_value, zval *op1, zval *op2, zval *op3)
{
int places = 0;
long mode = PHP_ROUND_HALF_UP;
double return_val;
convert_scalar_to_number_ex(op1);
if (op2) {
places = zephir_get_intval_ex(op2);
}
if (op3) {
mode = zephir_get_intval_ex(op3);
}
switch (Z_TYPE_P(op1)) {
case IS_LONG:
/* Simple case - long that doesn't need to be rounded. */
if (places >= 0) {
RETURN_DOUBLE((double) Z_LVAL_P(op1));
}
/* break omitted intentionally */
case IS_DOUBLE:
return_val = (Z_TYPE_P(op1) == IS_LONG) ? (double)Z_LVAL_P(op1) : Z_DVAL_P(op1);
return_val = _php_math_round(return_val, places, mode);
RETURN_DOUBLE(return_val);
break;
default:
RETURN_FALSE;
break;
}
}
long zephir_mt_rand(long min, long max)
{
long number;
if (max < min) {
php_error_docref(NULL, E_WARNING, "max(%ld) is smaller than min(%ld)", max, min);
return 0;
}
if (!BG(mt_rand_is_seeded)) {
php_mt_srand(GENERATE_SEED());
}
number = (long) (php_mt_rand() >> 1);
RAND_RANGE(number, min, max, PHP_MT_RAND_MAX);
return number;
}
double zephir_ldexp(zval *value, zval *expval TSRMLS_DC)
{
int exp = (int) zephir_get_numberval(expval);
switch (Z_TYPE_P(value)) {
case IS_LONG:
return (double) ldexp(Z_LVAL_P(value), exp);
case IS_DOUBLE:
return (double) ldexp(Z_DVAL_P(value), exp);
case IS_ARRAY:
case IS_OBJECT:
case IS_RESOURCE:
zend_error(E_WARNING, "Unsupported operand types");
break;
}
return ldexp(zephir_get_numberval(value), exp);
}
|
aaam/zephir
|
kernels/ZendEngine3/math.c
|
C
|
mit
| 5,282 |
/*
* The MIT License (MIT)
*
* Copyright (c) 2016 CNES
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/*
*/
#include "mal.h"
mal_element_holder_t *mal_element_holder_new() {
mal_element_holder_t *self = (mal_element_holder_t *) calloc(
1, sizeof(mal_element_holder_t));
if (!self)
return NULL;
return self;
}
void mal_element_holder_destroy(mal_element_holder_t **self_p) {
if (self_p && *self_p) {
mal_element_holder_t *self = *self_p;
free(self);
*self_p = NULL;
}
}
bool mal_element_holder_get_presence_flag(mal_element_holder_t *self) {
return self->presence_flag;
}
void mal_element_holder_set_presence_flag(mal_element_holder_t *self,
bool presence_flag) {
self->presence_flag = presence_flag;
}
long mal_element_holder_get_short_form(mal_element_holder_t *self) {
return self->short_form;
}
void mal_element_holder_set_short_form(mal_element_holder_t *self,
long short_form) {
self->short_form = short_form;
}
union mal_element_t mal_element_holder_get_value(mal_element_holder_t *self) {
return self->value;
}
void mal_element_holder_set_value(mal_element_holder_t *self,
union mal_element_t value) {
self->value = value;
}
void mal_element_holder_test(bool verbose) {
printf(" * mal_element_holder: ");
if (verbose)
printf("\n");
// @selftest
// ...
// @end
printf("OK\n");
}
|
gbonnefille/malc
|
mal/src/mal_element_holder.c
|
C
|
mit
| 2,413 |
/**
* profile.state.js
* Created by anonymous on 15/03/16 7:28.
*/
(function() {
'use strict';
angular
.module('client')
.config(profileState);
profileState.$inject = ['$stateProvider', '$urlRouterProvider', 'layoutProvider'];
/* @ngInject */
function profileState($stateProvider, $urlRouterProvider, layoutProvider) {
$stateProvider
.state('profile', {
abstract: true,
url : '/profile',
views : {
'layout@' : {
templateUrl : layoutProvider.layout('minimalist.theme'),
controller : 'ProfileController',
controllerAs: 'profile'
},
'header@profile' : {
templateUrl : layoutProvider.layout('minimalist.header'),
controller : 'HeaderController',
controllerAs: 'header'
},
'sidenav@profile': {
templateUrl : layoutProvider.layout('minimalist.sidenav'),
controller : 'SidenavController',
controllerAs: 'sidenav'
},
'aside@profile' : {
templateUrl : layoutProvider.layout('minimalist.aside'),
controller : 'AsideController',
controllerAs: 'aside'
},
'footer@profile' : {
templateUrl : layoutProvider.layout('minimalist.footer'),
controller : 'FooterController',
controllerAs: 'footer'
},
'main@profile' : {}
}
})
.state('profile.user', {
url : '/{user}',
data : {pageName: 'Profile'},
views : {
'main@profile': {
templateUrl : layoutProvider.view('profile.user'),
controller : 'ProfileUserController',
controllerAs: '$ctrl'
}
},
resolve: {
loginRequired: loginRequired
}
});
function skipIfLoggedIn($q, $auth) {
var deferred = $q.defer();
if ($auth.isAuthenticated()) {
deferred.reject();
} else {
deferred.resolve();
}
return deferred.promise;
}
function loginRequired($q, $state, $auth) {
var deferred = $q.defer();
if ($auth.isAuthenticated()) {
deferred.resolve();
} else {
$state.go('jwtauth.signin');
}
return deferred.promise;
}
}
})();
|
onderdelen/client
|
resources/angular-material/profile.state.js
|
JavaScript
|
mit
| 2,970 |
# Thrive Cube HRTFs
This is a set of binaural measurements taken from a cube loudspeaker configuration. Also provided is a preset configuration file for the [ambiX](https://github.com/kronihias/ambix) binaural decoder plugin.
## Details
* **Sampling rate**: 48kHz
* **Bit depth**: 16
* **Length**: 512 samples
* **Normalization**: -3.76 dBFS peak
* **Microphones**: Audio Technica BMC-10
* **Loudspeakers**: Equator D5
* **Distance**: 1.4m
* **Remarks**: Low frequencies remodeled below 500Hz.
|
topherbuckley/omnitone-PSV
|
node_modules/omnitone/build/resources/README.md
|
Markdown
|
mit
| 495 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.