text
stringlengths 2
1.04M
| meta
dict |
---|---|
. /home/airi/distro/install/bin/torch-activate
if [ -f "./on_training" ]; then
echo "On Training. Exit."
exit 1
fi
touch on_training
./classifier.py --dlibFacePredictor ignore --cuda train --classifier DBN --epoch 400 output/embedding/user
mv -f output/embedding/user/classifier.pkl ../dbn/
./classifier.py --dlibFacePredictor ignore --cuda train --classifier DBN --epoch 400 output/embedding/iguest
mv -f output/embedding/iguest/classifier.pkl ../dbn/classifier_iguest.pkl
rm -f on_training
| {
"content_hash": "ff428fc1fd796fe16ba899c4918ed800",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 109,
"avg_line_length": 31.625,
"alnum_prop": 0.7391304347826086,
"repo_name": "SeonghoBaek/RealtimeCamera",
"id": "8a1ee67199f350c0ca6dd56ad07ebba548808503",
"size": "518",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "face_register/train_dbn.sh",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "846"
},
{
"name": "C",
"bytes": "992555"
},
{
"name": "C++",
"bytes": "15017231"
},
{
"name": "CMake",
"bytes": "158155"
},
{
"name": "CSS",
"bytes": "60811"
},
{
"name": "Cuda",
"bytes": "110052"
},
{
"name": "Dockerfile",
"bytes": "3559"
},
{
"name": "HTML",
"bytes": "48185173"
},
{
"name": "JavaScript",
"bytes": "133435"
},
{
"name": "Lua",
"bytes": "144297"
},
{
"name": "MATLAB",
"bytes": "354"
},
{
"name": "Makefile",
"bytes": "2029791"
},
{
"name": "Objective-C",
"bytes": "558"
},
{
"name": "PHP",
"bytes": "70263"
},
{
"name": "Perl",
"bytes": "554"
},
{
"name": "Python",
"bytes": "482539"
},
{
"name": "Shell",
"bytes": "20361"
},
{
"name": "XSLT",
"bytes": "18442"
}
],
"symlink_target": ""
} |
'use strict';
angular.module('clansApp')
.service('clandata', function($http, $q, $rootScope, $location, CONFIG){
this.Fetch = function() {
var deferred = $q.defer();
$http.get(CONFIG.clanDataUrl).success(function (data) {
console.log('Data successful');
deferred.resolve(data);
}).error(function(data, status, headers, config) {
console.log('Ping not successful');
deferred.reject(data.error);
});
return deferred.promise;
};
})
.factory('FilterData', function() {
var filterData = {
filters:[],
search: ""
};
filterData.filters.push({
title: "Auf Mitgliedersuche",
options: [{
text: "Egal",
filter: function(data) {return true;}
},{
text: "Ja",
filter: function(data) {return data.join;}
},{
text: "Nein",
filter: function(data) {return !data.join;}
}],
selected: 0
});
filterData.filters.push({
title: "Akzeptiert Gastspieler",
options: [{
text: "Egal",
filter: function(data) {return true;}
},{
text: "Ja",
filter: function(data) {return data.guests;}
},{
text: "Nein",
filter: function(data) {return !data.guests;}
}],
selected: 0
});
filterData.filters.push({
title: "Mindestalter",
options: [{
text: "Egal",
filter: function(data) {return true;}
},{
text: "Unter 16 Jahre",
filter: function(data) {return data.joinage < 16;}
},{
text: "Mindestens 16 Jahre",
filter: function(data) {return data.joinage <= 16;}
},{
text: "Mindestens 18 Jahre",
filter: function(data) {return data.joinage <= 18;}
}],
selected: 0
});
filterData.filters.push({
title: "Alter",
options: [{
text: "Egal",
filter: function(data) {return true;}
},{
text: "< 1 Jahr (Frisch)",
filter: function(data) {return data.since == 2014;}
},{
text: "> 1 Jahre",
filter: function(data) {return data.since <= 2013;}
},{
text: "> 2 Jahr",
filter: function(data) {return data.since <= 2012;}
},{
text: "> 4 Jahr",
filter: function(data) {return data.since <= 2010;}
}],
selected: 0
});
filterData.filters.push({
title: "Arma Version",
options: [{
text: "Egal",
filter: function(data) {return true;}
},{
text: "ArmA 2",
filter: function(data) {return data.games.contains("a2");}
},{
text: "ArmA 3",
filter: function(data) {return data.games.contains("a3");}
},{
text: "ArmA 2 & 3",
filter: function(data) {return data.games.contains("a2") && data.games.contains("a3");}
}],
selected: 0
});
filterData.filters.push({
title: "Eigene Server",
options: [{
text: "Egal",
filter: function(data) {return true;}
},{
text: "Ja",
filter: function(data) {return data.ownserver;}
},{
text: "Nein",
filter: function(data) {return !data.ownserver;}
}],
selected: 0
});
filterData.filters.push({
title: "Regulaere Events",
options: [{
text: "Egal",
filter: function(data) {return true;}
},{
text: "Ja",
filter: function(data) {return data.regularevents;}
},{
text: "Nein",
filter: function(data) {return !data.regularevents;}
}],
selected: 0
});
return filterData;
}); | {
"content_hash": "cfdca87d6cf34c46cd18fb1528f0318f",
"timestamp": "",
"source": "github",
"line_count": 141,
"max_line_length": 93,
"avg_line_length": 24.134751773049647,
"alnum_prop": 0.5568615927123126,
"repo_name": "Echo12/armaclans.de",
"id": "0c8b4c815304deae26db93fa0f34995e9e81063d",
"size": "3403",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "scripts/service.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "787"
},
{
"name": "JavaScript",
"bytes": "4571"
}
],
"symlink_target": ""
} |
define(['bluebird', 'common/ui', 'common/html', 'common/events'], (Promise, UI, html, Events) => {
'use strict';
const div = html.tag('div'),
span = html.tag('span'),
button = html.tag('button'),
baseCss = 'kb-filetype-panel',
fileTypeIcon = `${baseCss}__filetype_icon`,
completeIcon = ['fa-check', `${fileTypeIcon}--complete`],
incompleteIcon = ['fa-exclamation', `${fileTypeIcon}--incomplete`],
warningIcon = ['fa-exclamation-circle', `${fileTypeIcon}--warning`];
/**
* This displays a vertical list of "fileTypes" that can be selected on and
* toggled. It's intended to be fairly generic, in that the fileTypes are
* really just labels with keys, and displays whether or not the process
* associated with those fileTypes is "complete" - it's up to the invoking
* class to determine what completion means.
*
* When running this factory, the key object it needs is a set of fileTypes,
* with the following format:
* {
* fileType1: {
* label: 'Some File Type'
* },
* fileType2: {
* label: 'Some Other File Type'
* }
* }
* The keys "fileType1" and "fileType2" are expected to be used later in
* the state, and are returned when one or the other file type is clicked on.
* @param {object} options
* - bus - a message bus
* - fileTypes - an object describing the fileTypes (see above)
* - header - an object with a "icon" and "label" properties for the header.
* the icon should be a font-awesome class set (fa fa-whatever)
* the label should just be a string
* - toggleAction - a function with a single input of 'key' - the file type
* that's been clicked on. Note that this will not be fired if the
* clicked file type is already selected.
*/
function FileTypePanel(options) {
const bus = options.bus,
fileTypes = options.fileTypes,
header = options.header,
toggleFileType = options.toggleAction,
viewOnly = options.viewOnly;
let container = null,
ui = null,
/*
* Basic state structure:
* {
* selected: string (a file type id),
* completed: {
* fileType1: boolean, // if true, then this file type is completed
* fileType2: boolean // if absent or falsy, then the file type is incomplete
* }
* }
*/
state;
/**
* Renders the initial layout. This returns a series of divs with no
* actual container, so it should be placed in one.
*/
function renderLayout() {
const events = Events.make(),
content = [renderHeader()].concat(renderFileTypes(events)).join('');
return {
content,
events,
};
}
/**
* Renders the header - this should just be a non-clickable label.
*/
function renderHeader() {
return div(
{
class: `${baseCss}__header`,
},
[
span({ class: `${baseCss}__header_icon ${header.icon}` }),
span({ class: `${baseCss}__header_label` }, header.label),
]
);
}
/**
* Renders each of the file type elements. These have an icon and a label. Each one
* has a click event bound to it. If the clicked element is not currently selected
* (as judged by the state), then it calls the toggleFileType function with the
* key of the clicked file type.
* @param {Events} events - an events object used to bind the DOM event
*/
function renderFileTypes(events) {
return Object.keys(fileTypes)
.sort()
.map((key) => {
return button(
{
class: `${baseCss}__filetype_button`,
dataElement: key,
id: events.addEvent({
type: 'click',
handler: () => {
if (key !== state.selected) {
toggleFileType(key);
}
},
}),
role: 'button',
'aria-label': `toggle ${fileTypes[key].label}`,
},
[
div({
class: `${fileTypeIcon} fa ${incompleteIcon.join(' ')}`,
dataElement: 'icon',
}),
div(
{
class: `${baseCss}__filetype_label`,
},
fileTypes[key].label
),
]
);
});
}
function addWarningIcon(fileType) {
const warningElem = div({
class: `${fileTypeIcon} fa ${warningIcon.join(' ')}`,
dataElement: 'warning-icon',
});
ui.getElement(fileType).appendChild(ui.createNode(warningElem));
}
/**
* The state of this component handles what file type is currently selected,
* and which fileTypes are completed. The basic structure of the state is
* expected to be:
* {
* selected: file_type_key,
* completed: {
* fileType1: true,
* fileType2: false,
* ...etc
* },
* warnings: Set(fileType1, fileType2, etc);
* }
* @param {object} newState - the state object
*/
function updateState(newState) {
state = newState;
const selected = `${baseCss}__filetype_button--selected`;
state.completed = state.completed || {}; // double-check we have the completed set
state.warnings = state.warnings || new Set();
/**
* Tweaking the visual state -
* 1. deselect everything
* 2. remove all icons
* 3. put in the completion icon for each file type
*/
Object.keys(fileTypes).forEach((key) => {
if (state.selected in fileTypes) {
ui.getElement(key).classList.remove(selected);
}
ui.getElement(`${key}.icon`).classList.remove(...completeIcon, ...incompleteIcon);
if (!viewOnly) {
const icon = state.completed[key] ? completeIcon : incompleteIcon;
ui.getElement(`${key}.icon`).classList.add(...icon);
// if there's a warning, and the fileType doesn't already have a warning icon,
// make one and insert it.
const warningIconElem = ui.getElement(`${key}.warning-icon`);
if (state.warnings.has(key) && !warningIconElem) {
addWarningIcon(key);
}
// if the state has changed so that the warning icon shouldn't be there, remove it.
else if (!state.warnings.has(key) && warningIconElem) {
warningIconElem.remove();
}
}
});
// if the "selected" file type is real, select it
if (state.selected in fileTypes) {
ui.getElement(state.selected).classList.add(selected);
}
}
/**
* Start up the component. This does the work of rendering and initializing the
* component.
* @param {object} args the startup args should have
* - node - a DOM node to build this component under
* - state - the initial state for this component (see updateState for structure)
*/
function start(args) {
return Promise.try(() => {
container = args.node;
ui = UI.make({
node: container,
bus,
});
const layout = renderLayout();
container.innerHTML = layout.content;
layout.events.attachEvents(container);
updateState(args.state);
});
}
/**
* Stop the component. Not used just yet.
*/
function stop() {
return Promise.try(() => {
/* no op */
});
}
return {
start,
stop,
updateState,
};
}
return {
make: FileTypePanel,
};
});
| {
"content_hash": "811d199b313379dc867d919ed4470015",
"timestamp": "",
"source": "github",
"line_count": 232,
"max_line_length": 103,
"avg_line_length": 39.275862068965516,
"alnum_prop": 0.47157594381035994,
"repo_name": "kbase/narrative",
"id": "309eaf4e0b79f9ea15897b29ae25fd0405897a20",
"size": "9112",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "nbextensions/bulkImportCell/tabs/fileTypePanel.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "7500"
},
{
"name": "Dockerfile",
"bytes": "2941"
},
{
"name": "HTML",
"bytes": "60140"
},
{
"name": "JavaScript",
"bytes": "10060716"
},
{
"name": "Makefile",
"bytes": "1984"
},
{
"name": "PHP",
"bytes": "1691"
},
{
"name": "Python",
"bytes": "1514550"
},
{
"name": "Ruby",
"bytes": "3328"
},
{
"name": "SCSS",
"bytes": "149174"
},
{
"name": "Shell",
"bytes": "24425"
}
],
"symlink_target": ""
} |
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "Containers/Array.h"
#include "Containers/BitArray.h"
// Forward declarations.
template<typename ElementType,typename Allocator = FDefaultSparseArrayAllocator >
class TSparseArray;
/** The result of a sparse array allocation. */
struct FSparseArrayAllocationInfo
{
int32 Index;
void* Pointer;
};
/** Allocated elements are overlapped with free element info in the element list. */
template<typename ElementType>
union TSparseArrayElementOrFreeListLink
{
/** If the element is allocated, its value is stored here. */
ElementType ElementData;
struct
{
/** If the element isn't allocated, this is a link to the previous element in the array's free list. */
int32 PrevFreeIndex;
/** If the element isn't allocated, this is a link to the next element in the array's free list. */
int32 NextFreeIndex;
};
};
class FScriptSparseArray;
/**
* A dynamically sized array where element indices aren't necessarily contiguous. Memory is allocated for all
* elements in the array's index range, so it doesn't save memory; but it does allow O(1) element removal that
* doesn't invalidate the indices of subsequent elements. It uses TArray to store the elements, and a TBitArray
* to store whether each element index is allocated (for fast iteration over allocated elements).
*
**/
template<typename ElementType,typename Allocator /*= FDefaultSparseArrayAllocator */>
class TSparseArray
{
friend struct TContainerTraits<TSparseArray>;
friend class FScriptSparseArray;
public:
/** Destructor. */
~TSparseArray()
{
// Destruct the elements in the array.
Empty();
}
/** Marks an index as allocated, and returns information about the allocation. */
FSparseArrayAllocationInfo AllocateIndex(int32 Index)
{
check(Index >= 0);
check(Index < GetMaxIndex());
check(!AllocationFlags[Index]);
// Flag the element as allocated.
AllocationFlags[Index] = true;
// Set the allocation info.
FSparseArrayAllocationInfo Result;
Result.Index = Index;
Result.Pointer = &GetData(Result.Index).ElementData;
return Result;
}
/**
* Allocates space for an element in the array. The element is not initialized, and you must use the corresponding placement new operator
* to construct the element in the allocated memory.
*/
FSparseArrayAllocationInfo AddUninitialized()
{
int32 Index;
if(NumFreeIndices)
{
// Remove and use the first index from the list of free elements.
Index = FirstFreeIndex;
FirstFreeIndex = GetData(FirstFreeIndex).NextFreeIndex;
--NumFreeIndices;
if(NumFreeIndices)
{
GetData(FirstFreeIndex).PrevFreeIndex = -1;
}
}
else
{
// Add a new element.
Index = Data.AddUninitialized(1);
AllocationFlags.Add(false);
}
return AllocateIndex(Index);
}
/** Adds an element to the array. */
int32 Add(typename TTypeTraits<ElementType>::ConstInitType Element)
{
FSparseArrayAllocationInfo Allocation = AddUninitialized();
new(Allocation) ElementType(Element);
return Allocation.Index;
}
/**
* Allocates space for an element in the array at a given index. The element is not initialized, and you must use the corresponding placement new operator
* to construct the element in the allocated memory.
*/
FSparseArrayAllocationInfo InsertUninitialized(int32 Index)
{
// Enlarge the array to include the given index.
if(Index >= Data.Num())
{
Data.AddUninitialized(Index + 1 - Data.Num());
while(AllocationFlags.Num() < Data.Num())
{
const int32 FreeIndex = AllocationFlags.Num();
GetData(FreeIndex).PrevFreeIndex = -1;
GetData(FreeIndex).NextFreeIndex = FirstFreeIndex;
if(NumFreeIndices)
{
GetData(FirstFreeIndex).PrevFreeIndex = FreeIndex;
}
FirstFreeIndex = FreeIndex;
verify(AllocationFlags.Add(false) == FreeIndex);
++NumFreeIndices;
};
}
// Verify that the specified index is free.
check(!AllocationFlags[Index]);
// Remove the index from the list of free elements.
--NumFreeIndices;
const int32 PrevFreeIndex = GetData(Index).PrevFreeIndex;
const int32 NextFreeIndex = GetData(Index).NextFreeIndex;
if(PrevFreeIndex != -1)
{
GetData(PrevFreeIndex).NextFreeIndex = NextFreeIndex;
}
else
{
FirstFreeIndex = NextFreeIndex;
}
if(NextFreeIndex != -1)
{
GetData(NextFreeIndex).PrevFreeIndex = PrevFreeIndex;
}
return AllocateIndex(Index);
}
/**
* Inserts an element to the array.
*/
void Insert(int32 Index,typename TTypeTraits<ElementType>::ConstInitType Element)
{
new(InsertUninitialized(Index)) ElementType(Element);
}
/** Removes Count elements from the array, starting from Index. */
void RemoveAt(int32 Index,int32 Count = 1)
{
if (TTypeTraits<ElementType>::NeedsDestructor)
{
for (int32 It = Index, ItCount = Count; ItCount; ++It, --ItCount)
{
((ElementType&)GetData(It).ElementData).~ElementType();
}
}
RemoveAtUninitialized(Index, Count);
}
/** Removes Count elements from the array, starting from Index, without destructing them. */
void RemoveAtUninitialized(int32 Index,int32 Count = 1)
{
for (; Count; --Count)
{
check(AllocationFlags[Index]);
// Mark the element as free and add it to the free element list.
if(NumFreeIndices)
{
GetData(FirstFreeIndex).PrevFreeIndex = Index;
}
auto& IndexData = GetData(Index);
IndexData.PrevFreeIndex = -1;
IndexData.NextFreeIndex = NumFreeIndices > 0 ? FirstFreeIndex : INDEX_NONE;
FirstFreeIndex = Index;
++NumFreeIndices;
AllocationFlags[Index] = false;
++Index;
}
}
/**
* Removes all elements from the array, potentially leaving space allocated for an expected number of elements about to be added.
* @param ExpectedNumElements - The expected number of elements about to be added.
*/
void Empty(int32 ExpectedNumElements = 0)
{
// Destruct the allocated elements.
if( TTypeTraits<ElementType>::NeedsDestructor )
{
for(TIterator It(*this);It;++It)
{
ElementType& Element = *It;
Element.~ElementType();
}
}
// Free the allocated elements.
Data.Empty(ExpectedNumElements);
FirstFreeIndex = -1;
NumFreeIndices = 0;
AllocationFlags.Empty(ExpectedNumElements);
}
/** Empties the array, but keep its allocated memory as slack. */
void Reset()
{
// Destruct the allocated elements.
if( TTypeTraits<ElementType>::NeedsDestructor )
{
for(TIterator It(*this);It;++It)
{
ElementType& Element = *It;
Element.~ElementType();
}
}
// Free the allocated elements.
Data.Reset();
FirstFreeIndex = -1;
NumFreeIndices = 0;
AllocationFlags.Reset();
}
/**
* Preallocates enough memory to contain the specified number of elements.
*
* @param ExpectedNumElements the total number of elements that the array will have
*/
void Reserve(int32 ExpectedNumElements)
{
if ( ExpectedNumElements > Data.Num() )
{
const int32 ElementsToAdd = ExpectedNumElements - Data.Num();
// allocate memory in the array itself
int32 ElementIndex = Data.AddUninitialized(ElementsToAdd);
// now mark the new elements as free
for ( int32 FreeIndex = ElementIndex; FreeIndex < ExpectedNumElements; FreeIndex++ )
{
if(NumFreeIndices)
{
GetData(FirstFreeIndex).PrevFreeIndex = FreeIndex;
}
GetData(FreeIndex).PrevFreeIndex = -1;
GetData(FreeIndex).NextFreeIndex = NumFreeIndices > 0 ? FirstFreeIndex : INDEX_NONE;
FirstFreeIndex = FreeIndex;
++NumFreeIndices;
}
//@fixme - this will have to do until TBitArray has a Reserve method....
for ( int32 i = 0; i < ElementsToAdd; i++ )
{
AllocationFlags.Add(false);
}
}
}
/** Shrinks the array's storage to avoid slack. */
void Shrink()
{
// Determine the highest allocated index in the data array.
int32 MaxAllocatedIndex = INDEX_NONE;
for(TConstSetBitIterator<typename Allocator::BitArrayAllocator> AllocatedIndexIt(AllocationFlags);AllocatedIndexIt;++AllocatedIndexIt)
{
MaxAllocatedIndex = FMath::Max(MaxAllocatedIndex,AllocatedIndexIt.GetIndex());
}
const int32 FirstIndexToRemove = MaxAllocatedIndex + 1;
if(FirstIndexToRemove < Data.Num())
{
if(NumFreeIndices > 0)
{
// Look for elements in the free list that are in the memory to be freed.
int32 FreeIndex = FirstFreeIndex;
while(FreeIndex != INDEX_NONE)
{
if(FreeIndex >= FirstIndexToRemove)
{
const int32 PrevFreeIndex = GetData(FreeIndex).PrevFreeIndex;
const int32 NextFreeIndex = GetData(FreeIndex).NextFreeIndex;
if(NextFreeIndex != -1)
{
GetData(NextFreeIndex).PrevFreeIndex = PrevFreeIndex;
}
if(PrevFreeIndex != -1)
{
GetData(PrevFreeIndex).NextFreeIndex = NextFreeIndex;
}
else
{
FirstFreeIndex = NextFreeIndex;
}
--NumFreeIndices;
FreeIndex = NextFreeIndex;
}
else
{
FreeIndex = GetData(FreeIndex).NextFreeIndex;
}
}
}
// Truncate unallocated elements at the end of the data array.
Data.RemoveAt(FirstIndexToRemove,Data.Num() - FirstIndexToRemove);
AllocationFlags.RemoveAt(FirstIndexToRemove,AllocationFlags.Num() - FirstIndexToRemove);
}
// Shrink the data array.
Data.Shrink();
}
/** Compacts the allocated elements into a contiguous index range. */
void Compact()
{
// Copy the existing elements to a new array.
TSparseArray<ElementType,Allocator> CompactedArray;
CompactedArray.Empty(Num());
for(TConstIterator It(*this);It;++It)
{
new(CompactedArray.AddUninitialized()) ElementType(*It);
}
// Replace this array with the compacted array.
Exchange(*this,CompactedArray);
}
/** Sorts the elements using the provided comparison class. */
template<typename PREDICATE_CLASS>
void Sort( const PREDICATE_CLASS& Predicate )
{
if(Num() > 0)
{
// Compact the elements array so all the elements are contiguous.
Compact();
// Sort the elements according to the provided comparison class.
::Sort( &GetData(0), Num(), FElementCompareClass< PREDICATE_CLASS >( Predicate ) );
}
}
/** Sorts the elements assuming < operator is defined for ElementType. */
void Sort()
{
Sort( TLess< ElementType >() );
}
/**
* Helper function to return the amount of memory allocated by this container
* @return number of bytes allocated by this container
*/
uint32 GetAllocatedSize( void ) const
{
return (Data.Num() + Data.GetSlack()) * sizeof(FElementOrFreeListLink) +
AllocationFlags.GetAllocatedSize();
}
/** Tracks the container's memory use through an archive. */
void CountBytes(FArchive& Ar)
{
Data.CountBytes(Ar);
AllocationFlags.CountBytes(Ar);
}
/** Serializer. */
friend FArchive& operator<<(FArchive& Ar,TSparseArray& Array)
{
Array.CountBytes(Ar);
if( Ar.IsLoading() )
{
// Load array.
int32 NewNumElements = 0;
Ar << NewNumElements;
Array.Empty( NewNumElements );
for(int32 ElementIndex = 0;ElementIndex < NewNumElements;ElementIndex++)
{
Ar << *::new(Array.AddUninitialized())ElementType;
}
}
else
{
// Save array.
int32 NewNumElements = Array.Num();
Ar << NewNumElements;
for(TIterator It(Array);It;++It)
{
Ar << *It;
}
}
return Ar;
}
/**
* Equality comparison operator.
* Checks that both arrays have the same elements and element indices; that means that unallocated elements are signifigant!
*/
friend bool operator==(const TSparseArray& A,const TSparseArray& B)
{
if(A.GetMaxIndex() != B.GetMaxIndex())
{
return false;
}
for(int32 ElementIndex = 0;ElementIndex < A.GetMaxIndex();ElementIndex++)
{
const bool bIsAllocatedA = A.IsAllocated(ElementIndex);
const bool bIsAllocatedB = B.IsAllocated(ElementIndex);
if(bIsAllocatedA != bIsAllocatedB)
{
return false;
}
else if(bIsAllocatedA)
{
if(A[ElementIndex] != B[ElementIndex])
{
return false;
}
}
}
return true;
}
/**
* Inequality comparison operator.
* Checks that both arrays have the same elements and element indices; that means that unallocated elements are signifigant!
*/
friend bool operator!=(const TSparseArray& A,const TSparseArray& B)
{
return !(A == B);
}
/** Default constructor. */
TSparseArray()
: FirstFreeIndex(-1)
, NumFreeIndices(0)
{}
/** Move constructor. */
TSparseArray(TSparseArray&& InCopy)
{
MoveOrCopy(*this, InCopy);
}
/** Copy constructor. */
TSparseArray(const TSparseArray& InCopy)
: FirstFreeIndex(-1)
, NumFreeIndices(0)
{
*this = InCopy;
}
/** Move assignment operator. */
TSparseArray& operator=(TSparseArray&& InCopy)
{
if(this != &InCopy)
{
MoveOrCopy(*this, InCopy);
}
return *this;
}
/** Copy assignment operator. */
TSparseArray& operator=(const TSparseArray& InCopy)
{
if(this != &InCopy)
{
// Reallocate the array.
Empty(InCopy.GetMaxIndex());
Data.AddUninitialized(InCopy.GetMaxIndex());
// Copy the other array's element allocation state.
FirstFreeIndex = InCopy.FirstFreeIndex;
NumFreeIndices = InCopy.NumFreeIndices;
AllocationFlags = InCopy.AllocationFlags;
// Determine whether we need per element construction or bulk copy is fine
if (TTypeTraits<ElementType>::NeedsCopyConstructor)
{
FElementOrFreeListLink* SrcData = (FElementOrFreeListLink*)Data.GetData();
const FElementOrFreeListLink* DestData = (FElementOrFreeListLink*)InCopy.Data.GetData();
// Use the inplace new to copy the element to an array element
for(int32 Index = 0;Index < InCopy.GetMaxIndex();Index++)
{
FElementOrFreeListLink& DestElement = SrcData [Index];
const FElementOrFreeListLink& SourceElement = DestData[Index];
if(InCopy.IsAllocated(Index))
{
::new((uint8*)&DestElement.ElementData) ElementType(*(ElementType*)&SourceElement.ElementData);
}
DestElement.PrevFreeIndex = SourceElement.PrevFreeIndex;
DestElement.NextFreeIndex = SourceElement.NextFreeIndex;
}
}
else
{
// Use the much faster path for types that allow it
FMemory::Memcpy(Data.GetData(),InCopy.Data.GetData(),sizeof(FElementOrFreeListLink) * InCopy.GetMaxIndex());
}
}
return *this;
}
private:
template <typename SparseArrayType>
FORCEINLINE static typename TEnableIf<TContainerTraits<SparseArrayType>::MoveWillEmptyContainer>::Type MoveOrCopy(SparseArrayType& ToArray, SparseArrayType& FromArray)
{
ToArray.Data = (DataType&&)FromArray.Data;
ToArray.AllocationFlags = (AllocationBitArrayType&&)FromArray.AllocationFlags;
ToArray.FirstFreeIndex = FromArray.FirstFreeIndex;
ToArray.NumFreeIndices = FromArray.NumFreeIndices;
FromArray.FirstFreeIndex = -1;
FromArray.NumFreeIndices = 0;
}
template <typename SparseArrayType>
FORCEINLINE static typename TEnableIf<!TContainerTraits<SparseArrayType>::MoveWillEmptyContainer>::Type MoveOrCopy(SparseArrayType& ToArray, SparseArrayType& FromArray)
{
ToArray = FromArray;
}
public:
// Accessors.
ElementType& operator[](int32 Index)
{
checkSlow(Index >= 0 && Index < Data.Num() && Index < AllocationFlags.Num());
//checkSlow(AllocationFlags[Index]); // Disabled to improve loading times -BZ
return *(ElementType*)&GetData(Index).ElementData;
}
const ElementType& operator[](int32 Index) const
{
checkSlow(Index >= 0 && Index < Data.Num() && Index < AllocationFlags.Num());
//checkSlow(AllocationFlags[Index]); // Disabled to improve loading times -BZ
return *(ElementType*)&GetData(Index).ElementData;
}
bool IsAllocated(int32 Index) const { return AllocationFlags[Index]; }
int32 GetMaxIndex() const { return Data.Num(); }
int32 Num() const { return Data.Num() - NumFreeIndices; }
/**
* Checks that the specified address is not part of an element within the container. Used for implementations
* to check that reference arguments aren't going to be invalidated by possible reallocation.
*
* @param Addr The address to check.
*/
FORCEINLINE void CheckAddress(const ElementType* Addr) const
{
Data.CheckAddress(Addr);
}
private:
/** The base class of sparse array iterators. */
template<bool bConst>
class TBaseIterator
{
public:
typedef TConstSetBitIterator<typename Allocator::BitArrayAllocator> BitArrayItType;
private:
typedef typename TChooseClass<bConst,const TSparseArray,TSparseArray>::Result ArrayType;
typedef typename TChooseClass<bConst,const ElementType,ElementType>::Result ItElementType;
public:
explicit TBaseIterator(ArrayType& InArray, const BitArrayItType& InBitArrayIt)
: Array (InArray)
, BitArrayIt(InBitArrayIt)
{
}
FORCEINLINE TBaseIterator& operator++()
{
// Iterate to the next set allocation flag.
++BitArrayIt;
return *this;
}
FORCEINLINE int32 GetIndex() const { return BitArrayIt.GetIndex(); }
FORCEINLINE friend bool operator==(const TBaseIterator& Lhs, const TBaseIterator& Rhs) { return Lhs.BitArrayIt == Rhs.BitArrayIt && &Lhs.Array == &Rhs.Array; }
FORCEINLINE friend bool operator!=(const TBaseIterator& Lhs, const TBaseIterator& Rhs) { return Lhs.BitArrayIt != Rhs.BitArrayIt || &Lhs.Array != &Rhs.Array; }
/** conversion to "bool" returning true if the iterator is valid. */
FORCEINLINE_EXPLICIT_OPERATOR_BOOL() const
{
return !!BitArrayIt;
}
/** inverse of the "bool" operator */
FORCEINLINE bool operator !() const
{
return !(bool)*this;
}
FORCEINLINE ItElementType& operator*() const { return Array[GetIndex()]; }
FORCEINLINE ItElementType* operator->() const { return &Array[GetIndex()]; }
FORCEINLINE const FRelativeBitReference& GetRelativeBitReference() const { return BitArrayIt; }
protected:
ArrayType& Array;
BitArrayItType BitArrayIt;
};
public:
/** Iterates over all allocated elements in a sparse array. */
class TIterator : public TBaseIterator<false>
{
public:
TIterator(TSparseArray& InArray)
: TBaseIterator<false>(InArray, TConstSetBitIterator<typename Allocator::BitArrayAllocator>(InArray.AllocationFlags))
{
}
TIterator(TSparseArray& InArray, const typename TBaseIterator<false>::BitArrayItType& InBitArrayIt)
: TBaseIterator<false>(InArray, InBitArrayIt)
{
}
/** Safely removes the current element from the array. */
void RemoveCurrent()
{
this->Array.RemoveAt(this->GetIndex());
}
};
/** Iterates over all allocated elements in a const sparse array. */
class TConstIterator : public TBaseIterator<true>
{
public:
TConstIterator(const TSparseArray& InArray)
: TBaseIterator<true>(InArray, TConstSetBitIterator<typename Allocator::BitArrayAllocator>(InArray.AllocationFlags))
{
}
TConstIterator(const TSparseArray& InArray, const typename TBaseIterator<true>::BitArrayItType& InBitArrayIt)
: TBaseIterator<true>(InArray, InBitArrayIt)
{
}
};
/** Creates an iterator for the contents of this array */
TIterator CreateIterator()
{
return TIterator(*this);
}
/** Creates a const iterator for the contents of this array */
TConstIterator CreateConstIterator() const
{
return TConstIterator(*this);
}
private:
/**
* DO NOT USE DIRECTLY
* STL-like iterators to enable range-based for loop support.
*/
FORCEINLINE friend TIterator begin( TSparseArray& Array) { return TIterator (Array, TConstSetBitIterator<typename Allocator::BitArrayAllocator>(Array.AllocationFlags)); }
FORCEINLINE friend TConstIterator begin(const TSparseArray& Array) { return TConstIterator(Array, TConstSetBitIterator<typename Allocator::BitArrayAllocator>(Array.AllocationFlags)); }
FORCEINLINE friend TIterator end ( TSparseArray& Array) { return TIterator (Array, TConstSetBitIterator<typename Allocator::BitArrayAllocator>(Array.AllocationFlags, Array.AllocationFlags.Num())); }
FORCEINLINE friend TConstIterator end (const TSparseArray& Array) { return TConstIterator(Array, TConstSetBitIterator<typename Allocator::BitArrayAllocator>(Array.AllocationFlags, Array.AllocationFlags.Num())); }
public:
/** An iterator which only iterates over the elements of the array which correspond to set bits in a separate bit array. */
template<typename SubsetAllocator = FDefaultBitArrayAllocator>
class TConstSubsetIterator
{
public:
TConstSubsetIterator( const TSparseArray& InArray, const TBitArray<SubsetAllocator>& InBitArray ):
Array(InArray),
BitArrayIt(InArray.AllocationFlags,InBitArray)
{}
FORCEINLINE TConstSubsetIterator& operator++()
{
// Iterate to the next element which is both allocated and has its bit set in the other bit array.
++BitArrayIt;
return *this;
}
FORCEINLINE int32 GetIndex() const { return BitArrayIt.GetIndex(); }
/** conversion to "bool" returning true if the iterator is valid. */
FORCEINLINE_EXPLICIT_OPERATOR_BOOL() const
{
return !!BitArrayIt;
}
/** inverse of the "bool" operator */
FORCEINLINE bool operator !() const
{
return !(bool)*this;
}
FORCEINLINE const ElementType& operator*() const { return Array(GetIndex()); }
FORCEINLINE const ElementType* operator->() const { return &Array(GetIndex()); }
FORCEINLINE const FRelativeBitReference& GetRelativeBitReference() const { return BitArrayIt; }
private:
const TSparseArray& Array;
TConstDualSetBitIterator<typename Allocator::BitArrayAllocator,SubsetAllocator> BitArrayIt;
};
/** Concatenation operators */
TSparseArray& operator+=( const TSparseArray& OtherArray )
{
this->Reserve(this->Num() + OtherArray.Num());
for ( typename TSparseArray::TConstIterator It(OtherArray); It; ++It )
{
this->Add(*It);
}
return *this;
}
TSparseArray& operator+=( const TArray<ElementType>& OtherArray )
{
this->Reserve(this->Num() + OtherArray.Num());
for ( int32 Idx = 0; Idx < OtherArray.Num(); Idx++ )
{
this->Add(OtherArray[Idx]);
}
return *this;
}
private:
/**
* The element type stored is only indirectly related to the element type requested, to avoid instantiating TArray redundantly for
* compatible types.
*/
typedef TSparseArrayElementOrFreeListLink<
TAlignedBytes<sizeof(ElementType),ALIGNOF(ElementType)>
> FElementOrFreeListLink;
/** Extracts the element value from the array's element structure and passes it to the user provided comparison class. */
template <typename PREDICATE_CLASS>
class FElementCompareClass
{
const PREDICATE_CLASS& Predicate;
public:
FElementCompareClass( const PREDICATE_CLASS& InPredicate )
: Predicate( InPredicate )
{}
bool operator()( const FElementOrFreeListLink& A,const FElementOrFreeListLink& B ) const
{
return Predicate(*(ElementType*)&A.ElementData,*(ElementType*)&B.ElementData);
}
};
/** Accessor for the element or free list data. */
FElementOrFreeListLink& GetData(int32 Index)
{
return ((FElementOrFreeListLink*)Data.GetData())[Index];
}
/** Accessor for the element or free list data. */
const FElementOrFreeListLink& GetData(int32 Index) const
{
return ((FElementOrFreeListLink*)Data.GetData())[Index];
}
typedef TArray<FElementOrFreeListLink,typename Allocator::ElementAllocator> DataType;
DataType Data;
typedef TBitArray<typename Allocator::BitArrayAllocator> AllocationBitArrayType;
AllocationBitArrayType AllocationFlags;
/** The index of an unallocated element in the array that currently contains the head of the linked list of free elements. */
int32 FirstFreeIndex;
/** The number of elements in the free list. */
int32 NumFreeIndices;
};
template<typename ElementType, typename Allocator>
struct TContainerTraits<TSparseArray<ElementType, Allocator> > : public TContainerTraitsBase<TSparseArray<ElementType, Allocator> >
{
enum { MoveWillEmptyContainer =
TContainerTraits<typename TSparseArray<ElementType, Allocator>::DataType>::MoveWillEmptyContainer &&
TContainerTraits<typename TSparseArray<ElementType, Allocator>::AllocationBitArrayType>::MoveWillEmptyContainer };
};
struct FScriptSparseArrayLayout
{
int32 ElementOffset;
int32 Alignment;
int32 Size;
};
// Untyped sparse array type for accessing TSparseArray data, like FScriptArray for TArray.
// Must have the same memory representation as a TSet.
class FScriptSparseArray
{
public:
static FScriptSparseArrayLayout GetScriptLayout(int32 ElementSize, int32 ElementAlignment)
{
FScriptSparseArrayLayout Result;
Result.ElementOffset = 0;
Result.Alignment = FMath::Max(ElementAlignment, (int32)ALIGNOF(FFreeListLink));
Result.Size = FMath::Max(ElementSize, (int32)sizeof (FFreeListLink));
return Result;
}
FScriptSparseArray()
: FirstFreeIndex(-1)
, NumFreeIndices(0)
{
}
bool IsValidIndex(int32 Index) const
{
return AllocationFlags.IsValidIndex(Index) && AllocationFlags[Index];
}
int32 Num() const
{
return Data.Num() - NumFreeIndices;
}
int32 GetMaxIndex() const
{
return Data.Num();
}
void* GetData(int32 Index, const FScriptSparseArrayLayout& Layout)
{
return (uint8*)Data.GetData() + Layout.Size * Index;
}
const void* GetData(int32 Index, const FScriptSparseArrayLayout& Layout) const
{
return (const uint8*)Data.GetData() + Layout.Size * Index;
}
void Empty(int32 Slack, const FScriptSparseArrayLayout& Layout)
{
// Free the allocated elements.
Data.Empty(Slack, Layout.Size);
FirstFreeIndex = -1;
NumFreeIndices = 0;
AllocationFlags.Empty(Slack);
}
/**
* Adds an uninitialized object to the array.
*
* @return The index of the added element.
*/
int32 AddUninitialized(const FScriptSparseArrayLayout& Layout)
{
int32 Index;
if (NumFreeIndices)
{
// Remove and use the first index from the list of free elements.
Index = FirstFreeIndex;
FirstFreeIndex = GetFreeListLink(FirstFreeIndex, Layout)->NextFreeIndex;
--NumFreeIndices;
if(NumFreeIndices)
{
GetFreeListLink(FirstFreeIndex, Layout)->PrevFreeIndex = -1;
}
}
else
{
// Add a new element.
Index = Data.Add(1, Layout.Size);
AllocationFlags.Add(false);
}
AllocationFlags[Index] = true;
return Index;
}
/** Removes Count elements from the array, starting from Index, without destructing them. */
void RemoveAtUninitialized(const FScriptSparseArrayLayout& Layout, int32 Index, int32 Count = 1)
{
for (; Count; --Count)
{
check(AllocationFlags[Index]);
// Mark the element as free and add it to the free element list.
if(NumFreeIndices)
{
GetFreeListLink(FirstFreeIndex, Layout)->PrevFreeIndex = Index;
}
auto* IndexData = GetFreeListLink(Index, Layout);
IndexData->PrevFreeIndex = -1;
IndexData->NextFreeIndex = NumFreeIndices > 0 ? FirstFreeIndex : INDEX_NONE;
FirstFreeIndex = Index;
++NumFreeIndices;
AllocationFlags[Index] = false;
++Index;
}
}
private:
FScriptArray Data;
FScriptBitArray AllocationFlags;
int32 FirstFreeIndex;
int32 NumFreeIndices;
// This function isn't intended to be called, just to be compiled to validate the correctness of the type.
static void CheckConstraints()
{
typedef FScriptSparseArray ScriptType;
typedef TSparseArray<int32> RealType;
// Check that the class footprint is the same
static_assert(sizeof (ScriptType) == sizeof (RealType), "FScriptSparseArray's size doesn't match TSparseArray");
static_assert(ALIGNOF(ScriptType) == ALIGNOF(RealType), "FScriptSparseArray's alignment doesn't match TSparseArray");
// Check member sizes
static_assert(sizeof(DeclVal<ScriptType>().Data) == sizeof(DeclVal<RealType>().Data), "FScriptSparseArray's Data member size does not match TSparseArray's");
static_assert(sizeof(DeclVal<ScriptType>().AllocationFlags) == sizeof(DeclVal<RealType>().AllocationFlags), "FScriptSparseArray's AllocationFlags member size does not match TSparseArray's");
static_assert(sizeof(DeclVal<ScriptType>().FirstFreeIndex) == sizeof(DeclVal<RealType>().FirstFreeIndex), "FScriptSparseArray's FirstFreeIndex member size does not match TSparseArray's");
static_assert(sizeof(DeclVal<ScriptType>().NumFreeIndices) == sizeof(DeclVal<RealType>().NumFreeIndices), "FScriptSparseArray's NumFreeIndices member size does not match TSparseArray's");
// Check member offsets
static_assert(STRUCT_OFFSET(ScriptType, Data) == STRUCT_OFFSET(RealType, Data), "FScriptSparseArray's Data member offset does not match TSparseArray's");
static_assert(STRUCT_OFFSET(ScriptType, AllocationFlags) == STRUCT_OFFSET(RealType, AllocationFlags), "FScriptSparseArray's AllocationFlags member offset does not match TSparseArray's");
static_assert(STRUCT_OFFSET(ScriptType, FirstFreeIndex) == STRUCT_OFFSET(RealType, FirstFreeIndex), "FScriptSparseArray's FirstFreeIndex member offset does not match TSparseArray's");
static_assert(STRUCT_OFFSET(ScriptType, NumFreeIndices) == STRUCT_OFFSET(RealType, NumFreeIndices), "FScriptSparseArray's NumFreeIndices member offset does not match TSparseArray's");
// Check free index offsets
static_assert(STRUCT_OFFSET(ScriptType::FFreeListLink, PrevFreeIndex) == STRUCT_OFFSET(RealType::FElementOrFreeListLink, PrevFreeIndex), "FScriptSparseArray's FFreeListLink's PrevFreeIndex member offset does not match TSparseArray's");
static_assert(STRUCT_OFFSET(ScriptType::FFreeListLink, NextFreeIndex) == STRUCT_OFFSET(RealType::FElementOrFreeListLink, NextFreeIndex), "FScriptSparseArray's FFreeListLink's NextFreeIndex member offset does not match TSparseArray's");
}
struct FFreeListLink
{
/** If the element isn't allocated, this is a link to the previous element in the array's free list. */
int32 PrevFreeIndex;
/** If the element isn't allocated, this is a link to the next element in the array's free list. */
int32 NextFreeIndex;
};
/** Accessor for the element or free list data. */
FORCEINLINE FFreeListLink* GetFreeListLink(int32 Index, const FScriptSparseArrayLayout& Layout)
{
return (FFreeListLink*)GetData(Index, Layout);
}
public:
// These should really be private, because they shouldn't be called, but there's a bunch of code
// that needs to be fixed first.
FScriptSparseArray(const FScriptSparseArray&) { check(false); }
void operator=(const FScriptSparseArray&) { check(false); }
};
template <>
struct TIsZeroConstructType<FScriptSparseArray>
{
enum { Value = true };
};
/**
* A placement new operator which constructs an element in a sparse array allocation.
*/
inline void* operator new(size_t Size,const FSparseArrayAllocationInfo& Allocation)
{
ASSUME(Allocation.Pointer);
return Allocation.Pointer;
}
| {
"content_hash": "697dca32bd8d08107d5a5110d552b603",
"timestamp": "",
"source": "github",
"line_count": 997,
"max_line_length": 237,
"avg_line_length": 30.613841524573722,
"alnum_prop": 0.7233470938994824,
"repo_name": "PopCap/GameIdea",
"id": "165f3bd87ade80ea99902f129de436d1a7dc5ffd",
"size": "30522",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Engine/Source/Runtime/Core/Public/Containers/SparseArray.h",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "ASP",
"bytes": "238055"
},
{
"name": "Assembly",
"bytes": "184134"
},
{
"name": "Batchfile",
"bytes": "116983"
},
{
"name": "C",
"bytes": "84264210"
},
{
"name": "C#",
"bytes": "9612596"
},
{
"name": "C++",
"bytes": "242290999"
},
{
"name": "CMake",
"bytes": "548754"
},
{
"name": "CSS",
"bytes": "134910"
},
{
"name": "GLSL",
"bytes": "96780"
},
{
"name": "HLSL",
"bytes": "124014"
},
{
"name": "HTML",
"bytes": "4097051"
},
{
"name": "Java",
"bytes": "757767"
},
{
"name": "JavaScript",
"bytes": "2742822"
},
{
"name": "Makefile",
"bytes": "1976144"
},
{
"name": "Objective-C",
"bytes": "75778979"
},
{
"name": "Objective-C++",
"bytes": "312592"
},
{
"name": "PAWN",
"bytes": "2029"
},
{
"name": "PHP",
"bytes": "10309"
},
{
"name": "PLSQL",
"bytes": "130426"
},
{
"name": "Pascal",
"bytes": "23662"
},
{
"name": "Perl",
"bytes": "218656"
},
{
"name": "Python",
"bytes": "21593012"
},
{
"name": "SAS",
"bytes": "1847"
},
{
"name": "Shell",
"bytes": "2889614"
},
{
"name": "Tcl",
"bytes": "1452"
}
],
"symlink_target": ""
} |
//package io.iansoft.blockchain.service.mapper;
//
//import io.iansoft.blockchain.domain.*;
//import io.iansoft.blockchain.service.dto.ResourceDTO;
//
//import org.mapstruct.*;
//
///**
// * Mapper for the entity Resource and its DTO ResourceDTO.
// */
//@Mapper(componentModel = "spring", uses = {CoinMapper.class, })
//public interface ResourceMapper extends EntityMapper <ResourceDTO, Resource> {
//
// @Mapping(source = "coin.id", target = "coinId")
// ResourceDTO toDto(Resource resource);
//
// @Mapping(source = "coinId", target = "coin")
// Resource toEntity(ResourceDTO resourceDTO);
// default Resource fromId(Long id) {
// if (id == null) {
// return null;
// }
// Resource resource = new Resource();
// resource.setId(id);
// return resource;
// }
//}
| {
"content_hash": "b648c996e6c3a72ab016d8b956154e92",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 80,
"avg_line_length": 30.666666666666668,
"alnum_prop": 0.6316425120772947,
"repo_name": "iansoftdev/all-blockchain",
"id": "af65711b3fd5a01ddeda78fe8a09b403eae13f16",
"size": "828",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/io/iansoft/blockchain/service/mapper/ResourceMapper.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "23670"
},
{
"name": "Dockerfile",
"bytes": "328"
},
{
"name": "Gherkin",
"bytes": "179"
},
{
"name": "HTML",
"bytes": "296792"
},
{
"name": "Java",
"bytes": "814900"
},
{
"name": "JavaScript",
"bytes": "999740"
},
{
"name": "Scala",
"bytes": "33739"
},
{
"name": "Shell",
"bytes": "280"
},
{
"name": "TSQL",
"bytes": "104378"
},
{
"name": "TypeScript",
"bytes": "759210"
}
],
"symlink_target": ""
} |
if(!dojo._hasResource["dojox.drawing.manager.Canvas"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["dojox.drawing.manager.Canvas"] = true;
dojo.provide("dojox.drawing.manager.Canvas");
(function(){
dojox.drawing.manager.Canvas = dojox.drawing.util.oo.declare(
// summary:
// Creates a dojox.gfx.surface to be used for Drawing. Note that
// The 'surface' that Drawing uses is actually a dojox.gfx.group.
// This allows for more versatility.
//
// Called internally from a dojox.Drawing.
//
// Note: Surface creation is asynchrous. Connect to
// onSurfaceReady in Drawing.
//
function(/*Object*/options){
dojo.mixin(this, options);
var dim = dojo.contentBox(this.srcRefNode);
this.height = this.parentHeight = dim.h;
this.width = this.parentWidth = dim.w;
this.domNode = dojo.create("div", {id:"canvasNode"}, this.srcRefNode);
dojo.style(this.domNode, {
width:this.width,
height:"auto"
});
dojo.setSelectable(this.domNode, false);
this.id = this.id || this.util.uid("surface");
console.info("create canvas");
this.gfxSurface = dojox.gfx.createSurface(this.domNode, this.width, this.height);
this.gfxSurface.whenLoaded(this, function(){
setTimeout(dojo.hitch(this, function(){
this.surfaceReady = true;
if(dojo.isIE){
//this.gfxSurface.rawNode.parentNode.id = this.id;
}else if(dojox.gfx.renderer == "silverlight"){
this.id = this.domNode.firstChild.id
}else{
//this.gfxSurface.rawNode.id = this.id;
}
this.underlay = this.gfxSurface.createGroup();
this.surface = this.gfxSurface.createGroup();
this.overlay = this.gfxSurface.createGroup();
this.surface.setTransform({dx:0, dy:0,xx:1,yy:1});
this.gfxSurface.getDimensions = dojo.hitch(this.gfxSurface, "getDimensions");
if(options.callback){
options.callback(this.domNode);
}
}),500);
});
this._mouseHandle = this.mouse.register(this);
},
{
// zoom: [readonly] Number
// The amount the canvas is zoomed
zoom:1,
useScrollbars: true,
baseClass:"drawingCanvas",
resize: function(width, height){
// summary:
// Method used to change size of canvas. Potentially
// called from a container like ContentPane. May be
// called directly.
//
this.parentWidth = width;
this.parentHeight = height;
this.setDimensions(width, height);
},
setDimensions: function(width, height, scrollx, scrolly){
// summary:
// Internal. Changes canvas size and sets scroll position.
// Do not call this, use resize().
//
// changing the size of the surface and setting scroll
// if items are off screen
var sw = this.getScrollWidth(); //+ 10;
this.width = Math.max(width, this.parentWidth);
this.height = Math.max(height, this.parentHeight);
if(this.height>this.parentHeight){
this.width -= sw;
}
if(this.width>this.parentWidth){
this.height -= sw;
}
this.mouse.resize(this.width,this.height);
this.gfxSurface.setDimensions(this.width, this.height);
this.domNode.parentNode.scrollTop = scrolly || 0;
this.domNode.parentNode.scrollLeft = scrollx || 0;
if(this.useScrollbars){
//console.info("Set Canvas Scroll", (this.height > this.parentHeight), this.height, this.parentHeight)
dojo.style(this.domNode.parentNode, {
overflowY: this.height > this.parentHeight ? "scroll" : "hidden",
overflowX: this.width > this.parentWidth ? "scroll" : "hidden"
});
}else{
dojo.style(this.domNode.parentNode, {
overflowY: "hidden",
overflowX: "hidden"
});
}
},
setZoom: function(zoom){
// summary:
// Internal. Zooms canvas in and out.
this.zoom = zoom;
this.surface.setTransform({xx:zoom, yy:zoom});
this.setDimensions(this.width*zoom, this.height*zoom)
},
onScroll: function(){
// summary:
// Event fires on scroll.NOT IMPLEMENTED
},
getScrollOffset: function(){
// summary:
// Get the scroll position of the canvas
return {
top:this.domNode.parentNode.scrollTop,
left:this.domNode.parentNode.scrollLeft
}; // Object
},
getScrollWidth: function(){
// summary:
// Special method used to detect the width (and height)
// of the browser scrollbars. Becomes memoized.
//
var p = dojo.create('div');
p.innerHTML = '<div style="width:50px;height:50px;overflow:hidden;position:absolute;top:0;left:-1000px;"><div style="height:100px;"></div>';
var div = p.firstChild;
dojo.body().appendChild(div);
var noscroll = dojo.contentBox(div).h;
dojo.style(div, "overflow", "scroll");
var scrollWidth = noscroll - dojo.contentBox(div).h;
dojo.destroy(div);
this.getScrollWidth = function(){
return scrollWidth;
};
return scrollWidth; // Object
}
}
);
})();
}
| {
"content_hash": "fb445b3b3cc2d5c287080bdd39ed1e7c",
"timestamp": "",
"source": "github",
"line_count": 168,
"max_line_length": 144,
"avg_line_length": 29.958333333333332,
"alnum_prop": 0.6437512418040929,
"repo_name": "henry-gobiernoabierto/geomoose",
"id": "a06d9048089c0cc44a9b773af9800efc2457db1a",
"size": "5227",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "htdocs/libs/dojo/release/geomoose2.6/dojox/drawing/manager/Canvas.js",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "ActionScript",
"bytes": "41025"
},
{
"name": "Batchfile",
"bytes": "7467"
},
{
"name": "C",
"bytes": "14284"
},
{
"name": "CSS",
"bytes": "2108805"
},
{
"name": "Groff",
"bytes": "684"
},
{
"name": "HTML",
"bytes": "10442977"
},
{
"name": "Java",
"bytes": "127625"
},
{
"name": "JavaScript",
"bytes": "25771831"
},
{
"name": "Makefile",
"bytes": "2980"
},
{
"name": "PHP",
"bytes": "762912"
},
{
"name": "Perl",
"bytes": "6881"
},
{
"name": "Python",
"bytes": "231993"
},
{
"name": "Ruby",
"bytes": "16321"
},
{
"name": "Shell",
"bytes": "26868"
},
{
"name": "TeX",
"bytes": "13485"
},
{
"name": "XQuery",
"bytes": "798"
},
{
"name": "XSLT",
"bytes": "151867"
}
],
"symlink_target": ""
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Search — Material Model Laboratory 3.0 documentation</title>
<link rel="stylesheet" href="_static/alabaster.css" type="text/css" />
<link rel="stylesheet" href="_static/pygments.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: './',
VERSION: '3.0',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true,
SOURCELINK_SUFFIX: '.txt'
};
</script>
<script type="text/javascript" src="_static/jquery.js"></script>
<script type="text/javascript" src="_static/underscore.js"></script>
<script type="text/javascript" src="_static/doctools.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script type="text/javascript" src="_static/searchtools.js"></script>
<link rel="index" title="Index" href="genindex.html" />
<link rel="search" title="Search" href="#" />
<script type="text/javascript">
jQuery(function() { Search.loadIndex("searchindex.js"); });
</script>
<script type="text/javascript" id="searchindexloader"></script>
<meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9">
</head>
<body>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<h1 id="search-documentation">Search</h1>
<div id="fallback" class="admonition warning">
<script type="text/javascript">$('#fallback').hide();</script>
<p>
Please activate JavaScript to enable the search
functionality.
</p>
</div>
<p>
From here you can search these documents. Enter your search
words into the box below and click "search". Note that the search
function will automatically search for all of the words. Pages
containing fewer words won't appear in the result list.
</p>
<form action="" method="get">
<input type="text" name="q" value="" />
<input type="submit" value="search" />
<span id="search-progress" style="padding-left: 10px"></span>
</form>
<div id="search-results">
</div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="sphinxsidebarwrapper">
<h1 class="logo"><a href="index.html">Material Model Laboratory</a></h1>
<p>
<iframe src="https://ghbtns.com/github-btn.html?user=tjfulle&repo=matmodlab&type=watch&count=true&size=large"
allowtransparency="true" frameborder="0" scrolling="0" width="200px" height="35px"></iframe>
</p>
<h3>Navigation</h3>
<ul>
<li class="toctree-l1"><a class="reference internal" href="intro/index.html">1. Introduction and Overview</a></li>
<li class="toctree-l1"><a class="reference internal" href="execution/index.html">2. Job Execution</a></li>
<li class="toctree-l1"><a class="reference internal" href="material/index.html">3. Materials</a></li>
<li class="toctree-l1"><a class="reference internal" href="examples/index.html">4. Examples</a></li>
<li class="toctree-l1"><a class="reference internal" href="test/index.html">5. Material Model Testing</a></li>
</ul>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="footer">
©2014, Tim Fuller, Scot Swan.
|
Powered by <a href="http://sphinx-doc.org/">Sphinx 1.6.3</a>
& <a href="https://github.com/bitprophet/alabaster">Alabaster 0.7.4</a>
</div>
</body>
</html> | {
"content_hash": "fed0c0c37699d00ef09747c98fe6e2fb",
"timestamp": "",
"source": "github",
"line_count": 114,
"max_line_length": 143,
"avg_line_length": 34.1578947368421,
"alnum_prop": 0.6394453004622496,
"repo_name": "matmodlab/matmodlab2",
"id": "db41466c844edc89b38595e4e98f78595a9fa150",
"size": "3895",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/search.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Fortran",
"bytes": "419488"
},
{
"name": "Jupyter Notebook",
"bytes": "1458750"
},
{
"name": "Python",
"bytes": "400440"
}
],
"symlink_target": ""
} |
.v-tree-node {
background: transparent url(img/collapsed.png) no-repeat 2px 1px;
}
.v-tree-node-expanded {
background: transparent url(img/expanded.png) no-repeat 2px 1px;
}
.v-tree-node-caption {
margin-left: 18px;
}
.v-tree-node-caption .v-icon {
margin: 0 2px 0 -2px;
}
.v-tree-node-caption span {
padding: 0 1px;
}
.v-tree-node-selected span {
background: #57a7ed;
color: #fff;
padding: 1px 2px 0;
display: inline-block;
zoom: 1;
margin: -1px -1px 0;
-webkit-border-radius: 2px;
-moz-border-radius: 2px;
border-radius: 2px;
}
.v-tree-node-children {
padding-left: 16px;
}
/* IMPORTANT keep the offsetWidth (width + padding) of this element the same as the margin-left of v-tree-node-caption */
.v-ie6 .v-tree-node-ie6compatnode {
width: 14px;
height: 10px;
padding: 1px;
}
.v-tree{
outline:none;
}
.v-tree-node-caption.v-tree-node-focused span{
padding-left: 1px;
padding-top: 0px;
padding-bottom: 0px;
}
.v-tree-node-focused span{
border: 1px dotted black;
}
.v-ie6 .v-tree-node-ie6compatnode.v-tree-node-focused{
padding-left: 0px;
}
/***************************************
* Drag'n'drop styles
***************************************/
.v-tree .v-tree-node-drag-top,
.v-tree .v-tree-node-drag-top.v-tree-node-expanded {
background-position: 2px 0;
} | {
"content_hash": "cf0b46da73b694011c8daf95dc8ceb02",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 121,
"avg_line_length": 22.964285714285715,
"alnum_prop": 0.6547433903576982,
"repo_name": "rjenkins/Reusable-Vaadin-Custom-Layout-Forms",
"id": "bec3b318dd6269ddc79b3150e931fd2c3f1b4c61",
"size": "1286",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "WebContent/VAADIN/themes/runo/tree/tree.css",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "28236"
}
],
"symlink_target": ""
} |
/* */
define(['exports', 'aurelia-pal', 'aurelia-task-queue', 'aurelia-metadata'], function (exports, _aureliaPal, _aureliaTaskQueue, _aureliaMetadata) {
'use strict';
exports.__esModule = true;
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
exports.camelCase = camelCase;
exports.createOverrideContext = createOverrideContext;
exports.getContextFor = getContextFor;
exports.createScopeForTest = createScopeForTest;
exports.connectable = connectable;
exports.enqueueBindingConnect = enqueueBindingConnect;
exports.subscriberCollection = subscriberCollection;
exports.calcSplices = calcSplices;
exports.mergeSplice = mergeSplice;
exports.projectArraySplices = projectArraySplices;
exports.getChangeRecords = getChangeRecords;
exports.getArrayObserver = _getArrayObserver;
exports.getMapObserver = _getMapObserver;
exports.hasDeclaredDependencies = hasDeclaredDependencies;
exports.declarePropertyDependencies = declarePropertyDependencies;
exports.computedFrom = computedFrom;
exports.valueConverter = valueConverter;
exports.bindingBehavior = bindingBehavior;
exports.getSetObserver = _getSetObserver;
exports.observable = observable;
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function camelCase(name) {
return name.charAt(0).toLowerCase() + name.slice(1);
}
function createOverrideContext(bindingContext, parentOverrideContext) {
return {
bindingContext: bindingContext,
parentOverrideContext: parentOverrideContext || null
};
}
function getContextFor(name, scope, ancestor) {
var oc = scope.overrideContext;
if (ancestor) {
while (ancestor && oc) {
ancestor--;
oc = oc.parentOverrideContext;
}
if (ancestor || !oc) {
return undefined;
}
return name in oc ? oc : oc.bindingContext;
}
while (oc && !(name in oc) && !(oc.bindingContext && name in oc.bindingContext)) {
oc = oc.parentOverrideContext;
}
if (oc) {
return name in oc ? oc : oc.bindingContext;
}
return scope.bindingContext || scope.overrideContext;
}
function createScopeForTest(bindingContext, parentBindingContext) {
if (parentBindingContext) {
return {
bindingContext: bindingContext,
overrideContext: createOverrideContext(bindingContext, createOverrideContext(parentBindingContext))
};
}
return {
bindingContext: bindingContext,
overrideContext: createOverrideContext(bindingContext)
};
}
var sourceContext = 'Binding:source';
exports.sourceContext = sourceContext;
var slotNames = [];
var versionSlotNames = [];
for (var i = 0; i < 100; i++) {
slotNames.push('_observer' + i);
versionSlotNames.push('_observerVersion' + i);
}
function addObserver(observer) {
var observerSlots = this._observerSlots === undefined ? 0 : this._observerSlots;
var i = observerSlots;
while (i-- && this[slotNames[i]] !== observer) {}
if (i === -1) {
i = 0;
while (this[slotNames[i]]) {
i++;
}
this[slotNames[i]] = observer;
observer.subscribe(sourceContext, this);
if (i === observerSlots) {
this._observerSlots = i + 1;
}
}
if (this._version === undefined) {
this._version = 0;
}
this[versionSlotNames[i]] = this._version;
}
function observeProperty(obj, propertyName) {
var observer = this.observerLocator.getObserver(obj, propertyName);
addObserver.call(this, observer);
}
function observeArray(array) {
var observer = this.observerLocator.getArrayObserver(array);
addObserver.call(this, observer);
}
function unobserve(all) {
var i = this._observerSlots;
while (i--) {
if (all || this[versionSlotNames[i]] !== this._version) {
var observer = this[slotNames[i]];
this[slotNames[i]] = null;
if (observer) {
observer.unsubscribe(sourceContext, this);
}
}
}
}
function connectable() {
return function (target) {
target.prototype.observeProperty = observeProperty;
target.prototype.observeArray = observeArray;
target.prototype.unobserve = unobserve;
target.prototype.addObserver = addObserver;
};
}
var bindings = new Map();
var minimumImmediate = 100;
var frameBudget = 15;
var isFlushRequested = false;
var immediate = 0;
function flush(animationFrameStart) {
var i = 0;
for (var _iterator = bindings, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var binding = _ref[0];
bindings['delete'](binding);
binding.connect(true);
i++;
if (i % 100 === 0 && _aureliaPal.PLATFORM.performance.now() - animationFrameStart > frameBudget) {
break;
}
}
if (bindings.size) {
_aureliaPal.PLATFORM.requestAnimationFrame(flush);
} else {
isFlushRequested = false;
immediate = 0;
}
}
function enqueueBindingConnect(binding) {
if (immediate < minimumImmediate) {
immediate++;
binding.connect(false);
} else {
bindings.set(binding);
}
if (!isFlushRequested) {
isFlushRequested = true;
_aureliaPal.PLATFORM.requestAnimationFrame(flush);
}
}
function addSubscriber(context, callable) {
if (this.hasSubscriber(context, callable)) {
return false;
}
if (!this._context0) {
this._context0 = context;
this._callable0 = callable;
return true;
}
if (!this._context1) {
this._context1 = context;
this._callable1 = callable;
return true;
}
if (!this._context2) {
this._context2 = context;
this._callable2 = callable;
return true;
}
if (!this._contextsRest) {
this._contextsRest = [context];
this._callablesRest = [callable];
return true;
}
this._contextsRest.push(context);
this._callablesRest.push(callable);
return true;
}
function removeSubscriber(context, callable) {
if (this._context0 === context && this._callable0 === callable) {
this._context0 = null;
this._callable0 = null;
return true;
}
if (this._context1 === context && this._callable1 === callable) {
this._context1 = null;
this._callable1 = null;
return true;
}
if (this._context2 === context && this._callable2 === callable) {
this._context2 = null;
this._callable2 = null;
return true;
}
var rest = this._contextsRest;
var index = undefined;
if (!rest || !rest.length || (index = rest.indexOf(context)) === -1 || this._callablesRest[index] !== callable) {
return false;
}
rest.splice(index, 1);
this._callablesRest.splice(index, 1);
return true;
}
var arrayPool1 = [];
var arrayPool2 = [];
var poolUtilization = [];
function callSubscribers(newValue, oldValue) {
var context0 = this._context0;
var callable0 = this._callable0;
var context1 = this._context1;
var callable1 = this._callable1;
var context2 = this._context2;
var callable2 = this._callable2;
var length = this._contextsRest ? this._contextsRest.length : 0;
var contextsRest = undefined;
var callablesRest = undefined;
var poolIndex = undefined;
var i = undefined;
if (length) {
poolIndex = poolUtilization.length;
while (poolIndex-- && poolUtilization[poolIndex]) {}
if (poolIndex < 0) {
poolIndex = poolUtilization.length;
contextsRest = [];
callablesRest = [];
poolUtilization.push(true);
arrayPool1.push(contextsRest);
arrayPool2.push(callablesRest);
} else {
poolUtilization[poolIndex] = true;
contextsRest = arrayPool1[poolIndex];
callablesRest = arrayPool2[poolIndex];
}
i = length;
while (i--) {
contextsRest[i] = this._contextsRest[i];
callablesRest[i] = this._callablesRest[i];
}
}
if (context0) {
if (callable0) {
callable0.call(context0, newValue, oldValue);
} else {
context0(newValue, oldValue);
}
}
if (context1) {
if (callable1) {
callable1.call(context1, newValue, oldValue);
} else {
context1(newValue, oldValue);
}
}
if (context2) {
if (callable2) {
callable2.call(context2, newValue, oldValue);
} else {
context2(newValue, oldValue);
}
}
if (length) {
for (i = 0; i < length; i++) {
var callable = callablesRest[i];
var context = contextsRest[i];
if (callable) {
callable.call(context, newValue, oldValue);
} else {
context(newValue, oldValue);
}
contextsRest[i] = null;
callablesRest[i] = null;
}
poolUtilization[poolIndex] = false;
}
}
function hasSubscribers() {
return !!(this._context0 || this._context1 || this._context2 || this._contextsRest && this._contextsRest.length);
}
function hasSubscriber(context, callable) {
var has = this._context0 === context && this._callable0 === callable || this._context1 === context && this._callable1 === callable || this._context2 === context && this._callable2 === callable;
if (has) {
return true;
}
var index = undefined;
var contexts = this._contextsRest;
if (!contexts || (index = contexts.length) === 0) {
return false;
}
var callables = this._callablesRest;
while (index--) {
if (contexts[index] === context && callables[index] === callable) {
return true;
}
}
return false;
}
function subscriberCollection() {
return function (target) {
target.prototype.addSubscriber = addSubscriber;
target.prototype.removeSubscriber = removeSubscriber;
target.prototype.callSubscribers = callSubscribers;
target.prototype.hasSubscribers = hasSubscribers;
target.prototype.hasSubscriber = hasSubscriber;
};
}
function isIndex(s) {
return +s === s >>> 0;
}
function toNumber(s) {
return +s;
}
function newSplice(index, removed, addedCount) {
return {
index: index,
removed: removed,
addedCount: addedCount
};
}
var EDIT_LEAVE = 0;
var EDIT_UPDATE = 1;
var EDIT_ADD = 2;
var EDIT_DELETE = 3;
function ArraySplice() {}
ArraySplice.prototype = {
calcEditDistances: function calcEditDistances(current, currentStart, currentEnd, old, oldStart, oldEnd) {
var rowCount = oldEnd - oldStart + 1;
var columnCount = currentEnd - currentStart + 1;
var distances = new Array(rowCount);
var i, j, north, west;
for (i = 0; i < rowCount; ++i) {
distances[i] = new Array(columnCount);
distances[i][0] = i;
}
for (j = 0; j < columnCount; ++j) {
distances[0][j] = j;
}
for (i = 1; i < rowCount; ++i) {
for (j = 1; j < columnCount; ++j) {
if (this.equals(current[currentStart + j - 1], old[oldStart + i - 1])) distances[i][j] = distances[i - 1][j - 1];else {
north = distances[i - 1][j] + 1;
west = distances[i][j - 1] + 1;
distances[i][j] = north < west ? north : west;
}
}
}
return distances;
},
spliceOperationsFromEditDistances: function spliceOperationsFromEditDistances(distances) {
var i = distances.length - 1;
var j = distances[0].length - 1;
var current = distances[i][j];
var edits = [];
while (i > 0 || j > 0) {
if (i == 0) {
edits.push(EDIT_ADD);
j--;
continue;
}
if (j == 0) {
edits.push(EDIT_DELETE);
i--;
continue;
}
var northWest = distances[i - 1][j - 1];
var west = distances[i - 1][j];
var north = distances[i][j - 1];
var min;
if (west < north) min = west < northWest ? west : northWest;else min = north < northWest ? north : northWest;
if (min == northWest) {
if (northWest == current) {
edits.push(EDIT_LEAVE);
} else {
edits.push(EDIT_UPDATE);
current = northWest;
}
i--;
j--;
} else if (min == west) {
edits.push(EDIT_DELETE);
i--;
current = west;
} else {
edits.push(EDIT_ADD);
j--;
current = north;
}
}
edits.reverse();
return edits;
},
calcSplices: function calcSplices(current, currentStart, currentEnd, old, oldStart, oldEnd) {
var prefixCount = 0;
var suffixCount = 0;
var minLength = Math.min(currentEnd - currentStart, oldEnd - oldStart);
if (currentStart == 0 && oldStart == 0) prefixCount = this.sharedPrefix(current, old, minLength);
if (currentEnd == current.length && oldEnd == old.length) suffixCount = this.sharedSuffix(current, old, minLength - prefixCount);
currentStart += prefixCount;
oldStart += prefixCount;
currentEnd -= suffixCount;
oldEnd -= suffixCount;
if (currentEnd - currentStart == 0 && oldEnd - oldStart == 0) return [];
if (currentStart == currentEnd) {
var splice = newSplice(currentStart, [], 0);
while (oldStart < oldEnd) splice.removed.push(old[oldStart++]);
return [splice];
} else if (oldStart == oldEnd) return [newSplice(currentStart, [], currentEnd - currentStart)];
var ops = this.spliceOperationsFromEditDistances(this.calcEditDistances(current, currentStart, currentEnd, old, oldStart, oldEnd));
var splice = undefined;
var splices = [];
var index = currentStart;
var oldIndex = oldStart;
for (var i = 0; i < ops.length; ++i) {
switch (ops[i]) {
case EDIT_LEAVE:
if (splice) {
splices.push(splice);
splice = undefined;
}
index++;
oldIndex++;
break;
case EDIT_UPDATE:
if (!splice) splice = newSplice(index, [], 0);
splice.addedCount++;
index++;
splice.removed.push(old[oldIndex]);
oldIndex++;
break;
case EDIT_ADD:
if (!splice) splice = newSplice(index, [], 0);
splice.addedCount++;
index++;
break;
case EDIT_DELETE:
if (!splice) splice = newSplice(index, [], 0);
splice.removed.push(old[oldIndex]);
oldIndex++;
break;
}
}
if (splice) {
splices.push(splice);
}
return splices;
},
sharedPrefix: function sharedPrefix(current, old, searchLength) {
for (var i = 0; i < searchLength; ++i) if (!this.equals(current[i], old[i])) return i;
return searchLength;
},
sharedSuffix: function sharedSuffix(current, old, searchLength) {
var index1 = current.length;
var index2 = old.length;
var count = 0;
while (count < searchLength && this.equals(current[--index1], old[--index2])) count++;
return count;
},
calculateSplices: function calculateSplices(current, previous) {
return this.calcSplices(current, 0, current.length, previous, 0, previous.length);
},
equals: function equals(currentValue, previousValue) {
return currentValue === previousValue;
}
};
var arraySplice = new ArraySplice();
function calcSplices(current, currentStart, currentEnd, old, oldStart, oldEnd) {
return arraySplice.calcSplices(current, currentStart, currentEnd, old, oldStart, oldEnd);
}
function intersect(start1, end1, start2, end2) {
if (end1 < start2 || end2 < start1) return -1;
if (end1 == start2 || end2 == start1) return 0;
if (start1 < start2) {
if (end1 < end2) return end1 - start2;else return end2 - start2;
} else {
if (end2 < end1) return end2 - start1;else return end1 - start1;
}
}
function mergeSplice(splices, index, removed, addedCount) {
var splice = newSplice(index, removed, addedCount);
var inserted = false;
var insertionOffset = 0;
for (var i = 0; i < splices.length; i++) {
var current = splices[i];
current.index += insertionOffset;
if (inserted) continue;
var intersectCount = intersect(splice.index, splice.index + splice.removed.length, current.index, current.index + current.addedCount);
if (intersectCount >= 0) {
splices.splice(i, 1);
i--;
insertionOffset -= current.addedCount - current.removed.length;
splice.addedCount += current.addedCount - intersectCount;
var deleteCount = splice.removed.length + current.removed.length - intersectCount;
if (!splice.addedCount && !deleteCount) {
inserted = true;
} else {
var removed = current.removed;
if (splice.index < current.index) {
var prepend = splice.removed.slice(0, current.index - splice.index);
Array.prototype.push.apply(prepend, removed);
removed = prepend;
}
if (splice.index + splice.removed.length > current.index + current.addedCount) {
var append = splice.removed.slice(current.index + current.addedCount - splice.index);
Array.prototype.push.apply(removed, append);
}
splice.removed = removed;
if (current.index < splice.index) {
splice.index = current.index;
}
}
} else if (splice.index < current.index) {
inserted = true;
splices.splice(i, 0, splice);
i++;
var offset = splice.addedCount - splice.removed.length;
current.index += offset;
insertionOffset += offset;
}
}
if (!inserted) splices.push(splice);
}
function createInitialSplices(array, changeRecords) {
var splices = [];
for (var i = 0; i < changeRecords.length; i++) {
var record = changeRecords[i];
switch (record.type) {
case 'splice':
mergeSplice(splices, record.index, record.removed.slice(), record.addedCount);
break;
case 'add':
case 'update':
case 'delete':
if (!isIndex(record.name)) continue;
var index = toNumber(record.name);
if (index < 0) continue;
mergeSplice(splices, index, [record.oldValue], record.type === 'delete' ? 0 : 1);
break;
default:
console.error('Unexpected record type: ' + JSON.stringify(record));
break;
}
}
return splices;
}
function projectArraySplices(array, changeRecords) {
var splices = [];
createInitialSplices(array, changeRecords).forEach(function (splice) {
if (splice.addedCount == 1 && splice.removed.length == 1) {
if (splice.removed[0] !== array[splice.index]) splices.push(splice);
return;
};
splices = splices.concat(calcSplices(array, splice.index, splice.index + splice.addedCount, splice.removed, 0, splice.removed.length));
});
return splices;
}
function newRecord(type, object, key, oldValue) {
return {
type: type,
object: object,
key: key,
oldValue: oldValue
};
}
function getChangeRecords(map) {
var entries = [];
for (var _iterator2 = map.keys(), _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
var _ref2;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref2 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref2 = _i2.value;
}
var key = _ref2;
entries.push(newRecord('added', map, key));
}
return entries;
}
var ModifyCollectionObserver = (function () {
function ModifyCollectionObserver(taskQueue, collection) {
_classCallCheck(this, _ModifyCollectionObserver);
this.taskQueue = taskQueue;
this.queued = false;
this.changeRecords = null;
this.oldCollection = null;
this.collection = collection;
this.lengthPropertyName = collection instanceof Map || collection instanceof Set ? 'size' : 'length';
}
ModifyCollectionObserver.prototype.subscribe = function subscribe(context, callable) {
this.addSubscriber(context, callable);
};
ModifyCollectionObserver.prototype.unsubscribe = function unsubscribe(context, callable) {
this.removeSubscriber(context, callable);
};
ModifyCollectionObserver.prototype.addChangeRecord = function addChangeRecord(changeRecord) {
if (!this.hasSubscribers() && !this.lengthObserver) {
return;
}
if (changeRecord.type === 'splice') {
var index = changeRecord.index;
var arrayLength = changeRecord.object.length;
if (index > arrayLength) {
index = arrayLength - changeRecord.addedCount;
} else if (index < 0) {
index = arrayLength + changeRecord.removed.length + index - changeRecord.addedCount;
}
if (index < 0) {
index = 0;
}
changeRecord.index = index;
}
if (this.changeRecords === null) {
this.changeRecords = [changeRecord];
} else {
this.changeRecords.push(changeRecord);
}
if (!this.queued) {
this.queued = true;
this.taskQueue.queueMicroTask(this);
}
};
ModifyCollectionObserver.prototype.flushChangeRecords = function flushChangeRecords() {
if (this.changeRecords && this.changeRecords.length || this.oldCollection) {
this.call();
}
};
ModifyCollectionObserver.prototype.reset = function reset(oldCollection) {
this.oldCollection = oldCollection;
if (this.hasSubscribers() && !this.queued) {
this.queued = true;
this.taskQueue.queueMicroTask(this);
}
};
ModifyCollectionObserver.prototype.getLengthObserver = function getLengthObserver() {
return this.lengthObserver || (this.lengthObserver = new CollectionLengthObserver(this.collection));
};
ModifyCollectionObserver.prototype.call = function call() {
var changeRecords = this.changeRecords;
var oldCollection = this.oldCollection;
var records = undefined;
this.queued = false;
this.changeRecords = [];
this.oldCollection = null;
if (this.hasSubscribers()) {
if (oldCollection) {
if (this.collection instanceof Map || this.collection instanceof Set) {
records = getChangeRecords(oldCollection);
} else {
records = calcSplices(this.collection, 0, this.collection.length, oldCollection, 0, oldCollection.length);
}
} else {
if (this.collection instanceof Map || this.collection instanceof Set) {
records = changeRecords;
} else {
records = projectArraySplices(this.collection, changeRecords);
}
}
this.callSubscribers(records);
}
if (this.lengthObserver) {
this.lengthObserver.call(this.collection[this.lengthPropertyName]);
}
};
var _ModifyCollectionObserver = ModifyCollectionObserver;
ModifyCollectionObserver = subscriberCollection()(ModifyCollectionObserver) || ModifyCollectionObserver;
return ModifyCollectionObserver;
})();
exports.ModifyCollectionObserver = ModifyCollectionObserver;
var CollectionLengthObserver = (function () {
function CollectionLengthObserver(collection) {
_classCallCheck(this, _CollectionLengthObserver);
this.collection = collection;
this.lengthPropertyName = collection instanceof Map || collection instanceof Set ? 'size' : 'length';
this.currentValue = collection[this.lengthPropertyName];
}
CollectionLengthObserver.prototype.getValue = function getValue() {
return this.collection[this.lengthPropertyName];
};
CollectionLengthObserver.prototype.setValue = function setValue(newValue) {
this.collection[this.lengthPropertyName] = newValue;
};
CollectionLengthObserver.prototype.subscribe = function subscribe(context, callable) {
this.addSubscriber(context, callable);
};
CollectionLengthObserver.prototype.unsubscribe = function unsubscribe(context, callable) {
this.removeSubscriber(context, callable);
};
CollectionLengthObserver.prototype.call = function call(newValue) {
var oldValue = this.currentValue;
this.callSubscribers(newValue, oldValue);
this.currentValue = newValue;
};
var _CollectionLengthObserver = CollectionLengthObserver;
CollectionLengthObserver = subscriberCollection()(CollectionLengthObserver) || CollectionLengthObserver;
return CollectionLengthObserver;
})();
exports.CollectionLengthObserver = CollectionLengthObserver;
var pop = Array.prototype.pop;
var push = Array.prototype.push;
var reverse = Array.prototype.reverse;
var shift = Array.prototype.shift;
var sort = Array.prototype.sort;
var splice = Array.prototype.splice;
var unshift = Array.prototype.unshift;
Array.prototype.pop = function () {
var methodCallResult = pop.apply(this, arguments);
if (this.__array_observer__ !== undefined) {
this.__array_observer__.addChangeRecord({
type: 'delete',
object: this,
name: this.length,
oldValue: methodCallResult
});
}
return methodCallResult;
};
Array.prototype.push = function () {
var methodCallResult = push.apply(this, arguments);
if (this.__array_observer__ !== undefined) {
this.__array_observer__.addChangeRecord({
type: 'splice',
object: this,
index: this.length - arguments.length,
removed: [],
addedCount: arguments.length
});
}
return methodCallResult;
};
Array.prototype.reverse = function () {
var oldArray = undefined;
if (this.__array_observer__ !== undefined) {
this.__array_observer__.flushChangeRecords();
oldArray = this.slice();
}
var methodCallResult = reverse.apply(this, arguments);
if (this.__array_observer__ !== undefined) {
this.__array_observer__.reset(oldArray);
}
return methodCallResult;
};
Array.prototype.shift = function () {
var methodCallResult = shift.apply(this, arguments);
if (this.__array_observer__ !== undefined) {
this.__array_observer__.addChangeRecord({
type: 'delete',
object: this,
name: 0,
oldValue: methodCallResult
});
}
return methodCallResult;
};
Array.prototype.sort = function () {
var oldArray = undefined;
if (this.__array_observer__ !== undefined) {
this.__array_observer__.flushChangeRecords();
oldArray = this.slice();
}
var methodCallResult = sort.apply(this, arguments);
if (this.__array_observer__ !== undefined) {
this.__array_observer__.reset(oldArray);
}
return methodCallResult;
};
Array.prototype.splice = function () {
var methodCallResult = splice.apply(this, arguments);
if (this.__array_observer__ !== undefined) {
this.__array_observer__.addChangeRecord({
type: 'splice',
object: this,
index: arguments[0],
removed: methodCallResult,
addedCount: arguments.length > 2 ? arguments.length - 2 : 0
});
}
return methodCallResult;
};
Array.prototype.unshift = function () {
var methodCallResult = unshift.apply(this, arguments);
if (this.__array_observer__ !== undefined) {
this.__array_observer__.addChangeRecord({
type: 'splice',
object: this,
index: 0,
removed: [],
addedCount: arguments.length
});
}
return methodCallResult;
};
function _getArrayObserver(taskQueue, array) {
return ModifyArrayObserver['for'](taskQueue, array);
}
var ModifyArrayObserver = (function (_ModifyCollectionObserver2) {
_inherits(ModifyArrayObserver, _ModifyCollectionObserver2);
function ModifyArrayObserver(taskQueue, array) {
_classCallCheck(this, ModifyArrayObserver);
_ModifyCollectionObserver2.call(this, taskQueue, array);
}
ModifyArrayObserver['for'] = function _for(taskQueue, array) {
if (!('__array_observer__' in array)) {
var observer = ModifyArrayObserver.create(taskQueue, array);
Object.defineProperty(array, '__array_observer__', { value: observer, enumerable: false, configurable: false });
}
return array.__array_observer__;
};
ModifyArrayObserver.create = function create(taskQueue, array) {
var observer = new ModifyArrayObserver(taskQueue, array);
return observer;
};
return ModifyArrayObserver;
})(ModifyCollectionObserver);
var Expression = (function () {
function Expression() {
_classCallCheck(this, Expression);
this.isChain = false;
this.isAssignable = false;
}
Expression.prototype.evaluate = function evaluate(scope, lookupFunctions, args) {
throw new Error('Binding expression "' + this + '" cannot be evaluated.');
};
Expression.prototype.assign = function assign(scope, value, lookupFunctions) {
throw new Error('Binding expression "' + this + '" cannot be assigned to.');
};
Expression.prototype.toString = function toString() {
return Unparser.unparse(this);
};
return Expression;
})();
exports.Expression = Expression;
var Chain = (function (_Expression) {
_inherits(Chain, _Expression);
function Chain(expressions) {
_classCallCheck(this, Chain);
_Expression.call(this);
this.expressions = expressions;
this.isChain = true;
}
Chain.prototype.evaluate = function evaluate(scope, lookupFunctions) {
var result,
expressions = this.expressions,
length = expressions.length,
i,
last;
for (i = 0; i < length; ++i) {
last = expressions[i].evaluate(scope, lookupFunctions);
if (last !== null) {
result = last;
}
}
return result;
};
Chain.prototype.accept = function accept(visitor) {
visitor.visitChain(this);
};
return Chain;
})(Expression);
exports.Chain = Chain;
var BindingBehavior = (function (_Expression2) {
_inherits(BindingBehavior, _Expression2);
function BindingBehavior(expression, name, args) {
_classCallCheck(this, BindingBehavior);
_Expression2.call(this);
this.expression = expression;
this.name = name;
this.args = args;
}
BindingBehavior.prototype.evaluate = function evaluate(scope, lookupFunctions) {
return this.expression.evaluate(scope, lookupFunctions);
};
BindingBehavior.prototype.assign = function assign(scope, value, lookupFunctions) {
return this.expression.assign(scope, value, lookupFunctions);
};
BindingBehavior.prototype.accept = function accept(visitor) {
visitor.visitBindingBehavior(this);
};
BindingBehavior.prototype.connect = function connect(binding, scope) {
this.expression.connect(binding, scope);
};
BindingBehavior.prototype.bind = function bind(binding, scope, lookupFunctions) {
if (this.expression.expression && this.expression.bind) {
this.expression.bind(binding, scope, lookupFunctions);
}
var behavior = lookupFunctions.bindingBehaviors(this.name);
if (!behavior) {
throw new Error('No BindingBehavior named "' + this.name + '" was found!');
}
var behaviorKey = 'behavior-' + this.name;
if (binding[behaviorKey]) {
throw new Error('A binding behavior named "' + this.name + '" has already been applied to "' + this.expression + '"');
}
binding[behaviorKey] = behavior;
behavior.bind.apply(behavior, [binding, scope].concat(evalList(scope, this.args, binding.lookupFunctions)));
};
BindingBehavior.prototype.unbind = function unbind(binding, scope) {
var behaviorKey = 'behavior-' + this.name;
binding[behaviorKey].unbind(binding, scope);
binding[behaviorKey] = null;
if (this.expression.expression && this.expression.unbind) {
this.expression.unbind(binding, scope);
}
};
return BindingBehavior;
})(Expression);
exports.BindingBehavior = BindingBehavior;
var ValueConverter = (function (_Expression3) {
_inherits(ValueConverter, _Expression3);
function ValueConverter(expression, name, args, allArgs) {
_classCallCheck(this, ValueConverter);
_Expression3.call(this);
this.expression = expression;
this.name = name;
this.args = args;
this.allArgs = allArgs;
}
ValueConverter.prototype.evaluate = function evaluate(scope, lookupFunctions) {
var converter = lookupFunctions.valueConverters(this.name);
if (!converter) {
throw new Error('No ValueConverter named "' + this.name + '" was found!');
}
if ('toView' in converter) {
return converter.toView.apply(converter, evalList(scope, this.allArgs, lookupFunctions));
}
return this.allArgs[0].evaluate(scope, lookupFunctions);
};
ValueConverter.prototype.assign = function assign(scope, value, lookupFunctions) {
var converter = lookupFunctions.valueConverters(this.name);
if (!converter) {
throw new Error('No ValueConverter named "' + this.name + '" was found!');
}
if ('fromView' in converter) {
value = converter.fromView.apply(converter, [value].concat(evalList(scope, this.args, lookupFunctions)));
}
return this.allArgs[0].assign(scope, value, lookupFunctions);
};
ValueConverter.prototype.accept = function accept(visitor) {
visitor.visitValueConverter(this);
};
ValueConverter.prototype.connect = function connect(binding, scope) {
var expressions = this.allArgs;
var i = expressions.length;
while (i--) {
expressions[i].connect(binding, scope);
}
};
return ValueConverter;
})(Expression);
exports.ValueConverter = ValueConverter;
var Assign = (function (_Expression4) {
_inherits(Assign, _Expression4);
function Assign(target, value) {
_classCallCheck(this, Assign);
_Expression4.call(this);
this.target = target;
this.value = value;
}
Assign.prototype.evaluate = function evaluate(scope, lookupFunctions) {
return this.target.assign(scope, this.value.evaluate(scope, lookupFunctions));
};
Assign.prototype.accept = function accept(vistor) {
vistor.visitAssign(this);
};
Assign.prototype.connect = function connect(binding, scope) {};
return Assign;
})(Expression);
exports.Assign = Assign;
var Conditional = (function (_Expression5) {
_inherits(Conditional, _Expression5);
function Conditional(condition, yes, no) {
_classCallCheck(this, Conditional);
_Expression5.call(this);
this.condition = condition;
this.yes = yes;
this.no = no;
}
Conditional.prototype.evaluate = function evaluate(scope, lookupFunctions) {
return !!this.condition.evaluate(scope) ? this.yes.evaluate(scope) : this.no.evaluate(scope);
};
Conditional.prototype.accept = function accept(visitor) {
visitor.visitConditional(this);
};
Conditional.prototype.connect = function connect(binding, scope) {
this.condition.connect(binding, scope);
if (this.condition.evaluate(scope)) {
this.yes.connect(binding, scope);
} else {
this.no.connect(binding, scope);
}
};
return Conditional;
})(Expression);
exports.Conditional = Conditional;
var AccessThis = (function (_Expression6) {
_inherits(AccessThis, _Expression6);
function AccessThis(ancestor) {
_classCallCheck(this, AccessThis);
_Expression6.call(this);
this.ancestor = ancestor;
}
AccessThis.prototype.evaluate = function evaluate(scope, lookupFunctions) {
var oc = scope.overrideContext;
var i = this.ancestor;
while (i-- && oc) {
oc = oc.parentOverrideContext;
}
return i < 1 && oc ? oc.bindingContext : undefined;
};
AccessThis.prototype.accept = function accept(visitor) {
visitor.visitAccessThis(this);
};
AccessThis.prototype.connect = function connect(binding, scope) {};
return AccessThis;
})(Expression);
exports.AccessThis = AccessThis;
var AccessScope = (function (_Expression7) {
_inherits(AccessScope, _Expression7);
function AccessScope(name, ancestor) {
_classCallCheck(this, AccessScope);
_Expression7.call(this);
this.name = name;
this.ancestor = ancestor;
this.isAssignable = true;
}
AccessScope.prototype.evaluate = function evaluate(scope, lookupFunctions) {
var context = getContextFor(this.name, scope, this.ancestor);
return context[this.name];
};
AccessScope.prototype.assign = function assign(scope, value) {
var context = getContextFor(this.name, scope, this.ancestor);
return context ? context[this.name] = value : undefined;
};
AccessScope.prototype.accept = function accept(visitor) {
visitor.visitAccessScope(this);
};
AccessScope.prototype.connect = function connect(binding, scope) {
var context = getContextFor(this.name, scope, this.ancestor);
binding.observeProperty(context, this.name);
};
return AccessScope;
})(Expression);
exports.AccessScope = AccessScope;
var AccessMember = (function (_Expression8) {
_inherits(AccessMember, _Expression8);
function AccessMember(object, name) {
_classCallCheck(this, AccessMember);
_Expression8.call(this);
this.object = object;
this.name = name;
this.isAssignable = true;
}
AccessMember.prototype.evaluate = function evaluate(scope, lookupFunctions) {
var instance = this.object.evaluate(scope, lookupFunctions);
return instance === null || instance === undefined ? instance : instance[this.name];
};
AccessMember.prototype.assign = function assign(scope, value) {
var instance = this.object.evaluate(scope);
if (instance === null || instance === undefined) {
instance = {};
this.object.assign(scope, instance);
}
return instance[this.name] = value;
};
AccessMember.prototype.accept = function accept(visitor) {
visitor.visitAccessMember(this);
};
AccessMember.prototype.connect = function connect(binding, scope) {
this.object.connect(binding, scope);
var obj = this.object.evaluate(scope);
if (obj) {
binding.observeProperty(obj, this.name);
}
};
return AccessMember;
})(Expression);
exports.AccessMember = AccessMember;
var AccessKeyed = (function (_Expression9) {
_inherits(AccessKeyed, _Expression9);
function AccessKeyed(object, key) {
_classCallCheck(this, AccessKeyed);
_Expression9.call(this);
this.object = object;
this.key = key;
this.isAssignable = true;
}
AccessKeyed.prototype.evaluate = function evaluate(scope, lookupFunctions) {
var instance = this.object.evaluate(scope, lookupFunctions);
var lookup = this.key.evaluate(scope, lookupFunctions);
return getKeyed(instance, lookup);
};
AccessKeyed.prototype.assign = function assign(scope, value) {
var instance = this.object.evaluate(scope);
var lookup = this.key.evaluate(scope);
return setKeyed(instance, lookup, value);
};
AccessKeyed.prototype.accept = function accept(visitor) {
visitor.visitAccessKeyed(this);
};
AccessKeyed.prototype.connect = function connect(binding, scope) {
this.object.connect(binding, scope);
var obj = this.object.evaluate(scope);
if (obj instanceof Object) {
this.key.connect(binding, scope);
var key = this.key.evaluate(scope);
if (key !== null && key !== undefined && !(Array.isArray(obj) && typeof key === 'number')) {
binding.observeProperty(obj, key);
}
}
};
return AccessKeyed;
})(Expression);
exports.AccessKeyed = AccessKeyed;
var CallScope = (function (_Expression10) {
_inherits(CallScope, _Expression10);
function CallScope(name, args, ancestor) {
_classCallCheck(this, CallScope);
_Expression10.call(this);
this.name = name;
this.args = args;
this.ancestor = ancestor;
}
CallScope.prototype.evaluate = function evaluate(scope, lookupFunctions, mustEvaluate) {
var args = evalList(scope, this.args, lookupFunctions);
var context = getContextFor(this.name, scope, this.ancestor);
var func = getFunction(context, this.name, mustEvaluate);
if (func) {
return func.apply(context, args);
}
return undefined;
};
CallScope.prototype.accept = function accept(visitor) {
visitor.visitCallScope(this);
};
CallScope.prototype.connect = function connect(binding, scope) {
var args = this.args;
var i = args.length;
while (i--) {
args[i].connect(binding, scope);
}
};
return CallScope;
})(Expression);
exports.CallScope = CallScope;
var CallMember = (function (_Expression11) {
_inherits(CallMember, _Expression11);
function CallMember(object, name, args) {
_classCallCheck(this, CallMember);
_Expression11.call(this);
this.object = object;
this.name = name;
this.args = args;
}
CallMember.prototype.evaluate = function evaluate(scope, lookupFunctions, mustEvaluate) {
var instance = this.object.evaluate(scope, lookupFunctions);
var args = evalList(scope, this.args, lookupFunctions);
var func = getFunction(instance, this.name, mustEvaluate);
if (func) {
return func.apply(instance, args);
}
return undefined;
};
CallMember.prototype.accept = function accept(visitor) {
visitor.visitCallMember(this);
};
CallMember.prototype.connect = function connect(binding, scope) {
this.object.connect(binding, scope);
var obj = this.object.evaluate(scope);
if (getFunction(obj, this.name, false)) {
var args = this.args;
var i = args.length;
while (i--) {
args[i].connect(binding, scope);
}
}
};
return CallMember;
})(Expression);
exports.CallMember = CallMember;
var CallFunction = (function (_Expression12) {
_inherits(CallFunction, _Expression12);
function CallFunction(func, args) {
_classCallCheck(this, CallFunction);
_Expression12.call(this);
this.func = func;
this.args = args;
}
CallFunction.prototype.evaluate = function evaluate(scope, lookupFunctions, mustEvaluate) {
var func = this.func.evaluate(scope, lookupFunctions);
if (typeof func === 'function') {
return func.apply(null, evalList(scope, this.args, lookupFunctions));
}
if (!mustEvaluate && (func === null || func === undefined)) {
return undefined;
}
throw new Error(this.func + ' is not a function');
};
CallFunction.prototype.accept = function accept(visitor) {
visitor.visitCallFunction(this);
};
CallFunction.prototype.connect = function connect(binding, scope) {
this.func.connect(binding, scope);
var func = this.func.evaluate(scope);
if (typeof func === 'function') {
var args = this.args;
var i = args.length;
while (i--) {
args[i].connect(binding, scope);
}
}
};
return CallFunction;
})(Expression);
exports.CallFunction = CallFunction;
var Binary = (function (_Expression13) {
_inherits(Binary, _Expression13);
function Binary(operation, left, right) {
_classCallCheck(this, Binary);
_Expression13.call(this);
this.operation = operation;
this.left = left;
this.right = right;
}
Binary.prototype.evaluate = function evaluate(scope, lookupFunctions) {
var left = this.left.evaluate(scope);
switch (this.operation) {
case '&&':
return left && this.right.evaluate(scope);
case '||':
return left || this.right.evaluate(scope);
}
var right = this.right.evaluate(scope);
switch (this.operation) {
case '==':
return left == right;
case '===':
return left === right;
case '!=':
return left != right;
case '!==':
return left !== right;
}
if (left === null || right === null) {
switch (this.operation) {
case '+':
if (left != null) return left;
if (right != null) return right;
return 0;
case '-':
if (left != null) return left;
if (right != null) return 0 - right;
return 0;
}
return null;
}
switch (this.operation) {
case '+':
return autoConvertAdd(left, right);
case '-':
return left - right;
case '*':
return left * right;
case '/':
return left / right;
case '%':
return left % right;
case '<':
return left < right;
case '>':
return left > right;
case '<=':
return left <= right;
case '>=':
return left >= right;
case '^':
return left ^ right;
}
throw new Error('Internal error [' + this.operation + '] not handled');
};
Binary.prototype.accept = function accept(visitor) {
visitor.visitBinary(this);
};
Binary.prototype.connect = function connect(binding, scope) {
this.left.connect(binding, scope);
var left = this.left.evaluate(scope);
if (this.operation === '&&' && !left || this.operation === '||' && left) {
return;
}
this.right.connect(binding, scope);
};
return Binary;
})(Expression);
exports.Binary = Binary;
var PrefixNot = (function (_Expression14) {
_inherits(PrefixNot, _Expression14);
function PrefixNot(operation, expression) {
_classCallCheck(this, PrefixNot);
_Expression14.call(this);
this.operation = operation;
this.expression = expression;
}
PrefixNot.prototype.evaluate = function evaluate(scope, lookupFunctions) {
return !this.expression.evaluate(scope);
};
PrefixNot.prototype.accept = function accept(visitor) {
visitor.visitPrefix(this);
};
PrefixNot.prototype.connect = function connect(binding, scope) {
this.expression.connect(binding, scope);
};
return PrefixNot;
})(Expression);
exports.PrefixNot = PrefixNot;
var LiteralPrimitive = (function (_Expression15) {
_inherits(LiteralPrimitive, _Expression15);
function LiteralPrimitive(value) {
_classCallCheck(this, LiteralPrimitive);
_Expression15.call(this);
this.value = value;
}
LiteralPrimitive.prototype.evaluate = function evaluate(scope, lookupFunctions) {
return this.value;
};
LiteralPrimitive.prototype.accept = function accept(visitor) {
visitor.visitLiteralPrimitive(this);
};
LiteralPrimitive.prototype.connect = function connect(binding, scope) {};
return LiteralPrimitive;
})(Expression);
exports.LiteralPrimitive = LiteralPrimitive;
var LiteralString = (function (_Expression16) {
_inherits(LiteralString, _Expression16);
function LiteralString(value) {
_classCallCheck(this, LiteralString);
_Expression16.call(this);
this.value = value;
}
LiteralString.prototype.evaluate = function evaluate(scope, lookupFunctions) {
return this.value;
};
LiteralString.prototype.accept = function accept(visitor) {
visitor.visitLiteralString(this);
};
LiteralString.prototype.connect = function connect(binding, scope) {};
return LiteralString;
})(Expression);
exports.LiteralString = LiteralString;
var LiteralArray = (function (_Expression17) {
_inherits(LiteralArray, _Expression17);
function LiteralArray(elements) {
_classCallCheck(this, LiteralArray);
_Expression17.call(this);
this.elements = elements;
}
LiteralArray.prototype.evaluate = function evaluate(scope, lookupFunctions) {
var elements = this.elements,
length = elements.length,
result = [],
i;
for (i = 0; i < length; ++i) {
result[i] = elements[i].evaluate(scope, lookupFunctions);
}
return result;
};
LiteralArray.prototype.accept = function accept(visitor) {
visitor.visitLiteralArray(this);
};
LiteralArray.prototype.connect = function connect(binding, scope) {
var length = this.elements.length;
for (var i = 0; i < length; i++) {
this.elements[i].connect(binding, scope);
}
};
return LiteralArray;
})(Expression);
exports.LiteralArray = LiteralArray;
var LiteralObject = (function (_Expression18) {
_inherits(LiteralObject, _Expression18);
function LiteralObject(keys, values) {
_classCallCheck(this, LiteralObject);
_Expression18.call(this);
this.keys = keys;
this.values = values;
}
LiteralObject.prototype.evaluate = function evaluate(scope, lookupFunctions) {
var instance = {},
keys = this.keys,
values = this.values,
length = keys.length,
i;
for (i = 0; i < length; ++i) {
instance[keys[i]] = values[i].evaluate(scope, lookupFunctions);
}
return instance;
};
LiteralObject.prototype.accept = function accept(visitor) {
visitor.visitLiteralObject(this);
};
LiteralObject.prototype.connect = function connect(binding, scope) {
var length = this.keys.length;
for (var i = 0; i < length; i++) {
this.values[i].connect(binding, scope);
}
};
return LiteralObject;
})(Expression);
exports.LiteralObject = LiteralObject;
var Unparser = (function () {
function Unparser(buffer) {
_classCallCheck(this, Unparser);
this.buffer = buffer;
}
Unparser.unparse = function unparse(expression) {
var buffer = [],
visitor = new Unparser(buffer);
expression.accept(visitor);
return buffer.join('');
};
Unparser.prototype.write = function write(text) {
this.buffer.push(text);
};
Unparser.prototype.writeArgs = function writeArgs(args) {
var i, length;
this.write('(');
for (i = 0, length = args.length; i < length; ++i) {
if (i !== 0) {
this.write(',');
}
args[i].accept(this);
}
this.write(')');
};
Unparser.prototype.visitChain = function visitChain(chain) {
var expressions = chain.expressions,
length = expressions.length,
i;
for (i = 0; i < length; ++i) {
if (i !== 0) {
this.write(';');
}
expressions[i].accept(this);
}
};
Unparser.prototype.visitBindingBehavior = function visitBindingBehavior(behavior) {
var args = behavior.args,
length = args.length,
i;
this.write('(');
behavior.expression.accept(this);
this.write('&' + behavior.name);
for (i = 0; i < length; ++i) {
this.write(' :');
args[i].accept(this);
}
this.write(')');
};
Unparser.prototype.visitValueConverter = function visitValueConverter(converter) {
var args = converter.args,
length = args.length,
i;
this.write('(');
converter.expression.accept(this);
this.write('|' + converter.name);
for (i = 0; i < length; ++i) {
this.write(' :');
args[i].accept(this);
}
this.write(')');
};
Unparser.prototype.visitAssign = function visitAssign(assign) {
assign.target.accept(this);
this.write('=');
assign.value.accept(this);
};
Unparser.prototype.visitConditional = function visitConditional(conditional) {
conditional.condition.accept(this);
this.write('?');
conditional.yes.accept(this);
this.write(':');
conditional.no.accept(this);
};
Unparser.prototype.visitAccessThis = function visitAccessThis(access) {
if (access.ancestor === 0) {
this.write('$this');
return;
}
this.write('$parent');
var i = access.ancestor - 1;
while (i--) {
this.write('.$parent');
}
};
Unparser.prototype.visitAccessScope = function visitAccessScope(access) {
var i = access.ancestor;
while (i--) {
this.write('$parent.');
}
this.write(access.name);
};
Unparser.prototype.visitAccessMember = function visitAccessMember(access) {
access.object.accept(this);
this.write('.' + access.name);
};
Unparser.prototype.visitAccessKeyed = function visitAccessKeyed(access) {
access.object.accept(this);
this.write('[');
access.key.accept(this);
this.write(']');
};
Unparser.prototype.visitCallScope = function visitCallScope(call) {
var i = call.ancestor;
while (i--) {
this.write('$parent.');
}
this.write(call.name);
this.writeArgs(call.args);
};
Unparser.prototype.visitCallFunction = function visitCallFunction(call) {
call.func.accept(this);
this.writeArgs(call.args);
};
Unparser.prototype.visitCallMember = function visitCallMember(call) {
call.object.accept(this);
this.write('.' + call.name);
this.writeArgs(call.args);
};
Unparser.prototype.visitPrefix = function visitPrefix(prefix) {
this.write('(' + prefix.operation);
prefix.expression.accept(this);
this.write(')');
};
Unparser.prototype.visitBinary = function visitBinary(binary) {
this.write('(');
binary.left.accept(this);
this.write(binary.operation);
binary.right.accept(this);
this.write(')');
};
Unparser.prototype.visitLiteralPrimitive = function visitLiteralPrimitive(literal) {
this.write('' + literal.value);
};
Unparser.prototype.visitLiteralArray = function visitLiteralArray(literal) {
var elements = literal.elements,
length = elements.length,
i;
this.write('[');
for (i = 0; i < length; ++i) {
if (i !== 0) {
this.write(',');
}
elements[i].accept(this);
}
this.write(']');
};
Unparser.prototype.visitLiteralObject = function visitLiteralObject(literal) {
var keys = literal.keys,
values = literal.values,
length = keys.length,
i;
this.write('{');
for (i = 0; i < length; ++i) {
if (i !== 0) {
this.write(',');
}
this.write('\'' + keys[i] + '\':');
values[i].accept(this);
}
this.write('}');
};
Unparser.prototype.visitLiteralString = function visitLiteralString(literal) {
var escaped = literal.value.replace(/'/g, "\'");
this.write('\'' + escaped + '\'');
};
return Unparser;
})();
exports.Unparser = Unparser;
var evalListCache = [[], [0], [0, 0], [0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0, 0]];
function evalList(scope, list, lookupFunctions) {
var length = list.length,
cacheLength,
i;
for (cacheLength = evalListCache.length; cacheLength <= length; ++cacheLength) {
evalListCache.push([]);
}
var result = evalListCache[length];
for (i = 0; i < length; ++i) {
result[i] = list[i].evaluate(scope, lookupFunctions);
}
return result;
}
function autoConvertAdd(a, b) {
if (a != null && b != null) {
if (typeof a == 'string' && typeof b != 'string') {
return a + b.toString();
}
if (typeof a != 'string' && typeof b == 'string') {
return a.toString() + b;
}
return a + b;
}
if (a != null) {
return a;
}
if (b != null) {
return b;
}
return 0;
}
function getFunction(obj, name, mustExist) {
var func = obj === null || obj === undefined ? null : obj[name];
if (typeof func === 'function') {
return func;
}
if (!mustExist && (func === null || func === undefined)) {
return null;
}
throw new Error(name + ' is not a function');
}
function getKeyed(obj, key) {
if (Array.isArray(obj)) {
return obj[parseInt(key)];
} else if (obj) {
return obj[key];
} else if (obj === null || obj === undefined) {
return undefined;
} else {
return obj[key];
}
}
function setKeyed(obj, key, value) {
if (Array.isArray(obj)) {
var index = parseInt(key);
if (obj.length <= index) {
obj.length = index + 1;
}
obj[index] = value;
} else {
obj[key] = value;
}
return value;
}
var bindingMode = {
oneTime: 0,
oneWay: 1,
twoWay: 2
};
exports.bindingMode = bindingMode;
var Token = (function () {
function Token(index, text) {
_classCallCheck(this, Token);
this.index = index;
this.text = text;
}
Token.prototype.withOp = function withOp(op) {
this.opKey = op;
return this;
};
Token.prototype.withGetterSetter = function withGetterSetter(key) {
this.key = key;
return this;
};
Token.prototype.withValue = function withValue(value) {
this.value = value;
return this;
};
Token.prototype.toString = function toString() {
return 'Token(' + this.text + ')';
};
return Token;
})();
exports.Token = Token;
var Lexer = (function () {
function Lexer() {
_classCallCheck(this, Lexer);
}
Lexer.prototype.lex = function lex(text) {
var scanner = new Scanner(text);
var tokens = [];
var token = scanner.scanToken();
while (token) {
tokens.push(token);
token = scanner.scanToken();
}
return tokens;
};
return Lexer;
})();
exports.Lexer = Lexer;
var Scanner = (function () {
function Scanner(input) {
_classCallCheck(this, Scanner);
this.input = input;
this.length = input.length;
this.peek = 0;
this.index = -1;
this.advance();
}
Scanner.prototype.scanToken = function scanToken() {
while (this.peek <= $SPACE) {
if (++this.index >= this.length) {
this.peek = $EOF;
return null;
} else {
this.peek = this.input.charCodeAt(this.index);
}
}
if (isIdentifierStart(this.peek)) {
return this.scanIdentifier();
}
if (isDigit(this.peek)) {
return this.scanNumber(this.index);
}
var start = this.index;
switch (this.peek) {
case $PERIOD:
this.advance();
return isDigit(this.peek) ? this.scanNumber(start) : new Token(start, '.');
case $LPAREN:
case $RPAREN:
case $LBRACE:
case $RBRACE:
case $LBRACKET:
case $RBRACKET:
case $COMMA:
case $COLON:
case $SEMICOLON:
return this.scanCharacter(start, String.fromCharCode(this.peek));
case $SQ:
case $DQ:
return this.scanString();
case $PLUS:
case $MINUS:
case $STAR:
case $SLASH:
case $PERCENT:
case $CARET:
case $QUESTION:
return this.scanOperator(start, String.fromCharCode(this.peek));
case $LT:
case $GT:
case $BANG:
case $EQ:
return this.scanComplexOperator(start, $EQ, String.fromCharCode(this.peek), '=');
case $AMPERSAND:
return this.scanComplexOperator(start, $AMPERSAND, '&', '&');
case $BAR:
return this.scanComplexOperator(start, $BAR, '|', '|');
case $NBSP:
while (isWhitespace(this.peek)) {
this.advance();
}
return this.scanToken();
}
var character = String.fromCharCode(this.peek);
this.error('Unexpected character [' + character + ']');
return null;
};
Scanner.prototype.scanCharacter = function scanCharacter(start, text) {
assert(this.peek === text.charCodeAt(0));
this.advance();
return new Token(start, text);
};
Scanner.prototype.scanOperator = function scanOperator(start, text) {
assert(this.peek === text.charCodeAt(0));
assert(OPERATORS.indexOf(text) !== -1);
this.advance();
return new Token(start, text).withOp(text);
};
Scanner.prototype.scanComplexOperator = function scanComplexOperator(start, code, one, two) {
assert(this.peek === one.charCodeAt(0));
this.advance();
var text = one;
if (this.peek === code) {
this.advance();
text += two;
}
if (this.peek === code) {
this.advance();
text += two;
}
assert(OPERATORS.indexOf(text) != -1);
return new Token(start, text).withOp(text);
};
Scanner.prototype.scanIdentifier = function scanIdentifier() {
assert(isIdentifierStart(this.peek));
var start = this.index;
this.advance();
while (isIdentifierPart(this.peek)) {
this.advance();
}
var text = this.input.substring(start, this.index);
var result = new Token(start, text);
if (OPERATORS.indexOf(text) !== -1) {
result.withOp(text);
} else {
result.withGetterSetter(text);
}
return result;
};
Scanner.prototype.scanNumber = function scanNumber(start) {
assert(isDigit(this.peek));
var simple = this.index === start;
this.advance();
while (true) {
if (isDigit(this.peek)) {} else if (this.peek === $PERIOD) {
simple = false;
} else if (isExponentStart(this.peek)) {
this.advance();
if (isExponentSign(this.peek)) {
this.advance();
}
if (!isDigit(this.peek)) {
this.error('Invalid exponent', -1);
}
simple = false;
} else {
break;
}
this.advance();
}
var text = this.input.substring(start, this.index);
var value = simple ? parseInt(text) : parseFloat(text);
return new Token(start, text).withValue(value);
};
Scanner.prototype.scanString = function scanString() {
assert(this.peek === $SQ || this.peek === $DQ);
var start = this.index;
var quote = this.peek;
this.advance();
var buffer = undefined;
var marker = this.index;
while (this.peek !== quote) {
if (this.peek === $BACKSLASH) {
if (!buffer) {
buffer = [];
}
buffer.push(this.input.substring(marker, this.index));
this.advance();
var _unescaped = undefined;
if (this.peek === $u) {
var hex = this.input.substring(this.index + 1, this.index + 5);
if (!/[A-Z0-9]{4}/.test(hex)) {
this.error('Invalid unicode escape [\\u' + hex + ']');
}
_unescaped = parseInt(hex, 16);
for (var i = 0; i < 5; ++i) {
this.advance();
}
} else {
_unescaped = unescape(this.peek);
this.advance();
}
buffer.push(String.fromCharCode(_unescaped));
marker = this.index;
} else if (this.peek === $EOF) {
this.error('Unterminated quote');
} else {
this.advance();
}
}
var last = this.input.substring(marker, this.index);
this.advance();
var text = this.input.substring(start, this.index);
var unescaped = last;
if (buffer != null) {
buffer.push(last);
unescaped = buffer.join('');
}
return new Token(start, text).withValue(unescaped);
};
Scanner.prototype.advance = function advance() {
if (++this.index >= this.length) {
this.peek = $EOF;
} else {
this.peek = this.input.charCodeAt(this.index);
}
};
Scanner.prototype.error = function error(message) {
var offset = arguments.length <= 1 || arguments[1] === undefined ? 0 : arguments[1];
var position = this.index + offset;
throw new Error('Lexer Error: ' + message + ' at column ' + position + ' in expression [' + this.input + ']');
};
return Scanner;
})();
exports.Scanner = Scanner;
var OPERATORS = ['undefined', 'null', 'true', 'false', '+', '-', '*', '/', '%', '^', '=', '==', '===', '!=', '!==', '<', '>', '<=', '>=', '&&', '||', '&', '|', '!', '?'];
var $EOF = 0;
var $TAB = 9;
var $LF = 10;
var $VTAB = 11;
var $FF = 12;
var $CR = 13;
var $SPACE = 32;
var $BANG = 33;
var $DQ = 34;
var $$ = 36;
var $PERCENT = 37;
var $AMPERSAND = 38;
var $SQ = 39;
var $LPAREN = 40;
var $RPAREN = 41;
var $STAR = 42;
var $PLUS = 43;
var $COMMA = 44;
var $MINUS = 45;
var $PERIOD = 46;
var $SLASH = 47;
var $COLON = 58;
var $SEMICOLON = 59;
var $LT = 60;
var $EQ = 61;
var $GT = 62;
var $QUESTION = 63;
var $0 = 48;
var $9 = 57;
var $A = 65;
var $E = 69;
var $Z = 90;
var $LBRACKET = 91;
var $BACKSLASH = 92;
var $RBRACKET = 93;
var $CARET = 94;
var $_ = 95;
var $a = 97;
var $e = 101;
var $f = 102;
var $n = 110;
var $r = 114;
var $t = 116;
var $u = 117;
var $v = 118;
var $z = 122;
var $LBRACE = 123;
var $BAR = 124;
var $RBRACE = 125;
var $NBSP = 160;
function isWhitespace(code) {
return code >= $TAB && code <= $SPACE || code === $NBSP;
}
function isIdentifierStart(code) {
return $a <= code && code <= $z || $A <= code && code <= $Z || code === $_ || code === $$;
}
function isIdentifierPart(code) {
return $a <= code && code <= $z || $A <= code && code <= $Z || $0 <= code && code <= $9 || code === $_ || code === $$;
}
function isDigit(code) {
return $0 <= code && code <= $9;
}
function isExponentStart(code) {
return code === $e || code === $E;
}
function isExponentSign(code) {
return code === $MINUS || code === $PLUS;
}
function unescape(code) {
switch (code) {
case $n:
return $LF;
case $f:
return $FF;
case $r:
return $CR;
case $t:
return $TAB;
case $v:
return $VTAB;
default:
return code;
}
}
function assert(condition, message) {
if (!condition) {
throw message || "Assertion failed";
}
}
var EOF = new Token(-1, null);
var Parser = (function () {
function Parser() {
_classCallCheck(this, Parser);
this.cache = {};
this.lexer = new Lexer();
}
Parser.prototype.parse = function parse(input) {
input = input || '';
return this.cache[input] || (this.cache[input] = new ParserImplementation(this.lexer, input).parseChain());
};
return Parser;
})();
exports.Parser = Parser;
var ParserImplementation = (function () {
function ParserImplementation(lexer, input) {
_classCallCheck(this, ParserImplementation);
this.index = 0;
this.input = input;
this.tokens = lexer.lex(input);
}
ParserImplementation.prototype.parseChain = function parseChain() {
var isChain = false;
var expressions = [];
while (this.optional(';')) {
isChain = true;
}
while (this.index < this.tokens.length) {
if (this.peek.text === ')' || this.peek.text === '}' || this.peek.text === ']') {
this.error('Unconsumed token ' + this.peek.text);
}
var expr = this.parseBindingBehavior();
expressions.push(expr);
while (this.optional(';')) {
isChain = true;
}
if (isChain) {
this.error('Multiple expressions are not allowed.');
}
}
return expressions.length === 1 ? expressions[0] : new Chain(expressions);
};
ParserImplementation.prototype.parseBindingBehavior = function parseBindingBehavior() {
var result = this.parseValueConverter();
while (this.optional('&')) {
var _name = this.peek.text;
var args = [];
this.advance();
while (this.optional(':')) {
args.push(this.parseExpression());
}
result = new BindingBehavior(result, _name, args);
}
return result;
};
ParserImplementation.prototype.parseValueConverter = function parseValueConverter() {
var result = this.parseExpression();
while (this.optional('|')) {
var _name2 = this.peek.text;
var args = [];
this.advance();
while (this.optional(':')) {
args.push(this.parseExpression());
}
result = new ValueConverter(result, _name2, args, [result].concat(args));
}
return result;
};
ParserImplementation.prototype.parseExpression = function parseExpression() {
var start = this.peek.index;
var result = this.parseConditional();
while (this.peek.text === '=') {
if (!result.isAssignable) {
var end = this.index < this.tokens.length ? this.peek.index : this.input.length;
var expression = this.input.substring(start, end);
this.error('Expression ' + expression + ' is not assignable');
}
this.expect('=');
result = new Assign(result, this.parseConditional());
}
return result;
};
ParserImplementation.prototype.parseConditional = function parseConditional() {
var start = this.peek.index;
var result = this.parseLogicalOr();
if (this.optional('?')) {
var yes = this.parseExpression();
if (!this.optional(':')) {
var end = this.index < this.tokens.length ? this.peek.index : this.input.length;
var expression = this.input.substring(start, end);
this.error('Conditional expression ' + expression + ' requires all 3 expressions');
}
var no = this.parseExpression();
result = new Conditional(result, yes, no);
}
return result;
};
ParserImplementation.prototype.parseLogicalOr = function parseLogicalOr() {
var result = this.parseLogicalAnd();
while (this.optional('||')) {
result = new Binary('||', result, this.parseLogicalAnd());
}
return result;
};
ParserImplementation.prototype.parseLogicalAnd = function parseLogicalAnd() {
var result = this.parseEquality();
while (this.optional('&&')) {
result = new Binary('&&', result, this.parseEquality());
}
return result;
};
ParserImplementation.prototype.parseEquality = function parseEquality() {
var result = this.parseRelational();
while (true) {
if (this.optional('==')) {
result = new Binary('==', result, this.parseRelational());
} else if (this.optional('!=')) {
result = new Binary('!=', result, this.parseRelational());
} else if (this.optional('===')) {
result = new Binary('===', result, this.parseRelational());
} else if (this.optional('!==')) {
result = new Binary('!==', result, this.parseRelational());
} else {
return result;
}
}
};
ParserImplementation.prototype.parseRelational = function parseRelational() {
var result = this.parseAdditive();
while (true) {
if (this.optional('<')) {
result = new Binary('<', result, this.parseAdditive());
} else if (this.optional('>')) {
result = new Binary('>', result, this.parseAdditive());
} else if (this.optional('<=')) {
result = new Binary('<=', result, this.parseAdditive());
} else if (this.optional('>=')) {
result = new Binary('>=', result, this.parseAdditive());
} else {
return result;
}
}
};
ParserImplementation.prototype.parseAdditive = function parseAdditive() {
var result = this.parseMultiplicative();
while (true) {
if (this.optional('+')) {
result = new Binary('+', result, this.parseMultiplicative());
} else if (this.optional('-')) {
result = new Binary('-', result, this.parseMultiplicative());
} else {
return result;
}
}
};
ParserImplementation.prototype.parseMultiplicative = function parseMultiplicative() {
var result = this.parsePrefix();
while (true) {
if (this.optional('*')) {
result = new Binary('*', result, this.parsePrefix());
} else if (this.optional('%')) {
result = new Binary('%', result, this.parsePrefix());
} else if (this.optional('/')) {
result = new Binary('/', result, this.parsePrefix());
} else {
return result;
}
}
};
ParserImplementation.prototype.parsePrefix = function parsePrefix() {
if (this.optional('+')) {
return this.parsePrefix();
} else if (this.optional('-')) {
return new Binary('-', new LiteralPrimitive(0), this.parsePrefix());
} else if (this.optional('!')) {
return new PrefixNot('!', this.parsePrefix());
} else {
return this.parseAccessOrCallMember();
}
};
ParserImplementation.prototype.parseAccessOrCallMember = function parseAccessOrCallMember() {
var result = this.parsePrimary();
while (true) {
if (this.optional('.')) {
var _name3 = this.peek.text;
this.advance();
if (this.optional('(')) {
var args = this.parseExpressionList(')');
this.expect(')');
if (result instanceof AccessThis) {
result = new CallScope(_name3, args, result.ancestor);
} else {
result = new CallMember(result, _name3, args);
}
} else {
if (result instanceof AccessThis) {
result = new AccessScope(_name3, result.ancestor);
} else {
result = new AccessMember(result, _name3);
}
}
} else if (this.optional('[')) {
var key = this.parseExpression();
this.expect(']');
result = new AccessKeyed(result, key);
} else if (this.optional('(')) {
var args = this.parseExpressionList(')');
this.expect(')');
result = new CallFunction(result, args);
} else {
return result;
}
}
};
ParserImplementation.prototype.parsePrimary = function parsePrimary() {
if (this.optional('(')) {
var result = this.parseExpression();
this.expect(')');
return result;
} else if (this.optional('null')) {
return new LiteralPrimitive(null);
} else if (this.optional('undefined')) {
return new LiteralPrimitive(undefined);
} else if (this.optional('true')) {
return new LiteralPrimitive(true);
} else if (this.optional('false')) {
return new LiteralPrimitive(false);
} else if (this.optional('[')) {
var _elements = this.parseExpressionList(']');
this.expect(']');
return new LiteralArray(_elements);
} else if (this.peek.text == '{') {
return this.parseObject();
} else if (this.peek.key != null) {
return this.parseAccessOrCallScope();
} else if (this.peek.value != null) {
var value = this.peek.value;
this.advance();
return value instanceof String || typeof value === 'string' ? new LiteralString(value) : new LiteralPrimitive(value);
} else if (this.index >= this.tokens.length) {
throw new Error('Unexpected end of expression: ' + this.input);
} else {
this.error('Unexpected token ' + this.peek.text);
}
};
ParserImplementation.prototype.parseAccessOrCallScope = function parseAccessOrCallScope() {
var name = this.peek.key;
this.advance();
if (name === '$this') {
return new AccessThis(0);
}
var ancestor = 0;
while (name === '$parent') {
ancestor++;
if (this.optional('.')) {
name = this.peek.key;
this.advance();
} else if (this.peek === EOF || this.peek.text === '(' || this.peek.text === '[' || this.peek.text === '}') {
return new AccessThis(ancestor);
} else {
this.error('Unexpected token ' + this.peek.text);
}
}
if (this.optional('(')) {
var args = this.parseExpressionList(')');
this.expect(')');
return new CallScope(name, args, ancestor);
}
return new AccessScope(name, ancestor);
};
ParserImplementation.prototype.parseObject = function parseObject() {
var keys = [];
var values = [];
this.expect('{');
if (this.peek.text !== '}') {
do {
var peek = this.peek;
var value = peek.value;
keys.push(typeof value === 'string' ? value : peek.text);
this.advance();
if (peek.key && (this.peek.text === ',' || this.peek.text === '}')) {
--this.index;
values.push(this.parseAccessOrCallScope());
} else {
this.expect(':');
values.push(this.parseExpression());
}
} while (this.optional(','));
}
this.expect('}');
return new LiteralObject(keys, values);
};
ParserImplementation.prototype.parseExpressionList = function parseExpressionList(terminator) {
var result = [];
if (this.peek.text != terminator) {
do {
result.push(this.parseExpression());
} while (this.optional(','));
}
return result;
};
ParserImplementation.prototype.optional = function optional(text) {
if (this.peek.text === text) {
this.advance();
return true;
}
return false;
};
ParserImplementation.prototype.expect = function expect(text) {
if (this.peek.text === text) {
this.advance();
} else {
this.error('Missing expected ' + text);
}
};
ParserImplementation.prototype.advance = function advance() {
this.index++;
};
ParserImplementation.prototype.error = function error(message) {
var location = this.index < this.tokens.length ? 'at column ' + (this.tokens[this.index].index + 1) + ' in' : 'at the end of the expression';
throw new Error('Parser Error: ' + message + ' ' + location + ' [' + this.input + ']');
};
_createClass(ParserImplementation, [{
key: 'peek',
get: function get() {
return this.index < this.tokens.length ? this.tokens[this.index] : EOF;
}
}]);
return ParserImplementation;
})();
exports.ParserImplementation = ParserImplementation;
var mapProto = Map.prototype;
function _getMapObserver(taskQueue, map) {
return ModifyMapObserver['for'](taskQueue, map);
}
var ModifyMapObserver = (function (_ModifyCollectionObserver3) {
_inherits(ModifyMapObserver, _ModifyCollectionObserver3);
function ModifyMapObserver(taskQueue, map) {
_classCallCheck(this, ModifyMapObserver);
_ModifyCollectionObserver3.call(this, taskQueue, map);
}
ModifyMapObserver['for'] = function _for(taskQueue, map) {
if (!('__map_observer__' in map)) {
var observer = ModifyMapObserver.create(taskQueue, map);
Object.defineProperty(map, '__map_observer__', { value: observer, enumerable: false, configurable: false });
}
return map.__map_observer__;
};
ModifyMapObserver.create = function create(taskQueue, map) {
var observer = new ModifyMapObserver(taskQueue, map);
var proto = mapProto;
if (proto.add !== map.add || proto['delete'] !== map['delete'] || proto.clear !== map.clear) {
proto = {
add: map.add,
'delete': map['delete'],
clear: map.clear
};
}
map['set'] = function () {
var hasValue = map.has(arguments[0]);
var type = hasValue ? 'update' : 'add';
var oldValue = map.get(arguments[0]);
var methodCallResult = proto['set'].apply(map, arguments);
if (!hasValue || oldValue !== map.get(arguments[0])) {
observer.addChangeRecord({
type: type,
object: map,
key: arguments[0],
oldValue: oldValue
});
}
return methodCallResult;
};
map['delete'] = function () {
var hasValue = map.has(arguments[0]);
var oldValue = map.get(arguments[0]);
var methodCallResult = proto['delete'].apply(map, arguments);
if (hasValue) {
observer.addChangeRecord({
type: 'delete',
object: map,
key: arguments[0],
oldValue: oldValue
});
}
return methodCallResult;
};
map['clear'] = function () {
var methodCallResult = proto['clear'].apply(map, arguments);
observer.addChangeRecord({
type: 'clear',
object: map
});
return methodCallResult;
};
return observer;
};
return ModifyMapObserver;
})(ModifyCollectionObserver);
function findOriginalEventTarget(event) {
return event.path && event.path[0] || event.deepPath && event.deepPath[0] || event.target;
}
function handleDelegatedEvent(event) {
var target = findOriginalEventTarget(event);
var callback = undefined;
while (target && !callback) {
if (target.delegatedCallbacks) {
callback = target.delegatedCallbacks[event.type];
}
if (!callback) {
target = target.parentNode;
}
}
if (callback) {
callback(event);
}
}
var DelegateHandlerEntry = (function () {
function DelegateHandlerEntry(eventName) {
_classCallCheck(this, DelegateHandlerEntry);
this.eventName = eventName;
this.count = 0;
}
DelegateHandlerEntry.prototype.increment = function increment() {
this.count++;
if (this.count === 1) {
_aureliaPal.DOM.addEventListener(this.eventName, handleDelegatedEvent, false);
}
};
DelegateHandlerEntry.prototype.decrement = function decrement() {
this.count--;
if (this.count === 0) {
_aureliaPal.DOM.removeEventListener(this.eventName, handleDelegatedEvent);
}
};
return DelegateHandlerEntry;
})();
var DefaultEventStrategy = (function () {
function DefaultEventStrategy() {
_classCallCheck(this, DefaultEventStrategy);
this.delegatedHandlers = [];
}
DefaultEventStrategy.prototype.subscribe = function subscribe(target, targetEvent, callback, delegate) {
var _this = this;
if (delegate) {
var _ret = (function () {
var delegatedHandlers = _this.delegatedHandlers;
var handlerEntry = delegatedHandlers[targetEvent] || (delegatedHandlers[targetEvent] = new DelegateHandlerEntry(targetEvent));
var delegatedCallbacks = target.delegatedCallbacks || (target.delegatedCallbacks = {});
handlerEntry.increment();
delegatedCallbacks[targetEvent] = callback;
return {
v: function () {
handlerEntry.decrement();
delegatedCallbacks[targetEvent] = null;
}
};
})();
if (typeof _ret === 'object') return _ret.v;
} else {
target.addEventListener(targetEvent, callback, false);
return function () {
target.removeEventListener(targetEvent, callback);
};
}
};
return DefaultEventStrategy;
})();
var EventManager = (function () {
function EventManager() {
_classCallCheck(this, EventManager);
this.elementHandlerLookup = {};
this.eventStrategyLookup = {};
this.registerElementConfig({
tagName: 'input',
properties: {
value: ['change', 'input'],
checked: ['change', 'input'],
files: ['change', 'input']
}
});
this.registerElementConfig({
tagName: 'textarea',
properties: {
value: ['change', 'input']
}
});
this.registerElementConfig({
tagName: 'select',
properties: {
value: ['change']
}
});
this.registerElementConfig({
tagName: 'content editable',
properties: {
value: ['change', 'input', 'blur', 'keyup', 'paste']
}
});
this.registerElementConfig({
tagName: 'scrollable element',
properties: {
scrollTop: ['scroll'],
scrollLeft: ['scroll']
}
});
this.defaultEventStrategy = new DefaultEventStrategy();
}
EventManager.prototype.registerElementConfig = function registerElementConfig(config) {
var tagName = config.tagName.toLowerCase();
var properties = config.properties;
var propertyName = undefined;
this.elementHandlerLookup[tagName] = {};
for (propertyName in properties) {
if (properties.hasOwnProperty(propertyName)) {
this.registerElementPropertyConfig(tagName, propertyName, properties[propertyName]);
}
}
};
EventManager.prototype.registerElementPropertyConfig = function registerElementPropertyConfig(tagName, propertyName, events) {
this.elementHandlerLookup[tagName][propertyName] = this.createElementHandler(events);
};
EventManager.prototype.createElementHandler = function createElementHandler(events) {
return {
subscribe: function subscribe(target, callback) {
events.forEach(function (changeEvent) {
target.addEventListener(changeEvent, callback, false);
});
return function () {
events.forEach(function (changeEvent) {
target.removeEventListener(changeEvent, callback);
});
};
}
};
};
EventManager.prototype.registerElementHandler = function registerElementHandler(tagName, handler) {
this.elementHandlerLookup[tagName.toLowerCase()] = handler;
};
EventManager.prototype.registerEventStrategy = function registerEventStrategy(eventName, strategy) {
this.eventStrategyLookup[eventName] = strategy;
};
EventManager.prototype.getElementHandler = function getElementHandler(target, propertyName) {
var tagName = undefined;
var lookup = this.elementHandlerLookup;
if (target.tagName) {
tagName = target.tagName.toLowerCase();
if (lookup[tagName] && lookup[tagName][propertyName]) {
return lookup[tagName][propertyName];
}
if (propertyName === 'textContent' || propertyName === 'innerHTML') {
return lookup['content editable']['value'];
}
if (propertyName === 'scrollTop' || propertyName === 'scrollLeft') {
return lookup['scrollable element'][propertyName];
}
}
return null;
};
EventManager.prototype.addEventListener = function addEventListener(target, targetEvent, callback, delegate) {
return (this.eventStrategyLookup[targetEvent] || this.defaultEventStrategy).subscribe(target, targetEvent, callback, delegate);
};
return EventManager;
})();
exports.EventManager = EventManager;
var DirtyChecker = (function () {
function DirtyChecker() {
_classCallCheck(this, DirtyChecker);
this.tracked = [];
this.checkDelay = 120;
}
DirtyChecker.prototype.addProperty = function addProperty(property) {
var tracked = this.tracked;
tracked.push(property);
if (tracked.length === 1) {
this.scheduleDirtyCheck();
}
};
DirtyChecker.prototype.removeProperty = function removeProperty(property) {
var tracked = this.tracked;
tracked.splice(tracked.indexOf(property), 1);
};
DirtyChecker.prototype.scheduleDirtyCheck = function scheduleDirtyCheck() {
var _this2 = this;
setTimeout(function () {
return _this2.check();
}, this.checkDelay);
};
DirtyChecker.prototype.check = function check() {
var tracked = this.tracked,
i = tracked.length;
while (i--) {
var current = tracked[i];
if (current.isDirty()) {
current.call();
}
}
if (tracked.length) {
this.scheduleDirtyCheck();
}
};
return DirtyChecker;
})();
exports.DirtyChecker = DirtyChecker;
var DirtyCheckProperty = (function () {
function DirtyCheckProperty(dirtyChecker, obj, propertyName) {
_classCallCheck(this, _DirtyCheckProperty);
this.dirtyChecker = dirtyChecker;
this.obj = obj;
this.propertyName = propertyName;
}
DirtyCheckProperty.prototype.getValue = function getValue() {
return this.obj[this.propertyName];
};
DirtyCheckProperty.prototype.setValue = function setValue(newValue) {
this.obj[this.propertyName] = newValue;
};
DirtyCheckProperty.prototype.call = function call() {
var oldValue = this.oldValue;
var newValue = this.getValue();
this.callSubscribers(newValue, oldValue);
this.oldValue = newValue;
};
DirtyCheckProperty.prototype.isDirty = function isDirty() {
return this.oldValue !== this.obj[this.propertyName];
};
DirtyCheckProperty.prototype.subscribe = function subscribe(context, callable) {
if (!this.hasSubscribers()) {
this.oldValue = this.getValue();
this.dirtyChecker.addProperty(this);
}
this.addSubscriber(context, callable);
};
DirtyCheckProperty.prototype.unsubscribe = function unsubscribe(context, callable) {
if (this.removeSubscriber(context, callable) && !this.hasSubscribers()) {
this.dirtyChecker.removeProperty(this);
}
};
var _DirtyCheckProperty = DirtyCheckProperty;
DirtyCheckProperty = subscriberCollection()(DirtyCheckProperty) || DirtyCheckProperty;
return DirtyCheckProperty;
})();
exports.DirtyCheckProperty = DirtyCheckProperty;
var propertyAccessor = {
getValue: function getValue(obj, propertyName) {
return obj[propertyName];
},
setValue: function setValue(value, obj, propertyName) {
return obj[propertyName] = value;
}
};
exports.propertyAccessor = propertyAccessor;
var PrimitiveObserver = (function () {
function PrimitiveObserver(primitive, propertyName) {
_classCallCheck(this, PrimitiveObserver);
this.doNotCache = true;
this.primitive = primitive;
this.propertyName = propertyName;
}
PrimitiveObserver.prototype.getValue = function getValue() {
return this.primitive[this.propertyName];
};
PrimitiveObserver.prototype.setValue = function setValue() {
var type = typeof this.primitive;
throw new Error('The ' + this.propertyName + ' property of a ' + type + ' (' + this.primitive + ') cannot be assigned.');
};
PrimitiveObserver.prototype.subscribe = function subscribe() {};
PrimitiveObserver.prototype.unsubscribe = function unsubscribe() {};
return PrimitiveObserver;
})();
exports.PrimitiveObserver = PrimitiveObserver;
var SetterObserver = (function () {
function SetterObserver(taskQueue, obj, propertyName) {
_classCallCheck(this, _SetterObserver);
this.taskQueue = taskQueue;
this.obj = obj;
this.propertyName = propertyName;
this.queued = false;
this.observing = false;
}
SetterObserver.prototype.getValue = function getValue() {
return this.obj[this.propertyName];
};
SetterObserver.prototype.setValue = function setValue(newValue) {
this.obj[this.propertyName] = newValue;
};
SetterObserver.prototype.getterValue = function getterValue() {
return this.currentValue;
};
SetterObserver.prototype.setterValue = function setterValue(newValue) {
var oldValue = this.currentValue;
if (oldValue !== newValue) {
if (!this.queued) {
this.oldValue = oldValue;
this.queued = true;
this.taskQueue.queueMicroTask(this);
}
this.currentValue = newValue;
}
};
SetterObserver.prototype.call = function call() {
var oldValue = this.oldValue;
var newValue = this.currentValue;
this.queued = false;
this.callSubscribers(newValue, oldValue);
};
SetterObserver.prototype.subscribe = function subscribe(context, callable) {
if (!this.observing) {
this.convertProperty();
}
this.addSubscriber(context, callable);
};
SetterObserver.prototype.unsubscribe = function unsubscribe(context, callable) {
this.removeSubscriber(context, callable);
};
SetterObserver.prototype.convertProperty = function convertProperty() {
this.observing = true;
this.currentValue = this.obj[this.propertyName];
this.setValue = this.setterValue;
this.getValue = this.getterValue;
try {
Object.defineProperty(this.obj, this.propertyName, {
configurable: true,
enumerable: true,
get: this.getValue.bind(this),
set: this.setValue.bind(this)
});
} catch (_) {}
};
var _SetterObserver = SetterObserver;
SetterObserver = subscriberCollection()(SetterObserver) || SetterObserver;
return SetterObserver;
})();
exports.SetterObserver = SetterObserver;
var XLinkAttributeObserver = (function () {
function XLinkAttributeObserver(element, propertyName, attributeName) {
_classCallCheck(this, XLinkAttributeObserver);
this.element = element;
this.propertyName = propertyName;
this.attributeName = attributeName;
}
XLinkAttributeObserver.prototype.getValue = function getValue() {
return this.element.getAttributeNS('http://www.w3.org/1999/xlink', this.attributeName);
};
XLinkAttributeObserver.prototype.setValue = function setValue(newValue) {
return this.element.setAttributeNS('http://www.w3.org/1999/xlink', this.attributeName, newValue);
};
XLinkAttributeObserver.prototype.subscribe = function subscribe() {
throw new Error('Observation of a "' + this.element.nodeName + '" element\'s "' + this.propertyName + '" property is not supported.');
};
return XLinkAttributeObserver;
})();
exports.XLinkAttributeObserver = XLinkAttributeObserver;
var dataAttributeAccessor = {
getValue: function getValue(obj, propertyName) {
return obj.getAttribute(propertyName);
},
setValue: function setValue(value, obj, propertyName) {
return obj.setAttribute(propertyName, value);
}
};
exports.dataAttributeAccessor = dataAttributeAccessor;
var DataAttributeObserver = (function () {
function DataAttributeObserver(element, propertyName) {
_classCallCheck(this, DataAttributeObserver);
this.element = element;
this.propertyName = propertyName;
}
DataAttributeObserver.prototype.getValue = function getValue() {
return this.element.getAttribute(this.propertyName);
};
DataAttributeObserver.prototype.setValue = function setValue(newValue) {
return this.element.setAttribute(this.propertyName, newValue);
};
DataAttributeObserver.prototype.subscribe = function subscribe() {
throw new Error('Observation of a "' + this.element.nodeName + '" element\'s "' + this.propertyName + '" property is not supported.');
};
return DataAttributeObserver;
})();
exports.DataAttributeObserver = DataAttributeObserver;
var StyleObserver = (function () {
function StyleObserver(element, propertyName) {
_classCallCheck(this, StyleObserver);
this.element = element;
this.propertyName = propertyName;
this.styles = null;
this.version = 0;
}
StyleObserver.prototype.getValue = function getValue() {
return this.element.style.cssText;
};
StyleObserver.prototype.setValue = function setValue(newValue) {
var styles = this.styles || {},
style = undefined,
version = this.version;
if (newValue !== null && newValue !== undefined) {
if (newValue instanceof Object) {
for (style in newValue) {
if (newValue.hasOwnProperty(style)) {
styles[style] = version;
this.element.style[style] = newValue[style];
}
}
} else if (newValue.length) {
var pairs = newValue.split(/(?:;|:(?!\/))\s*/);
for (var i = 0, _length = pairs.length; i < _length; i++) {
style = pairs[i].trim();
if (!style) {
continue;
}
styles[style] = version;
this.element.style[style] = pairs[++i];
}
}
}
this.styles = styles;
this.version += 1;
if (version === 0) {
return;
}
version -= 1;
for (style in styles) {
if (!styles.hasOwnProperty(style) || styles[style] !== version) {
continue;
}
this.element.style[style] = '';
}
};
StyleObserver.prototype.subscribe = function subscribe() {
throw new Error('Observation of a "' + this.element.nodeName + '" element\'s "' + this.propertyName + '" property is not supported.');
};
return StyleObserver;
})();
exports.StyleObserver = StyleObserver;
var ValueAttributeObserver = (function () {
function ValueAttributeObserver(element, propertyName, handler) {
_classCallCheck(this, _ValueAttributeObserver);
this.element = element;
this.propertyName = propertyName;
this.handler = handler;
if (propertyName === 'files') {
this.setValue = function () {};
}
}
ValueAttributeObserver.prototype.getValue = function getValue() {
return this.element[this.propertyName];
};
ValueAttributeObserver.prototype.setValue = function setValue(newValue) {
newValue = newValue === undefined || newValue === null ? '' : newValue;
if (this.element[this.propertyName] !== newValue) {
this.element[this.propertyName] = newValue;
this.notify();
}
};
ValueAttributeObserver.prototype.notify = function notify() {
var oldValue = this.oldValue;
var newValue = this.getValue();
this.callSubscribers(newValue, oldValue);
this.oldValue = newValue;
};
ValueAttributeObserver.prototype.subscribe = function subscribe(context, callable) {
if (!this.hasSubscribers()) {
this.oldValue = this.getValue();
this.disposeHandler = this.handler.subscribe(this.element, this.notify.bind(this));
}
this.addSubscriber(context, callable);
};
ValueAttributeObserver.prototype.unsubscribe = function unsubscribe(context, callable) {
if (this.removeSubscriber(context, callable) && !this.hasSubscribers()) {
this.disposeHandler();
this.disposeHandler = null;
}
};
var _ValueAttributeObserver = ValueAttributeObserver;
ValueAttributeObserver = subscriberCollection()(ValueAttributeObserver) || ValueAttributeObserver;
return ValueAttributeObserver;
})();
exports.ValueAttributeObserver = ValueAttributeObserver;
var checkedArrayContext = 'CheckedObserver:array';
var CheckedObserver = (function () {
function CheckedObserver(element, handler, observerLocator) {
_classCallCheck(this, _CheckedObserver);
this.element = element;
this.handler = handler;
this.observerLocator = observerLocator;
}
CheckedObserver.prototype.getValue = function getValue() {
return this.value;
};
CheckedObserver.prototype.setValue = function setValue(newValue) {
if (this.value === newValue) {
return;
}
if (this.arrayObserver) {
this.arrayObserver.unsubscribe(checkedArrayContext, this);
this.arrayObserver = null;
}
if (this.element.type === 'checkbox' && Array.isArray(newValue)) {
this.arrayObserver = this.observerLocator.getArrayObserver(newValue);
this.arrayObserver.subscribe(checkedArrayContext, this);
}
this.oldValue = this.value;
this.value = newValue;
this.synchronizeElement();
this.notify();
if (!this.initialSync) {
this.initialSync = true;
this.observerLocator.taskQueue.queueMicroTask(this);
}
};
CheckedObserver.prototype.call = function call(context, splices) {
this.synchronizeElement();
};
CheckedObserver.prototype.synchronizeElement = function synchronizeElement() {
var value = this.value,
element = this.element,
elementValue = element.hasOwnProperty('model') ? element.model : element.value,
isRadio = element.type === 'radio',
matcher = element.matcher || function (a, b) {
return a === b;
};
element.checked = isRadio && !!matcher(value, elementValue) || !isRadio && value === true || !isRadio && Array.isArray(value) && !!value.find(function (item) {
return !!matcher(item, elementValue);
});
};
CheckedObserver.prototype.synchronizeValue = function synchronizeValue() {
var value = this.value,
element = this.element,
elementValue = element.hasOwnProperty('model') ? element.model : element.value,
index = undefined,
matcher = element.matcher || function (a, b) {
return a === b;
};
if (element.type === 'checkbox') {
if (Array.isArray(value)) {
index = value.findIndex(function (item) {
return !!matcher(item, elementValue);
});
if (element.checked && index === -1) {
value.push(elementValue);
} else if (!element.checked && index !== -1) {
value.splice(index, 1);
}
return;
} else {
value = element.checked;
}
} else if (element.checked) {
value = elementValue;
} else {
return;
}
this.oldValue = this.value;
this.value = value;
this.notify();
};
CheckedObserver.prototype.notify = function notify() {
var oldValue = this.oldValue;
var newValue = this.value;
this.callSubscribers(newValue, oldValue);
};
CheckedObserver.prototype.subscribe = function subscribe(context, callable) {
if (!this.hasSubscribers()) {
this.disposeHandler = this.handler.subscribe(this.element, this.synchronizeValue.bind(this, false));
}
this.addSubscriber(context, callable);
};
CheckedObserver.prototype.unsubscribe = function unsubscribe(context, callable) {
if (this.removeSubscriber(context, callable) && !this.hasSubscribers()) {
this.disposeHandler();
this.disposeHandler = null;
}
};
CheckedObserver.prototype.unbind = function unbind() {
if (this.arrayObserver) {
this.arrayObserver.unsubscribe(checkedArrayContext, this);
this.arrayObserver = null;
}
};
var _CheckedObserver = CheckedObserver;
CheckedObserver = subscriberCollection()(CheckedObserver) || CheckedObserver;
return CheckedObserver;
})();
exports.CheckedObserver = CheckedObserver;
var selectArrayContext = 'SelectValueObserver:array';
var SelectValueObserver = (function () {
function SelectValueObserver(element, handler, observerLocator) {
_classCallCheck(this, _SelectValueObserver);
this.element = element;
this.handler = handler;
this.observerLocator = observerLocator;
}
SelectValueObserver.prototype.getValue = function getValue() {
return this.value;
};
SelectValueObserver.prototype.setValue = function setValue(newValue) {
if (newValue !== null && newValue !== undefined && this.element.multiple && !Array.isArray(newValue)) {
throw new Error('Only null or Array instances can be bound to a multi-select.');
}
if (this.value === newValue) {
return;
}
if (this.arrayObserver) {
this.arrayObserver.unsubscribe(selectArrayContext, this);
this.arrayObserver = null;
}
if (Array.isArray(newValue)) {
this.arrayObserver = this.observerLocator.getArrayObserver(newValue);
this.arrayObserver.subscribe(selectArrayContext, this);
}
this.oldValue = this.value;
this.value = newValue;
this.synchronizeOptions();
this.notify();
if (!this.initialSync) {
this.initialSync = true;
this.observerLocator.taskQueue.queueMicroTask(this);
}
};
SelectValueObserver.prototype.call = function call(context, splices) {
this.synchronizeOptions();
};
SelectValueObserver.prototype.synchronizeOptions = function synchronizeOptions() {
var value = this.value,
clear = undefined,
isArray = undefined;
if (value === null || value === undefined) {
clear = true;
} else if (Array.isArray(value)) {
isArray = true;
}
var options = this.element.options;
var i = options.length;
var matcher = this.element.matcher || function (a, b) {
return a === b;
};
var _loop = function () {
var option = options.item(i);
if (clear) {
option.selected = false;
return 'continue';
}
var optionValue = option.hasOwnProperty('model') ? option.model : option.value;
if (isArray) {
option.selected = !!value.find(function (item) {
return !!matcher(optionValue, item);
});
return 'continue';
}
option.selected = !!matcher(optionValue, value);
};
while (i--) {
var _ret2 = _loop();
if (_ret2 === 'continue') continue;
}
};
SelectValueObserver.prototype.synchronizeValue = function synchronizeValue() {
var _this3 = this;
var options = this.element.options,
count = 0,
value = [];
for (var i = 0, ii = options.length; i < ii; i++) {
var option = options.item(i);
if (!option.selected) {
continue;
}
value.push(option.hasOwnProperty('model') ? option.model : option.value);
count++;
}
if (this.element.multiple) {
if (Array.isArray(this.value)) {
var _ret3 = (function () {
var matcher = _this3.element.matcher || function (a, b) {
return a === b;
};
var i = 0;
var _loop2 = function () {
var a = _this3.value[i];
if (value.findIndex(function (b) {
return matcher(a, b);
}) === -1) {
_this3.value.splice(i, 1);
} else {
i++;
}
};
while (i < _this3.value.length) {
_loop2();
}
i = 0;
var _loop3 = function () {
var a = value[i];
if (_this3.value.findIndex(function (b) {
return matcher(a, b);
}) === -1) {
_this3.value.push(a);
}
i++;
};
while (i < value.length) {
_loop3();
}
return {
v: undefined
};
})();
if (typeof _ret3 === 'object') return _ret3.v;
}
} else {
if (count === 0) {
value = null;
} else {
value = value[0];
}
}
if (value !== this.value) {
this.oldValue = this.value;
this.value = value;
this.notify();
}
};
SelectValueObserver.prototype.notify = function notify() {
var oldValue = this.oldValue;
var newValue = this.value;
this.callSubscribers(newValue, oldValue);
};
SelectValueObserver.prototype.subscribe = function subscribe(context, callable) {
if (!this.hasSubscribers()) {
this.disposeHandler = this.handler.subscribe(this.element, this.synchronizeValue.bind(this, false));
}
this.addSubscriber(context, callable);
};
SelectValueObserver.prototype.unsubscribe = function unsubscribe(context, callable) {
if (this.removeSubscriber(context, callable) && !this.hasSubscribers()) {
this.disposeHandler();
this.disposeHandler = null;
}
};
SelectValueObserver.prototype.bind = function bind() {
var _this4 = this;
this.domObserver = _aureliaPal.DOM.createMutationObserver(function () {
_this4.synchronizeOptions();
_this4.synchronizeValue();
});
this.domObserver.observe(this.element, { childList: true, subtree: true });
};
SelectValueObserver.prototype.unbind = function unbind() {
this.domObserver.disconnect();
this.domObserver = null;
if (this.arrayObserver) {
this.arrayObserver.unsubscribe(selectArrayContext, this);
this.arrayObserver = null;
}
};
var _SelectValueObserver = SelectValueObserver;
SelectValueObserver = subscriberCollection()(SelectValueObserver) || SelectValueObserver;
return SelectValueObserver;
})();
exports.SelectValueObserver = SelectValueObserver;
var ClassObserver = (function () {
function ClassObserver(element) {
_classCallCheck(this, ClassObserver);
this.element = element;
this.doNotCache = true;
this.value = '';
this.version = 0;
}
ClassObserver.prototype.getValue = function getValue() {
return this.value;
};
ClassObserver.prototype.setValue = function setValue(newValue) {
var nameIndex = this.nameIndex || {},
version = this.version,
names,
name;
if (newValue !== null && newValue !== undefined && newValue.length) {
names = newValue.split(/\s+/);
for (var i = 0, _length2 = names.length; i < _length2; i++) {
name = names[i];
if (name === '') {
continue;
}
nameIndex[name] = version;
this.element.classList.add(name);
}
}
this.value = newValue;
this.nameIndex = nameIndex;
this.version += 1;
if (version === 0) {
return;
}
version -= 1;
for (name in nameIndex) {
if (!nameIndex.hasOwnProperty(name) || nameIndex[name] !== version) {
continue;
}
this.element.classList.remove(name);
}
};
ClassObserver.prototype.subscribe = function subscribe() {
throw new Error('Observation of a "' + this.element.nodeName + '" element\'s "class" property is not supported.');
};
return ClassObserver;
})();
exports.ClassObserver = ClassObserver;
var computedContext = 'ComputedPropertyObserver';
var ComputedPropertyObserver = (function () {
function ComputedPropertyObserver(obj, propertyName, descriptor, observerLocator) {
_classCallCheck(this, _ComputedPropertyObserver);
this.obj = obj;
this.propertyName = propertyName;
this.descriptor = descriptor;
this.observerLocator = observerLocator;
}
ComputedPropertyObserver.prototype.getValue = function getValue() {
return this.obj[this.propertyName];
};
ComputedPropertyObserver.prototype.setValue = function setValue(newValue) {
this.obj[this.propertyName] = newValue;
};
ComputedPropertyObserver.prototype.call = function call(context) {
var newValue = this.getValue();
if (this.oldValue === newValue) return;
this.callSubscribers(newValue, this.oldValue);
this.oldValue = newValue;
return;
};
ComputedPropertyObserver.prototype.subscribe = function subscribe(context, callable) {
if (!this.hasSubscribers()) {
this.oldValue = this.getValue();
var dependencies = this.descriptor.get.dependencies;
this.observers = [];
for (var i = 0, ii = dependencies.length; i < ii; i++) {
var observer = this.observerLocator.getObserver(this.obj, dependencies[i]);
this.observers.push(observer);
observer.subscribe(computedContext, this);
}
}
this.addSubscriber(context, callable);
};
ComputedPropertyObserver.prototype.unsubscribe = function unsubscribe(context, callable) {
if (this.removeSubscriber(context, callable) && !this.hasSubscribers()) {
this.oldValue = undefined;
var i = this.observers.length;
while (i--) {
this.observers[i].unsubscribe(computedContext, this);
}
this.observers = null;
}
};
var _ComputedPropertyObserver = ComputedPropertyObserver;
ComputedPropertyObserver = subscriberCollection()(ComputedPropertyObserver) || ComputedPropertyObserver;
return ComputedPropertyObserver;
})();
exports.ComputedPropertyObserver = ComputedPropertyObserver;
function hasDeclaredDependencies(descriptor) {
return descriptor && descriptor.get && descriptor.get.dependencies && descriptor.get.dependencies.length > 0;
}
function declarePropertyDependencies(ctor, propertyName, dependencies) {
var descriptor = Object.getOwnPropertyDescriptor(ctor.prototype, propertyName);
descriptor.get.dependencies = dependencies;
}
function computedFrom() {
for (var _len = arguments.length, rest = Array(_len), _key = 0; _key < _len; _key++) {
rest[_key] = arguments[_key];
}
return function (target, key, descriptor) {
descriptor.get.dependencies = rest;
return descriptor;
};
}
var elements = {
a: ['class', 'externalResourcesRequired', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'target', 'transform', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'],
altGlyph: ['class', 'dx', 'dy', 'externalResourcesRequired', 'format', 'glyphRef', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'rotate', 'style', 'systemLanguage', 'x', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space', 'y'],
altGlyphDef: ['id', 'xml:base', 'xml:lang', 'xml:space'],
altGlyphItem: ['id', 'xml:base', 'xml:lang', 'xml:space'],
animate: ['accumulate', 'additive', 'attributeName', 'attributeType', 'begin', 'by', 'calcMode', 'dur', 'end', 'externalResourcesRequired', 'fill', 'from', 'id', 'keySplines', 'keyTimes', 'max', 'min', 'onbegin', 'onend', 'onload', 'onrepeat', 'repeatCount', 'repeatDur', 'requiredExtensions', 'requiredFeatures', 'restart', 'systemLanguage', 'to', 'values', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'],
animateColor: ['accumulate', 'additive', 'attributeName', 'attributeType', 'begin', 'by', 'calcMode', 'dur', 'end', 'externalResourcesRequired', 'fill', 'from', 'id', 'keySplines', 'keyTimes', 'max', 'min', 'onbegin', 'onend', 'onload', 'onrepeat', 'repeatCount', 'repeatDur', 'requiredExtensions', 'requiredFeatures', 'restart', 'systemLanguage', 'to', 'values', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'],
animateMotion: ['accumulate', 'additive', 'begin', 'by', 'calcMode', 'dur', 'end', 'externalResourcesRequired', 'fill', 'from', 'id', 'keyPoints', 'keySplines', 'keyTimes', 'max', 'min', 'onbegin', 'onend', 'onload', 'onrepeat', 'origin', 'path', 'repeatCount', 'repeatDur', 'requiredExtensions', 'requiredFeatures', 'restart', 'rotate', 'systemLanguage', 'to', 'values', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'],
animateTransform: ['accumulate', 'additive', 'attributeName', 'attributeType', 'begin', 'by', 'calcMode', 'dur', 'end', 'externalResourcesRequired', 'fill', 'from', 'id', 'keySplines', 'keyTimes', 'max', 'min', 'onbegin', 'onend', 'onload', 'onrepeat', 'repeatCount', 'repeatDur', 'requiredExtensions', 'requiredFeatures', 'restart', 'systemLanguage', 'to', 'type', 'values', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'],
circle: ['class', 'cx', 'cy', 'externalResourcesRequired', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'r', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'xml:base', 'xml:lang', 'xml:space'],
clipPath: ['class', 'clipPathUnits', 'externalResourcesRequired', 'id', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'xml:base', 'xml:lang', 'xml:space'],
'color-profile': ['id', 'local', 'name', 'rendering-intent', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'],
cursor: ['externalResourcesRequired', 'id', 'requiredExtensions', 'requiredFeatures', 'systemLanguage', 'x', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space', 'y'],
defs: ['class', 'externalResourcesRequired', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'xml:base', 'xml:lang', 'xml:space'],
desc: ['class', 'id', 'style', 'xml:base', 'xml:lang', 'xml:space'],
ellipse: ['class', 'cx', 'cy', 'externalResourcesRequired', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'rx', 'ry', 'style', 'systemLanguage', 'transform', 'xml:base', 'xml:lang', 'xml:space'],
feBlend: ['class', 'height', 'id', 'in', 'in2', 'mode', 'result', 'style', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'],
feColorMatrix: ['class', 'height', 'id', 'in', 'result', 'style', 'type', 'values', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'],
feComponentTransfer: ['class', 'height', 'id', 'in', 'result', 'style', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'],
feComposite: ['class', 'height', 'id', 'in', 'in2', 'k1', 'k2', 'k3', 'k4', 'operator', 'result', 'style', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'],
feConvolveMatrix: ['bias', 'class', 'divisor', 'edgeMode', 'height', 'id', 'in', 'kernelMatrix', 'kernelUnitLength', 'order', 'preserveAlpha', 'result', 'style', 'targetX', 'targetY', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'],
feDiffuseLighting: ['class', 'diffuseConstant', 'height', 'id', 'in', 'kernelUnitLength', 'result', 'style', 'surfaceScale', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'],
feDisplacementMap: ['class', 'height', 'id', 'in', 'in2', 'result', 'scale', 'style', 'width', 'x', 'xChannelSelector', 'xml:base', 'xml:lang', 'xml:space', 'y', 'yChannelSelector'],
feDistantLight: ['azimuth', 'elevation', 'id', 'xml:base', 'xml:lang', 'xml:space'],
feFlood: ['class', 'height', 'id', 'result', 'style', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'],
feFuncA: ['amplitude', 'exponent', 'id', 'intercept', 'offset', 'slope', 'tableValues', 'type', 'xml:base', 'xml:lang', 'xml:space'],
feFuncB: ['amplitude', 'exponent', 'id', 'intercept', 'offset', 'slope', 'tableValues', 'type', 'xml:base', 'xml:lang', 'xml:space'],
feFuncG: ['amplitude', 'exponent', 'id', 'intercept', 'offset', 'slope', 'tableValues', 'type', 'xml:base', 'xml:lang', 'xml:space'],
feFuncR: ['amplitude', 'exponent', 'id', 'intercept', 'offset', 'slope', 'tableValues', 'type', 'xml:base', 'xml:lang', 'xml:space'],
feGaussianBlur: ['class', 'height', 'id', 'in', 'result', 'stdDeviation', 'style', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'],
feImage: ['class', 'externalResourcesRequired', 'height', 'id', 'preserveAspectRatio', 'result', 'style', 'width', 'x', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space', 'y'],
feMerge: ['class', 'height', 'id', 'result', 'style', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'],
feMergeNode: ['id', 'xml:base', 'xml:lang', 'xml:space'],
feMorphology: ['class', 'height', 'id', 'in', 'operator', 'radius', 'result', 'style', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'],
feOffset: ['class', 'dx', 'dy', 'height', 'id', 'in', 'result', 'style', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'],
fePointLight: ['id', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y', 'z'],
feSpecularLighting: ['class', 'height', 'id', 'in', 'kernelUnitLength', 'result', 'specularConstant', 'specularExponent', 'style', 'surfaceScale', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'],
feSpotLight: ['id', 'limitingConeAngle', 'pointsAtX', 'pointsAtY', 'pointsAtZ', 'specularExponent', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y', 'z'],
feTile: ['class', 'height', 'id', 'in', 'result', 'style', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'],
feTurbulence: ['baseFrequency', 'class', 'height', 'id', 'numOctaves', 'result', 'seed', 'stitchTiles', 'style', 'type', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'],
filter: ['class', 'externalResourcesRequired', 'filterRes', 'filterUnits', 'height', 'id', 'primitiveUnits', 'style', 'width', 'x', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space', 'y'],
font: ['class', 'externalResourcesRequired', 'horiz-adv-x', 'horiz-origin-x', 'horiz-origin-y', 'id', 'style', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'xml:base', 'xml:lang', 'xml:space'],
'font-face': ['accent-height', 'alphabetic', 'ascent', 'bbox', 'cap-height', 'descent', 'font-family', 'font-size', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'hanging', 'id', 'ideographic', 'mathematical', 'overline-position', 'overline-thickness', 'panose-1', 'slope', 'stemh', 'stemv', 'strikethrough-position', 'strikethrough-thickness', 'underline-position', 'underline-thickness', 'unicode-range', 'units-per-em', 'v-alphabetic', 'v-hanging', 'v-ideographic', 'v-mathematical', 'widths', 'x-height', 'xml:base', 'xml:lang', 'xml:space'],
'font-face-format': ['id', 'string', 'xml:base', 'xml:lang', 'xml:space'],
'font-face-name': ['id', 'name', 'xml:base', 'xml:lang', 'xml:space'],
'font-face-src': ['id', 'xml:base', 'xml:lang', 'xml:space'],
'font-face-uri': ['id', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'],
foreignObject: ['class', 'externalResourcesRequired', 'height', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'],
g: ['class', 'externalResourcesRequired', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'xml:base', 'xml:lang', 'xml:space'],
glyph: ['arabic-form', 'class', 'd', 'glyph-name', 'horiz-adv-x', 'id', 'lang', 'orientation', 'style', 'unicode', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'xml:base', 'xml:lang', 'xml:space'],
glyphRef: ['class', 'dx', 'dy', 'format', 'glyphRef', 'id', 'style', 'x', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space', 'y'],
hkern: ['g1', 'g2', 'id', 'k', 'u1', 'u2', 'xml:base', 'xml:lang', 'xml:space'],
image: ['class', 'externalResourcesRequired', 'height', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'preserveAspectRatio', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'width', 'x', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space', 'y'],
line: ['class', 'externalResourcesRequired', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'x1', 'x2', 'xml:base', 'xml:lang', 'xml:space', 'y1', 'y2'],
linearGradient: ['class', 'externalResourcesRequired', 'gradientTransform', 'gradientUnits', 'id', 'spreadMethod', 'style', 'x1', 'x2', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space', 'y1', 'y2'],
marker: ['class', 'externalResourcesRequired', 'id', 'markerHeight', 'markerUnits', 'markerWidth', 'orient', 'preserveAspectRatio', 'refX', 'refY', 'style', 'viewBox', 'xml:base', 'xml:lang', 'xml:space'],
mask: ['class', 'externalResourcesRequired', 'height', 'id', 'maskContentUnits', 'maskUnits', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'],
metadata: ['id', 'xml:base', 'xml:lang', 'xml:space'],
'missing-glyph': ['class', 'd', 'horiz-adv-x', 'id', 'style', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'xml:base', 'xml:lang', 'xml:space'],
mpath: ['externalResourcesRequired', 'id', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'],
path: ['class', 'd', 'externalResourcesRequired', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'pathLength', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'xml:base', 'xml:lang', 'xml:space'],
pattern: ['class', 'externalResourcesRequired', 'height', 'id', 'patternContentUnits', 'patternTransform', 'patternUnits', 'preserveAspectRatio', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'viewBox', 'width', 'x', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space', 'y'],
polygon: ['class', 'externalResourcesRequired', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'points', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'xml:base', 'xml:lang', 'xml:space'],
polyline: ['class', 'externalResourcesRequired', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'points', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'xml:base', 'xml:lang', 'xml:space'],
radialGradient: ['class', 'cx', 'cy', 'externalResourcesRequired', 'fx', 'fy', 'gradientTransform', 'gradientUnits', 'id', 'r', 'spreadMethod', 'style', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'],
rect: ['class', 'externalResourcesRequired', 'height', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'rx', 'ry', 'style', 'systemLanguage', 'transform', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'],
script: ['externalResourcesRequired', 'id', 'type', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'],
set: ['attributeName', 'attributeType', 'begin', 'dur', 'end', 'externalResourcesRequired', 'fill', 'id', 'max', 'min', 'onbegin', 'onend', 'onload', 'onrepeat', 'repeatCount', 'repeatDur', 'requiredExtensions', 'requiredFeatures', 'restart', 'systemLanguage', 'to', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'],
stop: ['class', 'id', 'offset', 'style', 'xml:base', 'xml:lang', 'xml:space'],
style: ['id', 'media', 'title', 'type', 'xml:base', 'xml:lang', 'xml:space'],
svg: ['baseProfile', 'class', 'contentScriptType', 'contentStyleType', 'externalResourcesRequired', 'height', 'id', 'onabort', 'onactivate', 'onclick', 'onerror', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onresize', 'onscroll', 'onunload', 'onzoom', 'preserveAspectRatio', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'version', 'viewBox', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y', 'zoomAndPan'],
'switch': ['class', 'externalResourcesRequired', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'xml:base', 'xml:lang', 'xml:space'],
symbol: ['class', 'externalResourcesRequired', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'preserveAspectRatio', 'style', 'viewBox', 'xml:base', 'xml:lang', 'xml:space'],
text: ['class', 'dx', 'dy', 'externalResourcesRequired', 'id', 'lengthAdjust', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'rotate', 'style', 'systemLanguage', 'textLength', 'transform', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'],
textPath: ['class', 'externalResourcesRequired', 'id', 'lengthAdjust', 'method', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'spacing', 'startOffset', 'style', 'systemLanguage', 'textLength', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'],
title: ['class', 'id', 'style', 'xml:base', 'xml:lang', 'xml:space'],
tref: ['class', 'dx', 'dy', 'externalResourcesRequired', 'id', 'lengthAdjust', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'rotate', 'style', 'systemLanguage', 'textLength', 'x', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space', 'y'],
tspan: ['class', 'dx', 'dy', 'externalResourcesRequired', 'id', 'lengthAdjust', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'rotate', 'style', 'systemLanguage', 'textLength', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'],
use: ['class', 'externalResourcesRequired', 'height', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'width', 'x', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space', 'y'],
view: ['externalResourcesRequired', 'id', 'preserveAspectRatio', 'viewBox', 'viewTarget', 'xml:base', 'xml:lang', 'xml:space', 'zoomAndPan'],
vkern: ['g1', 'g2', 'id', 'k', 'u1', 'u2', 'xml:base', 'xml:lang', 'xml:space']
};
exports.elements = elements;
var presentationElements = {
'a': true,
'altGlyph': true,
'animate': true,
'animateColor': true,
'circle': true,
'clipPath': true,
'defs': true,
'ellipse': true,
'feBlend': true,
'feColorMatrix': true,
'feComponentTransfer': true,
'feComposite': true,
'feConvolveMatrix': true,
'feDiffuseLighting': true,
'feDisplacementMap': true,
'feFlood': true,
'feGaussianBlur': true,
'feImage': true,
'feMerge': true,
'feMorphology': true,
'feOffset': true,
'feSpecularLighting': true,
'feTile': true,
'feTurbulence': true,
'filter': true,
'font': true,
'foreignObject': true,
'g': true,
'glyph': true,
'glyphRef': true,
'image': true,
'line': true,
'linearGradient': true,
'marker': true,
'mask': true,
'missing-glyph': true,
'path': true,
'pattern': true,
'polygon': true,
'polyline': true,
'radialGradient': true,
'rect': true,
'stop': true,
'svg': true,
'switch': true,
'symbol': true,
'text': true,
'textPath': true,
'tref': true,
'tspan': true,
'use': true
};
exports.presentationElements = presentationElements;
var presentationAttributes = {
'alignment-baseline': true,
'baseline-shift': true,
'clip-path': true,
'clip-rule': true,
'clip': true,
'color-interpolation-filters': true,
'color-interpolation': true,
'color-profile': true,
'color-rendering': true,
'color': true,
'cursor': true,
'direction': true,
'display': true,
'dominant-baseline': true,
'enable-background': true,
'fill-opacity': true,
'fill-rule': true,
'fill': true,
'filter': true,
'flood-color': true,
'flood-opacity': true,
'font-family': true,
'font-size-adjust': true,
'font-size': true,
'font-stretch': true,
'font-style': true,
'font-variant': true,
'font-weight': true,
'glyph-orientation-horizontal': true,
'glyph-orientation-vertical': true,
'image-rendering': true,
'kerning': true,
'letter-spacing': true,
'lighting-color': true,
'marker-end': true,
'marker-mid': true,
'marker-start': true,
'mask': true,
'opacity': true,
'overflow': true,
'pointer-events': true,
'shape-rendering': true,
'stop-color': true,
'stop-opacity': true,
'stroke-dasharray': true,
'stroke-dashoffset': true,
'stroke-linecap': true,
'stroke-linejoin': true,
'stroke-miterlimit': true,
'stroke-opacity': true,
'stroke-width': true,
'stroke': true,
'text-anchor': true,
'text-decoration': true,
'text-rendering': true,
'unicode-bidi': true,
'visibility': true,
'word-spacing': true,
'writing-mode': true
};
exports.presentationAttributes = presentationAttributes;
function createElement(html) {
var div = _aureliaPal.DOM.createElement('div');
div.innerHTML = html;
return div.firstChild;
}
var SVGAnalyzer = (function () {
function SVGAnalyzer() {
_classCallCheck(this, SVGAnalyzer);
if (createElement('<svg><altGlyph /></svg>').firstElementChild.nodeName === 'altglyph' && elements.altGlyph) {
elements.altglyph = elements.altGlyph;
delete elements.altGlyph;
elements.altglyphdef = elements.altGlyphDef;
delete elements.altGlyphDef;
elements.altglyphitem = elements.altGlyphItem;
delete elements.altGlyphItem;
elements.glyphref = elements.glyphRef;
delete elements.glyphRef;
}
}
SVGAnalyzer.prototype.isStandardSvgAttribute = function isStandardSvgAttribute(nodeName, attributeName) {
return presentationElements[nodeName] && presentationAttributes[attributeName] || elements[nodeName] && elements[nodeName].indexOf(attributeName) !== -1;
};
return SVGAnalyzer;
})();
exports.SVGAnalyzer = SVGAnalyzer;
var ObserverLocator = (function () {
_createClass(ObserverLocator, null, [{
key: 'inject',
value: [_aureliaTaskQueue.TaskQueue, EventManager, DirtyChecker, SVGAnalyzer],
enumerable: true
}]);
function ObserverLocator(taskQueue, eventManager, dirtyChecker, svgAnalyzer) {
_classCallCheck(this, ObserverLocator);
this.taskQueue = taskQueue;
this.eventManager = eventManager;
this.dirtyChecker = dirtyChecker;
this.svgAnalyzer = svgAnalyzer;
this.adapters = [];
}
ObserverLocator.prototype.getObserver = function getObserver(obj, propertyName) {
var observersLookup = obj.__observers__;
var observer = undefined;
if (observersLookup && propertyName in observersLookup) {
return observersLookup[propertyName];
}
observer = this.createPropertyObserver(obj, propertyName);
if (!observer.doNotCache) {
if (observersLookup === undefined) {
observersLookup = this.getOrCreateObserversLookup(obj);
}
observersLookup[propertyName] = observer;
}
return observer;
};
ObserverLocator.prototype.getOrCreateObserversLookup = function getOrCreateObserversLookup(obj) {
return obj.__observers__ || this.createObserversLookup(obj);
};
ObserverLocator.prototype.createObserversLookup = function createObserversLookup(obj) {
var value = {};
try {
Object.defineProperty(obj, "__observers__", {
enumerable: false,
configurable: false,
writable: false,
value: value
});
} catch (_) {}
return value;
};
ObserverLocator.prototype.addAdapter = function addAdapter(adapter) {
this.adapters.push(adapter);
};
ObserverLocator.prototype.getAdapterObserver = function getAdapterObserver(obj, propertyName, descriptor) {
for (var i = 0, ii = this.adapters.length; i < ii; i++) {
var adapter = this.adapters[i];
var observer = adapter.getObserver(obj, propertyName, descriptor);
if (observer) {
return observer;
}
}
return null;
};
ObserverLocator.prototype.createPropertyObserver = function createPropertyObserver(obj, propertyName) {
var observerLookup = undefined;
var descriptor = undefined;
var handler = undefined;
var xlinkResult = undefined;
if (!(obj instanceof Object)) {
return new PrimitiveObserver(obj, propertyName);
}
if (obj instanceof _aureliaPal.DOM.Element) {
if (propertyName === 'class') {
return new ClassObserver(obj);
}
if (propertyName === 'style' || propertyName === 'css') {
return new StyleObserver(obj, propertyName);
}
handler = this.eventManager.getElementHandler(obj, propertyName);
if (propertyName === 'value' && obj.tagName.toLowerCase() === 'select') {
return new SelectValueObserver(obj, handler, this);
}
if (propertyName === 'checked' && obj.tagName.toLowerCase() === 'input') {
return new CheckedObserver(obj, handler, this);
}
if (handler) {
return new ValueAttributeObserver(obj, propertyName, handler);
}
xlinkResult = /^xlink:(.+)$/.exec(propertyName);
if (xlinkResult) {
return new XLinkAttributeObserver(obj, propertyName, xlinkResult[1]);
}
if (/^\w+:|^data-|^aria-/.test(propertyName) || obj instanceof _aureliaPal.DOM.SVGElement && this.svgAnalyzer.isStandardSvgAttribute(obj.nodeName, propertyName)) {
return new DataAttributeObserver(obj, propertyName);
}
}
descriptor = Object.getPropertyDescriptor(obj, propertyName);
if (hasDeclaredDependencies(descriptor)) {
return new ComputedPropertyObserver(obj, propertyName, descriptor, this);
}
var existingGetterOrSetter = undefined;
if (descriptor && (existingGetterOrSetter = descriptor.get || descriptor.set)) {
if (existingGetterOrSetter.getObserver) {
return existingGetterOrSetter.getObserver(obj);
}
var adapterObserver = this.getAdapterObserver(obj, propertyName, descriptor);
if (adapterObserver) {
return adapterObserver;
}
return new DirtyCheckProperty(this.dirtyChecker, obj, propertyName);
}
if (obj instanceof Array) {
if (propertyName === 'length') {
return this.getArrayObserver(obj).getLengthObserver();
} else {
return new DirtyCheckProperty(this.dirtyChecker, obj, propertyName);
}
} else if (obj instanceof Map) {
if (propertyName === 'size') {
return this.getMapObserver(obj).getLengthObserver();
} else {
return new DirtyCheckProperty(this.dirtyChecker, obj, propertyName);
}
} else if (obj instanceof Set) {
if (propertyName === 'size') {
return this.getSetObserver(obj).getLengthObserver();
} else {
return new DirtyCheckProperty(this.dirtyChecker, obj, propertyName);
}
}
return new SetterObserver(this.taskQueue, obj, propertyName);
};
ObserverLocator.prototype.getAccessor = function getAccessor(obj, propertyName) {
if (obj instanceof _aureliaPal.DOM.Element) {
if (propertyName === 'class' || propertyName === 'style' || propertyName === 'css' || propertyName === 'value' && (obj.tagName.toLowerCase() === 'input' || obj.tagName.toLowerCase() === 'select') || propertyName === 'checked' && obj.tagName.toLowerCase() === 'input' || /^xlink:.+$/.exec(propertyName)) {
return this.getObserver(obj, propertyName);
}
if (/^\w+:|^data-|^aria-/.test(propertyName) || obj instanceof _aureliaPal.DOM.SVGElement && this.svgAnalyzer.isStandardSvgAttribute(obj.nodeName, propertyName)) {
return dataAttributeAccessor;
}
}
return propertyAccessor;
};
ObserverLocator.prototype.getArrayObserver = function getArrayObserver(array) {
return _getArrayObserver(this.taskQueue, array);
};
ObserverLocator.prototype.getMapObserver = function getMapObserver(map) {
return _getMapObserver(this.taskQueue, map);
};
ObserverLocator.prototype.getSetObserver = function getSetObserver(set) {
return _getSetObserver(this.taskQueue, set);
};
return ObserverLocator;
})();
exports.ObserverLocator = ObserverLocator;
var ObjectObservationAdapter = (function () {
function ObjectObservationAdapter() {
_classCallCheck(this, ObjectObservationAdapter);
}
ObjectObservationAdapter.prototype.getObserver = function getObserver(object, propertyName, descriptor) {
throw new Error('BindingAdapters must implement getObserver(object, propertyName).');
};
return ObjectObservationAdapter;
})();
exports.ObjectObservationAdapter = ObjectObservationAdapter;
var BindingExpression = (function () {
function BindingExpression(observerLocator, targetProperty, sourceExpression, mode, lookupFunctions, attribute) {
_classCallCheck(this, BindingExpression);
this.observerLocator = observerLocator;
this.targetProperty = targetProperty;
this.sourceExpression = sourceExpression;
this.mode = mode;
this.lookupFunctions = lookupFunctions;
this.attribute = attribute;
this.discrete = false;
}
BindingExpression.prototype.createBinding = function createBinding(target) {
return new Binding(this.observerLocator, this.sourceExpression, target, this.targetProperty, this.mode, this.lookupFunctions);
};
return BindingExpression;
})();
exports.BindingExpression = BindingExpression;
var targetContext = 'Binding:target';
var Binding = (function () {
function Binding(observerLocator, sourceExpression, target, targetProperty, mode, lookupFunctions) {
_classCallCheck(this, _Binding);
this.observerLocator = observerLocator;
this.sourceExpression = sourceExpression;
this.target = target;
this.targetProperty = targetProperty;
this.mode = mode;
this.lookupFunctions = lookupFunctions;
}
Binding.prototype.updateTarget = function updateTarget(value) {
this.targetObserver.setValue(value, this.target, this.targetProperty);
};
Binding.prototype.updateSource = function updateSource(value) {
this.sourceExpression.assign(this.source, value, this.lookupFunctions);
};
Binding.prototype.call = function call(context, newValue, oldValue) {
if (!this.isBound) {
return;
}
if (context === sourceContext) {
oldValue = this.targetObserver.getValue(this.target, this.targetProperty);
newValue = this.sourceExpression.evaluate(this.source, this.lookupFunctions);
if (newValue !== oldValue) {
this.updateTarget(newValue);
}
if (this.mode !== bindingMode.oneTime) {
this._version++;
this.sourceExpression.connect(this, this.source);
this.unobserve(false);
}
return;
}
if (context === targetContext) {
if (newValue !== this.sourceExpression.evaluate(this.source, this.lookupFunctions)) {
this.updateSource(newValue);
}
return;
}
throw new Error('Unexpected call context ' + context);
};
Binding.prototype.bind = function bind(source) {
if (this.isBound) {
if (this.source === source) {
return;
}
this.unbind();
}
this.isBound = true;
this.source = source;
var sourceExpression = this.sourceExpression;
if (sourceExpression.bind) {
sourceExpression.bind(this, source, this.lookupFunctions);
}
var mode = this.mode;
if (!this.targetObserver) {
var method = mode === bindingMode.twoWay ? 'getObserver' : 'getAccessor';
this.targetObserver = this.observerLocator[method](this.target, this.targetProperty);
}
if ('bind' in this.targetObserver) {
this.targetObserver.bind();
}
var value = sourceExpression.evaluate(source, this.lookupFunctions);
this.updateTarget(value);
if (mode === bindingMode.oneWay) {
enqueueBindingConnect(this);
} else if (mode === bindingMode.twoWay) {
sourceExpression.connect(this, source);
this.targetObserver.subscribe(targetContext, this);
}
};
Binding.prototype.unbind = function unbind() {
if (!this.isBound) {
return;
}
this.isBound = false;
if (this.sourceExpression.unbind) {
this.sourceExpression.unbind(this, this.source);
}
this.source = null;
if ('unbind' in this.targetObserver) {
this.targetObserver.unbind();
}
if (this.targetObserver.unsubscribe) {
this.targetObserver.unsubscribe(targetContext, this);
}
this.unobserve(true);
};
Binding.prototype.connect = function connect(evaluate) {
if (!this.isBound) {
return;
}
if (evaluate) {
var value = this.sourceExpression.evaluate(this.source, this.lookupFunctions);
this.updateTarget(value);
}
this.sourceExpression.connect(this, this.source);
};
var _Binding = Binding;
Binding = connectable()(Binding) || Binding;
return Binding;
})();
exports.Binding = Binding;
var CallExpression = (function () {
function CallExpression(observerLocator, targetProperty, sourceExpression, lookupFunctions) {
_classCallCheck(this, CallExpression);
this.observerLocator = observerLocator;
this.targetProperty = targetProperty;
this.sourceExpression = sourceExpression;
this.lookupFunctions = lookupFunctions;
}
CallExpression.prototype.createBinding = function createBinding(target) {
return new Call(this.observerLocator, this.sourceExpression, target, this.targetProperty, this.lookupFunctions);
};
return CallExpression;
})();
exports.CallExpression = CallExpression;
var Call = (function () {
function Call(observerLocator, sourceExpression, target, targetProperty, lookupFunctions) {
_classCallCheck(this, Call);
this.sourceExpression = sourceExpression;
this.target = target;
this.targetProperty = observerLocator.getObserver(target, targetProperty);
this.lookupFunctions = lookupFunctions;
}
Call.prototype.callSource = function callSource($event) {
var overrideContext = this.source.overrideContext;
Object.assign(overrideContext, $event);
overrideContext.$event = $event;
var mustEvaluate = true;
var result = this.sourceExpression.evaluate(this.source, this.lookupFunctions, mustEvaluate);
delete overrideContext.$event;
for (var prop in $event) {
delete overrideContext[prop];
}
return result;
};
Call.prototype.bind = function bind(source) {
var _this5 = this;
if (this.isBound) {
if (this.source === source) {
return;
}
this.unbind();
}
this.isBound = true;
this.source = source;
var sourceExpression = this.sourceExpression;
if (sourceExpression.bind) {
sourceExpression.bind(this, source, this.lookupFunctions);
}
this.targetProperty.setValue(function ($event) {
return _this5.callSource($event);
});
};
Call.prototype.unbind = function unbind() {
if (!this.isBound) {
return;
}
this.isBound = false;
if (this.sourceExpression.unbind) {
this.sourceExpression.unbind(this, this.source);
}
this.source = null;
this.targetProperty.setValue(null);
};
return Call;
})();
exports.Call = Call;
var ValueConverterResource = (function () {
function ValueConverterResource(name) {
_classCallCheck(this, ValueConverterResource);
this.name = name;
}
ValueConverterResource.convention = function convention(name) {
if (name.endsWith('ValueConverter')) {
return new ValueConverterResource(camelCase(name.substring(0, name.length - 14)));
}
};
ValueConverterResource.prototype.initialize = function initialize(container, target) {
this.instance = container.get(target);
};
ValueConverterResource.prototype.register = function register(registry, name) {
registry.registerValueConverter(name || this.name, this.instance);
};
ValueConverterResource.prototype.load = function load(container, target) {};
return ValueConverterResource;
})();
exports.ValueConverterResource = ValueConverterResource;
function valueConverter(nameOrTarget) {
if (nameOrTarget === undefined || typeof nameOrTarget === 'string') {
return function (target) {
_aureliaMetadata.metadata.define(_aureliaMetadata.metadata.resource, new ValueConverterResource(nameOrTarget), target);
};
}
_aureliaMetadata.metadata.define(_aureliaMetadata.metadata.resource, new ValueConverterResource(), nameOrTarget);
}
var BindingBehaviorResource = (function () {
function BindingBehaviorResource(name) {
_classCallCheck(this, BindingBehaviorResource);
this.name = name;
}
BindingBehaviorResource.convention = function convention(name) {
if (name.endsWith('BindingBehavior')) {
return new BindingBehaviorResource(camelCase(name.substring(0, name.length - 15)));
}
};
BindingBehaviorResource.prototype.initialize = function initialize(container, target) {
this.instance = container.get(target);
};
BindingBehaviorResource.prototype.register = function register(registry, name) {
registry.registerBindingBehavior(name || this.name, this.instance);
};
BindingBehaviorResource.prototype.load = function load(container, target) {};
return BindingBehaviorResource;
})();
exports.BindingBehaviorResource = BindingBehaviorResource;
function bindingBehavior(nameOrTarget) {
if (nameOrTarget === undefined || typeof nameOrTarget === 'string') {
return function (target) {
_aureliaMetadata.metadata.define(_aureliaMetadata.metadata.resource, new BindingBehaviorResource(nameOrTarget), target);
};
}
_aureliaMetadata.metadata.define(_aureliaMetadata.metadata.resource, new BindingBehaviorResource(), nameOrTarget);
}
var ListenerExpression = (function () {
function ListenerExpression(eventManager, targetEvent, sourceExpression, delegate, preventDefault, lookupFunctions) {
_classCallCheck(this, ListenerExpression);
this.eventManager = eventManager;
this.targetEvent = targetEvent;
this.sourceExpression = sourceExpression;
this.delegate = delegate;
this.discrete = true;
this.preventDefault = preventDefault;
this.lookupFunctions = lookupFunctions;
}
ListenerExpression.prototype.createBinding = function createBinding(target) {
return new Listener(this.eventManager, this.targetEvent, this.delegate, this.sourceExpression, target, this.preventDefault, this.lookupFunctions);
};
return ListenerExpression;
})();
exports.ListenerExpression = ListenerExpression;
var Listener = (function () {
function Listener(eventManager, targetEvent, delegate, sourceExpression, target, preventDefault, lookupFunctions) {
_classCallCheck(this, Listener);
this.eventManager = eventManager;
this.targetEvent = targetEvent;
this.delegate = delegate;
this.sourceExpression = sourceExpression;
this.target = target;
this.preventDefault = preventDefault;
this.lookupFunctions = lookupFunctions;
}
Listener.prototype.callSource = function callSource(event) {
var overrideContext = this.source.overrideContext;
overrideContext.$event = event;
var mustEvaluate = true;
var result = this.sourceExpression.evaluate(this.source, this.lookupFunctions, mustEvaluate);
delete overrideContext.$event;
if (result !== true && this.preventDefault) {
event.preventDefault();
}
return result;
};
Listener.prototype.bind = function bind(source) {
var _this6 = this;
if (this.isBound) {
if (this.source === source) {
return;
}
this.unbind();
}
this.isBound = true;
this.source = source;
var sourceExpression = this.sourceExpression;
if (sourceExpression.bind) {
sourceExpression.bind(this, source, this.lookupFunctions);
}
this._disposeListener = this.eventManager.addEventListener(this.target, this.targetEvent, function (event) {
return _this6.callSource(event);
}, this.delegate);
};
Listener.prototype.unbind = function unbind() {
if (!this.isBound) {
return;
}
this.isBound = false;
if (this.sourceExpression.unbind) {
this.sourceExpression.unbind(this, this.source);
}
this.source = null;
this._disposeListener();
this._disposeListener = null;
};
return Listener;
})();
exports.Listener = Listener;
function getAU(element) {
var au = element.au;
if (au === undefined) {
throw new Error('No Aurelia APIs are defined for the referenced element.');
}
return au;
}
var NameExpression = (function () {
function NameExpression(sourceExpression, apiName) {
_classCallCheck(this, NameExpression);
this.sourceExpression = sourceExpression;
this.apiName = apiName;
this.discrete = true;
}
NameExpression.prototype.createBinding = function createBinding(target) {
return new NameBinder(this.sourceExpression, NameExpression.locateAPI(target, this.apiName));
};
NameExpression.locateAPI = function locateAPI(element, apiName) {
switch (apiName) {
case 'element':
return element;
case 'controller':
return getAU(element).controller;
case 'view-model':
return getAU(element).controller.viewModel;
case 'view':
return getAU(element).controller.view;
default:
var target = getAU(element)[apiName];
if (target === undefined) {
throw new Error('Attempted to reference "' + apiName + '", but it was not found amongst the target\'s API.');
}
return target.viewModel;
}
};
return NameExpression;
})();
exports.NameExpression = NameExpression;
var NameBinder = (function () {
function NameBinder(sourceExpression, target) {
_classCallCheck(this, NameBinder);
this.sourceExpression = sourceExpression;
this.target = target;
}
NameBinder.prototype.bind = function bind(source) {
if (this.isBound) {
if (this.source === source) {
return;
}
this.unbind();
}
this.isBound = true;
this.source = source;
this.sourceExpression.assign(this.source, this.target);
};
NameBinder.prototype.unbind = function unbind() {
if (!this.isBound) {
return;
}
this.isBound = false;
this.sourceExpression.assign(this.source, null);
this.source = null;
};
return NameBinder;
})();
var lookupFunctions = {
bindingBehaviors: function bindingBehaviors(name) {
return null;
},
valueConverters: function valueConverters(name) {
return null;
}
};
var BindingEngine = (function () {
_createClass(BindingEngine, null, [{
key: 'inject',
value: [ObserverLocator, Parser],
enumerable: true
}]);
function BindingEngine(observerLocator, parser) {
_classCallCheck(this, BindingEngine);
this.observerLocator = observerLocator;
this.parser = parser;
}
BindingEngine.prototype.createBindingExpression = function createBindingExpression(targetProperty, sourceExpression) {
var mode = arguments.length <= 2 || arguments[2] === undefined ? bindingMode.oneWay : arguments[2];
var lookupFunctions = arguments.length <= 3 || arguments[3] === undefined ? lookupFunctions : arguments[3];
return (function () {
return new BindingExpression(this.observerLocator, targetProperty, this.parser.parse(sourceExpression), mode, lookupFunctions);
}).apply(this, arguments);
};
BindingEngine.prototype.propertyObserver = function propertyObserver(obj, propertyName) {
var _this7 = this;
return {
subscribe: function subscribe(callback) {
var observer = _this7.observerLocator.getObserver(obj, propertyName);
observer.subscribe(callback);
return {
dispose: function dispose() {
return observer.unsubscribe(callback);
}
};
}
};
};
BindingEngine.prototype.collectionObserver = function collectionObserver(collection) {
var _this8 = this;
return {
subscribe: function subscribe(callback) {
var observer = undefined;
if (collection instanceof Array) {
observer = _this8.observerLocator.getArrayObserver(collection);
} else if (collection instanceof Map) {
observer = _this8.observerLocator.getMapObserver(collection);
} else if (collection instanceof Set) {
observer = _this8.observerLocator.getSetObserver(collection);
} else {
throw new Error('collection must be an instance of Array, Map or Set.');
}
observer.subscribe(callback);
return {
dispose: function dispose() {
return observer.unsubscribe(callback);
}
};
}
};
};
BindingEngine.prototype.expressionObserver = function expressionObserver(bindingContext, expression) {
var scope = { bindingContext: bindingContext, overrideContext: createOverrideContext(bindingContext) };
return new ExpressionObserver(scope, this.parser.parse(expression), this.observerLocator);
};
BindingEngine.prototype.parseExpression = function parseExpression(expression) {
return this.parser.parse(expression);
};
BindingEngine.prototype.registerAdapter = function registerAdapter(adapter) {
this.observerLocator.addAdapter(adapter);
};
return BindingEngine;
})();
exports.BindingEngine = BindingEngine;
var ExpressionObserver = (function () {
function ExpressionObserver(scope, expression, observerLocator) {
_classCallCheck(this, _ExpressionObserver);
this.scope = scope;
this.expression = expression;
this.observerLocator = observerLocator;
}
ExpressionObserver.prototype.subscribe = function subscribe(callback) {
var _this9 = this;
if (!this.hasSubscribers()) {
this.oldValue = this.expression.evaluate(this.scope, lookupFunctions);
this.expression.connect(this, this.scope);
}
this.addSubscriber(callback);
return {
dispose: function dispose() {
if (_this9.removeSubscriber(callback) && !_this9.hasSubscribers()) {
_this9.unobserve(true);
}
}
};
};
ExpressionObserver.prototype.call = function call() {
var newValue = this.expression.evaluate(this.scope, lookupFunctions);
var oldValue = this.oldValue;
if (newValue !== oldValue) {
this.oldValue = newValue;
this.callSubscribers(newValue, oldValue);
}
this._version++;
this.expression.connect(this, this.scope);
this.unobserve(false);
};
var _ExpressionObserver = ExpressionObserver;
ExpressionObserver = subscriberCollection()(ExpressionObserver) || ExpressionObserver;
ExpressionObserver = connectable()(ExpressionObserver) || ExpressionObserver;
return ExpressionObserver;
})();
var setProto = Set.prototype;
function _getSetObserver(taskQueue, set) {
return ModifySetObserver['for'](taskQueue, set);
}
var ModifySetObserver = (function (_ModifyCollectionObserver4) {
_inherits(ModifySetObserver, _ModifyCollectionObserver4);
function ModifySetObserver(taskQueue, set) {
_classCallCheck(this, ModifySetObserver);
_ModifyCollectionObserver4.call(this, taskQueue, set);
}
ModifySetObserver['for'] = function _for(taskQueue, set) {
if (!('__set_observer__' in set)) {
var observer = ModifySetObserver.create(taskQueue, set);
Object.defineProperty(set, '__set_observer__', { value: observer, enumerable: false, configurable: false });
}
return set.__set_observer__;
};
ModifySetObserver.create = function create(taskQueue, set) {
var observer = new ModifySetObserver(taskQueue, set);
var proto = setProto;
if (proto.add !== set.add || proto['delete'] !== set['delete'] || proto.clear !== set.clear) {
proto = {
add: set.add,
'delete': set['delete'],
clear: set.clear
};
}
set['add'] = function () {
var type = 'add';
var oldSize = set.size;
var methodCallResult = proto['add'].apply(set, arguments);
var hasValue = set.size === oldSize;
if (!hasValue) {
observer.addChangeRecord({
type: type,
object: set,
value: Array.from(set).pop()
});
}
return methodCallResult;
};
set['delete'] = function () {
var hasValue = set.has(arguments[0]);
var methodCallResult = proto['delete'].apply(set, arguments);
if (hasValue) {
observer.addChangeRecord({
type: 'delete',
object: set,
value: arguments[0]
});
}
return methodCallResult;
};
set['clear'] = function () {
var methodCallResult = proto['clear'].apply(set, arguments);
observer.addChangeRecord({
type: 'clear',
object: set
});
return methodCallResult;
};
return observer;
};
return ModifySetObserver;
})(ModifyCollectionObserver);
function observable(targetOrConfig, key, descriptor) {
var deco = function deco(target, key2, descriptor2) {
var innerPropertyName = '_' + key2;
var callbackName = targetOrConfig && targetOrConfig.changeHandler || key2 + 'Changed';
var babel = descriptor2 !== undefined;
if (babel) {
if (typeof descriptor2.initializer === 'function') {
target[innerPropertyName] = descriptor2.initializer();
}
} else {
descriptor2 = {};
}
delete descriptor2.writable;
delete descriptor2.initializer;
descriptor2.get = function () {
return this[innerPropertyName];
};
descriptor2.set = function (newValue) {
var oldValue = this[innerPropertyName];
this[innerPropertyName] = newValue;
if (this[callbackName]) {
this[callbackName](newValue, oldValue);
}
};
descriptor2.get.dependencies = [innerPropertyName];
if (!babel) {
Object.defineProperty(target, key2, descriptor2);
}
};
if (key) {
var target = targetOrConfig;
targetOrConfig = null;
return deco(target, key, descriptor);
}
return deco;
}
}); | {
"content_hash": "83bd3fc2ce1fa16abb195e5abf78f145",
"timestamp": "",
"source": "github",
"line_count": 5236,
"max_line_length": 568,
"avg_line_length": 32.25935828877005,
"alnum_prop": 0.6141909892842342,
"repo_name": "bitfly-p2p/bitfly-client",
"id": "aa10771deb9cf654a61a47a22f001f393400276f",
"size": "168910",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "jspm_packages/npm/[email protected]/aurelia-binding.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "290515"
},
{
"name": "CoffeeScript",
"bytes": "2294"
},
{
"name": "HTML",
"bytes": "20454"
},
{
"name": "JavaScript",
"bytes": "6186431"
},
{
"name": "Makefile",
"bytes": "6126"
},
{
"name": "Python",
"bytes": "1435"
},
{
"name": "Shell",
"bytes": "3024"
}
],
"symlink_target": ""
} |
'use strict';
var utils = require('./utils');
function Task(queue, id, data, attempts) {
this._queue = queue;
this.id = id;
this.data = data;
this.attempts = attempts || 0;
}
/**
* The callback to run when a task is complete
* @param {Object} [err] - Any error that occured while processing task
* @param {Function} [callback] - A callback to run after saving finished task
*/
Task.prototype.done = function(err, callback) {
if(typeof err === 'function' && !callback) {
callback = err;
err = null;
}
var cb = utils.optCallback(callback),
self = this,
queue = this._queue,
result = err ? queue.keys.failed
: queue.keys.completed
;
if(err) {
queue.emit('fail', err, self);
if(self.attempts < queue._retries) {
self.attempts++;
queue._handler(self);
return;
}
}
queue.unlock(self.id);
queue._nbclient.multi()
.lpush(result, self.id)
.lrem(queue.keys.working, 0, self.id)
.exec(function (err, res) {
queue.dequeue(queue._handler);
if(!err && result === queue.keys.completed) {
queue.emit('complete', self);
}
cb(err, res);
});
};
module.exports = Task;
| {
"content_hash": "b472b46495156f2a2f07e7f5a1109f71",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 78,
"avg_line_length": 21.263157894736842,
"alnum_prop": 0.5899339933993399,
"repo_name": "jimgswang/RedisQueue",
"id": "b2dfae7b3ca3ffad68d13444afdd8997a1a99567",
"size": "1212",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/task.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "20811"
}
],
"symlink_target": ""
} |
from ciscoconfparse import CiscoConfParse
def parser():
parse = CiscoConfParse('parsefile.txt')
crypto = parse.find_objects(r'crypto map CRYPTO')
for i in crypto:
print i.text
for child in i.children:
print child.text
parser()
| {
"content_hash": "1ba3b503497cfab32cbb907f6344bc09",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 53,
"avg_line_length": 29.666666666666668,
"alnum_prop": 0.6629213483146067,
"repo_name": "thecableguy11492/pynet_practice",
"id": "f8517dd43f739ed7fabd19289cc28225e0a7d88d",
"size": "289",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "class1/exercise8.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "24100"
}
],
"symlink_target": ""
} |
./fetch-mean.sh > mean.dat
| {
"content_hash": "1bc84cb050353a2dcdd08ac18db379a5",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 26,
"avg_line_length": 27,
"alnum_prop": 0.6666666666666666,
"repo_name": "mkurnosov/tscbench",
"id": "8a5dcc85ee564cf9969eed60710995b11a12ff32",
"size": "38",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "experiments/graphs/build-all.sh",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "27494"
},
{
"name": "C++",
"bytes": "9826"
},
{
"name": "Shell",
"bytes": "22720"
}
],
"symlink_target": ""
} |
<?php
namespace Simgroep\ConcurrentSpiderBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;
/**
* This is the class that loads and manages your bundle configuration
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
*/
class SimgroepConcurrentSpiderExtension extends Extension
{
/**
* {@inheritdoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$container->setParameter('simgroep_concurrent_spider.maximum_resource_size', $config['maximum_resource_size']);
$container->setParameter('simgroep_concurrent_spider.http_user_agent', $config['http_user_agent']);
$container->setParameter('simgroep_concurrent_spider.rabbitmq.host', $config['rabbitmq']['host']);
$container->setParameter('simgroep_concurrent_spider.rabbitmq.port', $config['rabbitmq']['port']);
$container->setParameter('simgroep_concurrent_spider.rabbitmq.user', $config['rabbitmq']['user']);
$container->setParameter('simgroep_concurrent_spider.rabbitmq.password', $config['rabbitmq']['password']);
$container->setParameter('simgroep_concurrent_spider.queue.discoveredurls_queue', $config['queue']['discoveredurls_queue']);
$container->setParameter('simgroep_concurrent_spider.queue.indexer_queue', $config['queue']['indexer_queue']);
$container->setParameter('simgroep_concurrent_spider.solr.host', $config['solr']['host']);
$container->setParameter('simgroep_concurrent_spider.solr.port', $config['solr']['port']);
$container->setParameter('simgroep_concurrent_spider.solr.path', $config['solr']['path']);
$container->setParameter('simgroep_concurrent_spider.solr.proxy', $config['solr']['proxy']);
$container->setParameter('simgroep_concurrent_spider.logger_service', $config['logger_service']);
$container->setParameter('simgroep_concurrent_spider.mapping', $config['mapping']);
$container->setParameter('simgroep_concurrent_spider.css_blacklist', $config['css_blacklist']);
$loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.xml');
}
}
| {
"content_hash": "ae5bacf51ef2e9fa56e6457f4a1da7f0",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 132,
"avg_line_length": 57.34090909090909,
"alnum_prop": 0.7177962742766548,
"repo_name": "Breuls/concurrent-spider-bundle",
"id": "0d1629e67ec4190835a31de086fb753584d55fb0",
"size": "2523",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "DependencyInjection/SimgroepConcurrentSpiderExtension.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "204159"
},
{
"name": "Ruby",
"bytes": "943"
},
{
"name": "Shell",
"bytes": "769"
}
],
"symlink_target": ""
} |
<merge xmlns:android="http://schemas.android.com/apk/res/android" >
<ListView
android:id="@+id/lv_favorlilst"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@android:color/white"
android:isScrollContainer="false" />
<TextView
android:id="@+id/empty"
style="@style/noresult"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:text="@string/nofavor" />
</merge> | {
"content_hash": "b70637f144544e8abc782674f9028d51",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 67,
"avg_line_length": 31.77777777777778,
"alnum_prop": 0.6118881118881119,
"repo_name": "linghp/ZLFAsist",
"id": "3e0dfd748f86bb681dca800120911c74d4a3c70b",
"size": "572",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ZLFAssist/res/layout/activity_favor.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "56140"
},
{
"name": "Java",
"bytes": "1267443"
},
{
"name": "Makefile",
"bytes": "12611"
},
{
"name": "Shell",
"bytes": "30"
}
],
"symlink_target": ""
} |
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flowable.examples.runtime;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.flowable.common.engine.api.FlowableException;
import org.flowable.engine.impl.test.ResourceFlowableTestCase;
import org.flowable.engine.test.Deployment;
import org.junit.jupiter.api.Test;
/**
* This class shows an example of configurable agenda usage.
*/
public class WatchDogAgendaTest extends ResourceFlowableTestCase {
public WatchDogAgendaTest() {
super("org/flowable/examples/runtime/WatchDogAgendaTest.flowable.cfg.xml");
}
@Test
@Deployment(resources = "org/flowable/engine/test/api/oneTaskProcess.bpmn20.xml")
public void testWatchDogWithOneTaskProcess() {
this.runtimeService.startProcessInstanceByKey("oneTaskProcess");
org.flowable.task.api.Task task = this.taskService.createTaskQuery().singleResult();
this.taskService.complete(task.getId());
assertThat(this.runtimeService.createProcessInstanceQuery().count()).isZero();
}
@Test
@Deployment(resources = "org/flowable/examples/runtime/WatchDogAgendaTest-endlessloop.bpmn20.xml")
public void testWatchDogWithEndLessLoop() {
assertThatThrownBy(() -> this.runtimeService.startProcessInstanceByKey("endlessloop"))
.isInstanceOf(FlowableException.class)
.hasMessageContaining("WatchDog limit exceeded.");
}
} | {
"content_hash": "82fc8ebb18b0c77f26b1736d95e1675d",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 102,
"avg_line_length": 41.44897959183673,
"alnum_prop": 0.7493845396356474,
"repo_name": "dbmalkovsky/flowable-engine",
"id": "0ac6dab35a59927b43837c5ea72e5cd57bf11431",
"size": "2031",
"binary": false,
"copies": "3",
"ref": "refs/heads/main",
"path": "modules/flowable-engine/src/test/java/org/flowable/examples/runtime/WatchDogAgendaTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "166"
},
{
"name": "CSS",
"bytes": "673786"
},
{
"name": "Dockerfile",
"bytes": "477"
},
{
"name": "Groovy",
"bytes": "482"
},
{
"name": "HTML",
"bytes": "1201811"
},
{
"name": "Handlebars",
"bytes": "6004"
},
{
"name": "Java",
"bytes": "46660725"
},
{
"name": "JavaScript",
"bytes": "12668702"
},
{
"name": "Mustache",
"bytes": "2383"
},
{
"name": "PLSQL",
"bytes": "268970"
},
{
"name": "SQLPL",
"bytes": "238673"
},
{
"name": "Shell",
"bytes": "12773"
},
{
"name": "TSQL",
"bytes": "19452"
}
],
"symlink_target": ""
} |
Scalr.regPage('Scalr.ui.account2.environments.clouds.gce', function (loadParams, moduleParams) {
var params = moduleParams['params'];
var form = Ext.create('Ext.form.Panel', {
bodyCls: 'x-container-fieldset',
fieldDefaults: {
anchor: '100%',
labelWidth: 110
},
autoScroll: true,
items: [{
xtype: 'component',
cls: 'x-fieldset-subheader',
html: 'OAuth Service Account'
},{
xtype: 'hidden',
name: 'gce.is_enabled',
value: 'on'
},{
xtype: 'buttongroupfield',
margin: '0 0 12',
layout: 'hbox',
name: 'mode',
submitValue: false,
defaults: {
flex: 1
},
items: [{
text: 'Configure manually',
value: 'manual'
},{
text: 'Upload JSON key',
value: 'jsonkey'
}],
listeners: {
change: function(comp, value) {
var form = comp.up('form'), ct, fields;
form.suspendLayouts();
Ext.each(['manual', 'jsonkey'], function(v){
ct = form.down('#' + v);
ct.setVisible(value === v);
Ext.each(ct.query('[isFormField]'), function(field){
field.setDisabled(value !== v);
});
});
form.resumeLayouts(true);
}
}
},{
xtype: 'textfield',
fieldLabel: 'Project ID',
name: 'gce.project_id',
value: params['gce.project_id']
},{
xtype: 'container',
layout: 'anchor',
itemId: 'manual',
items: [{
xtype: 'textfield',
fieldLabel: 'Client ID',
name: 'gce.client_id',
value: params['gce.client_id']
},{
xtype: 'textfield',
fieldLabel: 'Email (Service account name)',
name: 'gce.service_account_name',
value: params['gce.service_account_name']
},{
xtype: 'filefield',
fieldLabel: 'Private key',
name: 'gce.key',
value: params['gce.key'],
listeners: {
//Bug: file button will not be disabled when filefield is hidden initially
afterrender: function(){
this.setDisabled(this.disabled);
}
}
}]
},{
xtype: 'container',
layout: 'anchor',
itemId: 'jsonkey',
items: [{
xtype: 'filefield',
fieldLabel: 'JSON key',
name: 'gce.json_key',
value: params['gce.json_key'],
listeners: {
//Bug: file button will not be disabled when filefield is hidden initially
afterrender: function(){
this.setDisabled(this.disabled);
}
}
}]
}]
});
form.getForm().findField('mode').setValue(params['gce.json_key'] ? 'jsonkey' : 'manual');
return form;
});
| {
"content_hash": "3ea59045e8784ba2803fad80c9e907f5",
"timestamp": "",
"source": "github",
"line_count": 101,
"max_line_length": 96,
"avg_line_length": 33.277227722772274,
"alnum_prop": 0.42308836655757215,
"repo_name": "kikov79/scalr",
"id": "586a6b9e04f8b23c05022e8888b887e7674eec3d",
"size": "3361",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "app/www/ui2/js/ui/account2/environments/clouds/gce.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "4249"
},
{
"name": "CSS",
"bytes": "86731"
},
{
"name": "Cucumber",
"bytes": "72478"
},
{
"name": "HTML",
"bytes": "2474225"
},
{
"name": "JavaScript",
"bytes": "16934089"
},
{
"name": "PHP",
"bytes": "20637716"
},
{
"name": "Python",
"bytes": "350030"
},
{
"name": "Ruby",
"bytes": "9397"
},
{
"name": "Shell",
"bytes": "17207"
},
{
"name": "Smarty",
"bytes": "2245"
},
{
"name": "XSLT",
"bytes": "29678"
}
],
"symlink_target": ""
} |
<?php
/*
Safe sample
input : Get a serialize string in POST and unserialize it
Uses a number_int_filter via filter_var function
construction : concatenation with simple quote
*/
/*Copyright 2015 Bertrand STIVALET
Permission is hereby granted, without written agreement or royalty fee, to
use, copy, modify, and distribute this software and its documentation for
any purpose, provided that the above copyright notice and the following
three paragraphs appear in all copies of this software.
IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT,
INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT
LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO
OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
MODIFICATIONS.*/
$string = $_POST['UserData'] ;
$tainted = unserialize($string);
$sanitized = filter_var($tainted, FILTER_SANITIZE_NUMBER_INT);
if (filter_var($sanitized, FILTER_VALIDATE_INT))
$tainted = $sanitized ;
else
$tainted = "" ;
$query = "//User[@id='". $tainted . "']";
$xml = simplexml_load_file("users.xml");//file load
echo "query : ". $query ."<br /><br />" ;
$res=$xml->xpath($query);//execution
print_r($res);
echo "<br />" ;
?> | {
"content_hash": "2cdb8afb8e628d9f4c81becd4600c4e9",
"timestamp": "",
"source": "github",
"line_count": 64,
"max_line_length": 75,
"avg_line_length": 23.921875,
"alnum_prop": 0.7393860222077073,
"repo_name": "stivalet/PHP-Vulnerability-test-suite",
"id": "36efe7c25d99f68588e0ebf3e39b4f7be04e44c7",
"size": "1531",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Injection/CWE_91/safe/CWE_91__unserialize__func_FILTER-CLEANING-number_int_filter__ID_test-concatenation_simple_quote.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "64184004"
}
],
"symlink_target": ""
} |
import React, {Component} from 'react';
import './AutomatedRuns.css';
import 'react-select/dist/react-select.css';
import { Modal, Button, Alert } from 'react-bootstrap';
import CodeMirror from 'react-codemirror';
import 'codemirror/lib/codemirror.css';
import 'codemirror/mode/python/python';
function DisplayError(props) {
return <Alert bsStyle='danger'>
{props.description['error_traceback'].join('').split("\n").map((i, index) => {
return <div key={index}>{i}</div>;
})}
</Alert>
}
export class DetailsModal extends Component {
render() {
const automatedRun = this.props.automatedRuns.find(el => el.id === this.props.moreDetailsId);
if (automatedRun === undefined) {
return null;
}
var options = {
lineNumbers: true,
indentUnit: 4,
readOnly: true
};
return (
<Modal
bsSize='lg'
show={this.props.moreDetailsId !== null}
onHide={this.props.onRequestClose}
>
<Modal.Header closeButton>
<Modal.Title>{'Details of Automated Run ID ' + automatedRun.id}</Modal.Title>
</Modal.Header>
<Modal.Body>
<b>Configuration Source</b>
<CodeMirror value={automatedRun.source}
options={options}/>
<b>{'Base Learner Type ID: '}</b>
{automatedRun.base_learner_origin_id}
<br/>
<b>{'Job ID: '}</b>
{automatedRun.job_id}
{(automatedRun.job_status === 'errored') &&
<DisplayError description={automatedRun.description} />}
</Modal.Body>
</Modal>
)
}
}
export class DeleteModal extends Component {
handleYesAndClose() {
this.props.handleYes();
this.props.onRequestClose();
}
render() {
return (
<Modal
show={this.props.isOpen}
onHide={this.props.onRequestClose}
>
<Modal.Header closeButton>
<Modal.Title>Delete Automated Run</Modal.Title>
</Modal.Header>
<Modal.Body>
<p>Are you sure you want to delete record of this automated run?</p>
<p><strong>This action is irreversible.</strong></p>
</Modal.Body>
<Modal.Footer>
<Button bsStyle='danger' onClick={() => this.handleYesAndClose()}>
Delete
</Button>
<Button onClick={this.props.onRequestClose}>Cancel</Button>
</Modal.Footer>
</Modal>
)
}
}
| {
"content_hash": "479579a893ab9cf32f8a23a093048a68",
"timestamp": "",
"source": "github",
"line_count": 87,
"max_line_length": 97,
"avg_line_length": 27.885057471264368,
"alnum_prop": 0.5886232481450948,
"repo_name": "reiinakano/xcessiv",
"id": "e28064b72d4c6396a91249b1d9d10a910a49666c",
"size": "2426",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "xcessiv/ui/src/AutomatedRuns/Modals.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "2343"
},
{
"name": "HTML",
"bytes": "1135"
},
{
"name": "JavaScript",
"bytes": "101476"
},
{
"name": "Python",
"bytes": "154422"
}
],
"symlink_target": ""
} |
from ducktape.mark.resource import cluster
from kafkatest.tests.kafka_test import KafkaTest
from kafkatest.services.streams import StreamsEosTestDriverService, StreamsEosTestJobRunnerService, StreamsEosTestVerifyRunnerService
import time
class StreamsEosTest(KafkaTest):
"""
Test of Kafka Streams exactly-once semantics
"""
def __init__(self, test_context):
super(StreamsEosTest, self).__init__(test_context, num_zk=1, num_brokers=3, topics={
'data' : { 'partitions': 5, 'replication-factor': 2 },
'echo' : { 'partitions': 5, 'replication-factor': 2 },
'min' : { 'partitions': 5, 'replication-factor': 2 },
'sum' : { 'partitions': 5, 'replication-factor': 2 }
})
self.driver = StreamsEosTestDriverService(test_context, self.kafka)
self.processor1 = StreamsEosTestJobRunnerService(test_context, self.kafka)
self.processor2 = StreamsEosTestJobRunnerService(test_context, self.kafka)
self.verifier = StreamsEosTestVerifyRunnerService(test_context, self.kafka)
@cluster(num_nodes=8)
def test_rebalance(self):
"""
Starts and stops two test clients a few times.
Ensure that all records are delivered exactly-once.
"""
self.driver.start()
self.processor1.start()
time.sleep(30)
self.processor2.start()
time.sleep(30)
self.processor1.stop()
time.sleep(30)
self.processor1.start()
time.sleep(30)
self.processor2.stop()
time.sleep(30)
self.driver.stop()
self.processor1.stop()
self.processor2.stop()
self.verifier.start()
self.verifier.wait()
self.verifier.node.account.ssh("grep ALL-RECORDS-DELIVERED %s" % self.verifier.STDOUT_FILE, allow_fail=False)
@cluster(num_nodes=8)
def test_failure_and_recovery(self):
"""
Starts two test clients, then abort (kill -9) and restart them a few times.
Ensure that all records are delivered exactly-once.
"""
self.driver.start()
self.processor1.start()
self.processor2.start()
time.sleep(30)
self.processor1.abortThenRestart()
time.sleep(30)
self.processor1.abortThenRestart()
time.sleep(30)
self.processor2.abortThenRestart()
time.sleep(30)
self.driver.stop()
self.processor1.stop()
self.processor2.stop()
self.verifier.start()
self.verifier.wait()
self.verifier.node.account.ssh("grep ALL-RECORDS-DELIVERED %s" % self.verifier.STDOUT_FILE, allow_fail=False)
| {
"content_hash": "89f9272d06d3c018e7db141c4febf75f",
"timestamp": "",
"source": "github",
"line_count": 90,
"max_line_length": 133,
"avg_line_length": 29.677777777777777,
"alnum_prop": 0.6330962186447023,
"repo_name": "YMCoding/kafka-0.11.0.0-src-with-comment",
"id": "305cde095777b888d5b55ddc3c14a05846c4bcb6",
"size": "3452",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "tests/kafkatest/tests/streams/streams_eos_test.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "27418"
},
{
"name": "HTML",
"bytes": "5443"
},
{
"name": "Java",
"bytes": "9699073"
},
{
"name": "Python",
"bytes": "569082"
},
{
"name": "Scala",
"bytes": "4696237"
},
{
"name": "Shell",
"bytes": "66776"
},
{
"name": "XSLT",
"bytes": "7116"
}
],
"symlink_target": ""
} |
require 'gemoji'
require 'magnet/markdown/filter'
class Magnet::Markdown::Filter::Emoji < HTML::Pipeline::Filter
def self.emojis
Emoji.all.map(&:aliases).flatten.sort
end
def self.regexp_pattern
@regexp_pattern ||= /:(?<name>#{ (emojis.map { |n| Regexp.escape(n) }).join('|') }):/xo
end
def self.img_tag
'<img class="emoji" alt=":%{name}:" title=":%{name}:" style="width: 1em; height: 1em;" align="absmiddle" src="%{src}">'
end
def call
doc.search('.//text()').each do |node|
content = node.text
next unless content.include?(':')
next if has_ancestor?(node, %w(pre code tt))
html = emojify(content)
next if html == content
node.replace(html)
end
doc
end
def validate
needs :emoji_root
end
def emojify(html)
html.gsub(self.class.regexp_pattern) do |_match|
name = Regexp.last_match['name']
self.class.img_tag % { name: name, src: src_url(name) }
end
end
def src_url(emoji_name)
File.join(context[:emoji_root], src_path(emoji_name))
end
def src_path(emoji_name)
if context[:emoji_path]
context[:emoji_path].sub(':filename', emoji_filename(emoji_name))
else
File.join('emoji', emoji_filename(emoji_name))
end
end
def emoji_filename(emoji_name)
Emoji.find_by_alias(emoji_name).image_filename
end
end
| {
"content_hash": "f05acd01446f92dc4fe143927cf0f4e4",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 123,
"avg_line_length": 24.672727272727272,
"alnum_prop": 0.6285924834193073,
"repo_name": "magnet-inc/magnet-markdown",
"id": "d9b6a7532888c1f35ac3bfe78eef8054f1115e83",
"size": "1357",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/magnet/markdown/filter/emoji.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "8190"
}
],
"symlink_target": ""
} |
package helpers
import (
"io/ioutil"
"strings"
"talisman/detector/severity"
mock "talisman/internal/mock/prompt"
"talisman/prompt"
"talisman/talismanrc"
"testing"
"github.com/golang/mock/gomock"
"github.com/spf13/afero"
logr "github.com/sirupsen/logrus"
"github.com/stretchr/testify/assert"
)
func init() {
logr.SetOutput(ioutil.Discard)
}
func TestNewDetectionResultsAreSuccessful(t *testing.T) {
results := NewDetectionResults(talismanrc.HookMode)
assert.True(t, results.Successful(), "New detection result is always expected to succeed")
assert.False(t, results.HasFailures(), "New detection result is not expected to fail")
}
func TestCallingFailOnDetectionResultsFails(t *testing.T) {
results := NewDetectionResults(talismanrc.HookMode)
results.Fail("some_filename", "filename", "Bomb", []string{}, severity.Low)
assert.False(t, results.Successful(), "Calling fail on a result should not make it succeed")
assert.True(t, results.HasFailures(), "Calling fail on a result should make it fail")
}
func TestCanRecordMultipleErrorsAgainstASingleFile(t *testing.T) {
results := NewDetectionResults(talismanrc.HookMode)
results.Fail("some_filename", "filename", "Bomb", []string{}, severity.Low)
results.Fail("some_filename", "filename", "Complete & utter failure", []string{}, severity.Low)
results.Fail("another_filename", "filename", "Complete & utter failure", []string{}, severity.Low)
assert.Len(t, results.GetFailures("some_filename"), 2, "Expected two errors against some_filename.")
assert.Len(t, results.GetFailures("another_filename"), 1, "Expected one error against another_filename")
}
func TestResultsReportsFailures(t *testing.T) {
results := NewDetectionResults(talismanrc.HookMode)
results.Fail("some_filename", "", "Bomb", []string{}, severity.Low)
results.Fail("some_filename", "", "Complete & utter failure", []string{}, severity.Low)
results.Fail("another_filename", "", "Complete & utter failure", []string{}, severity.Low)
actualErrorReport := results.ReportFileFailures("some_filename")
firstErrorMessage := strings.Join(actualErrorReport[0], " ")
secondErrorMessage := strings.Join(actualErrorReport[1], " ")
finalStringMessage := firstErrorMessage + " " + secondErrorMessage
assert.Regexp(t, "some_filename", finalStringMessage, "Error report does not contain expected output")
assert.Regexp(t, "Bomb", finalStringMessage, "Error report does not contain expected output")
assert.Regexp(t, "Complete & utter failure", finalStringMessage, "Error report does not contain expected output")
}
func TestUpdateResultsSummary(t *testing.T) {
results := NewDetectionResults(talismanrc.HookMode)
categories := []string{"filecontent", "filename", "filesize"}
for _, category := range categories {
results.updateResultsSummary(category, false)
}
assert.Equal(t, 1, results.Summary.Types.Filename)
assert.Equal(t, 1, results.Summary.Types.Filecontent)
assert.Equal(t, 1, results.Summary.Types.Filesize)
for _, category := range categories {
results.updateResultsSummary(category, true)
}
assert.Equal(t, 0, results.Summary.Types.Filename)
assert.Equal(t, 0, results.Summary.Types.Filecontent)
assert.Equal(t, 0, results.Summary.Types.Filesize)
}
func TestErrorExitCodeInInteractive(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
prompter := mock.NewMockPrompt(ctrl)
results := NewDetectionResults(talismanrc.HookMode)
promptContext := prompt.NewPromptContext(true, prompter)
prompter.EXPECT().Confirm(gomock.Any()).Return(false).Times(2)
results.Fail("some_file.pem", "filecontent", "Bomb", []string{}, severity.Low)
results.Fail("another.pem", "filecontent", "password", []string{}, severity.Low)
results.Report(promptContext, "default")
assert.True(t, results.HasFailures())
}
func TestSuccessExitCodeInInteractive(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
prompter := mock.NewMockPrompt(ctrl)
results := NewDetectionResults(talismanrc.HookMode)
promptContext := prompt.NewPromptContext(true, prompter)
prompter.EXPECT().Confirm(gomock.Any()).Return(true).Times(2)
results.Fail("some_file.pem", "filecontent", "Bomb", []string{}, severity.Low)
results.Fail("another.pem", "filecontent", "password", []string{}, severity.Low)
results.Report(promptContext, "default")
assert.False(t, results.HasFailures())
}
// Presently not showing the ignored files in the log
// func TestLoggingIgnoredFilesDoesNotCauseFailure(t *testing.T) {
// results := NewDetectionResults(talismanrc.HookMode)
// results.Ignore("some_file", "some-detector")
// results.Ignore("some/other_file", "some-other-detector")
// results.Ignore("some_file_ignored_for_multiple_things", "some-detector")
// results.Ignore("some_file_ignored_for_multiple_things", "some-other-detector")
// assert.True(t, results.Successful(), "Calling ignore should keep the result successful.")
// assert.True(t, results.HasIgnores(), "Calling ignore should be logged.")
// assert.False(t, results.HasFailures(), "Calling ignore should not cause a result to fail.")
// assert.Regexp(t, "some_file was ignored by .talismanrc for the following detectors: some-detector", results.Report(), "foo")
// assert.Regexp(t, "some/other_file was ignored by .talismanrc for the following detectors: some-other-detector", results.Report(), "foo")
// assert.Regexp(t, "some_file_ignored_for_multiple_things was ignored by .talismanrc for the following detectors: some-detector, some-other-detector", results.Report(), "foo")
// }
func TestTalismanRCSuggestionWhenThereAreFailures(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
prompter := mock.NewMockPrompt(ctrl)
results := NewDetectionResults(talismanrc.HookMode)
// Creating temp file with some content
fs := afero.NewMemMapFs()
file, err := afero.TempFile(fs, "", "talismanrc")
assert.NoError(t, err)
ignoreFile := file.Name()
talismanrc.SetFs__(fs)
talismanrc.SetRcFilename__(ignoreFile)
existingContent := `fileignoreconfig:
- filename: existing.pem
checksum: 123444ddssa75333b25b6275f97680604add51b84eb8f4a3b9dcbbc652e6f27ac
`
err = afero.WriteFile(fs, ignoreFile, []byte(existingContent), 0666)
assert.NoError(t, err)
// The tests below depend on the upper configuration which is shared across all three of them. Hence the order in
// which they run matters.
t.Run("should not prompt if there are no failures", func(t *testing.T) {
promptContext := prompt.NewPromptContext(true, prompter)
prompter.EXPECT().Confirm(gomock.Any()).Return(false).Times(0)
results.Report(promptContext, "default")
bytesFromFile, err := afero.ReadFile(fs, ignoreFile)
assert.NoError(t, err)
assert.Equal(t, existingContent, string(bytesFromFile))
})
_ = afero.WriteFile(fs, ignoreFile, []byte(existingContent), 0666)
t.Run("when user declines, entry should not be added to talismanrc", func(t *testing.T) {
promptContext := prompt.NewPromptContext(true, prompter)
prompter.EXPECT().Confirm("Do you want to add some_file.pem with above checksum in talismanrc ?").Return(false)
results.Fail("some_file.pem", "filecontent", "Bomb", []string{}, severity.Low)
results.Report(promptContext, "default")
bytesFromFile, err := afero.ReadFile(fs, ignoreFile)
assert.NoError(t, err)
assert.Equal(t, existingContent, string(bytesFromFile))
})
_ = afero.WriteFile(fs, ignoreFile, []byte(existingContent), 0666)
t.Run("when interactive flag is set to false, it should not ask user", func(t *testing.T) {
promptContext := prompt.NewPromptContext(false, prompter)
prompter.EXPECT().Confirm(gomock.Any()).Return(false).Times(0)
results.Fail("some_file.pem", "filecontent", "Bomb", []string{}, severity.Low)
results.Report(promptContext, "default")
bytesFromFile, err := afero.ReadFile(fs, ignoreFile)
assert.NoError(t, err)
assert.Equal(t, existingContent, string(bytesFromFile))
})
_ = afero.WriteFile(fs, ignoreFile, []byte(existingContent), 0666)
t.Run("when user confirms, entry should be appended to given ignore file", func(t *testing.T) {
promptContext := prompt.NewPromptContext(true, prompter)
prompter.EXPECT().Confirm("Do you want to add some_file.pem with above checksum in talismanrc ?").Return(true)
results.Fail("some_file.pem", "filecontent", "Bomb", []string{}, severity.Low)
expectedFileContent := `fileignoreconfig:
- filename: some_file.pem
checksum: 87139cc4d975333b25b6275f97680604add51b84eb8f4a3b9dcbbc652e6f27ac
version: "1.0"
`
results.Report(promptContext, "default")
bytesFromFile, err := afero.ReadFile(fs, ignoreFile)
assert.NoError(t, err)
assert.Equal(t, expectedFileContent, string(bytesFromFile))
})
_ = afero.WriteFile(fs, ignoreFile, []byte(existingContent), 0666)
t.Run("when user confirms, entry for existing file should updated", func(t *testing.T) {
promptContext := prompt.NewPromptContext(true, prompter)
prompter.EXPECT().Confirm("Do you want to add existing.pem with above checksum in talismanrc ?").Return(true)
results := NewDetectionResults(talismanrc.HookMode)
results.Fail("existing.pem", "filecontent", "This will bomb!", []string{}, severity.Low)
expectedFileContent := `fileignoreconfig:
- filename: existing.pem
checksum: 5bc0b0692a316bb2919263addaef0ffba3a21b9e1cca62a1028390e97e861e4e
version: "1.0"
`
results.Report(promptContext, "default")
bytesFromFile, err := afero.ReadFile(fs, ignoreFile)
assert.NoError(t, err)
assert.Equal(t, expectedFileContent, string(bytesFromFile))
})
_ = afero.WriteFile(fs, ignoreFile, []byte(existingContent), 0666)
t.Run("when user confirms for multiple entries, they should be appended to given ignore file", func(t *testing.T) {
promptContext := prompt.NewPromptContext(true, prompter)
prompter.EXPECT().Confirm("Do you want to add some_file.pem with above checksum in talismanrc ?").Return(true)
prompter.EXPECT().Confirm("Do you want to add another.pem with above checksum in talismanrc ?").Return(true)
results.Fail("some_file.pem", "filecontent", "Bomb", []string{}, severity.Low)
results.Fail("another.pem", "filecontent", "password", []string{}, severity.Low)
expectedFileContent := `fileignoreconfig:
- filename: another.pem
checksum: 117e23557c02cbd472854ebce4933d6daec1fd207971286f6ffc9f1774c1a83b
- filename: some_file.pem
checksum: 87139cc4d975333b25b6275f97680604add51b84eb8f4a3b9dcbbc652e6f27ac
version: "1.0"
`
results.Report(promptContext, "default")
bytesFromFile, err := afero.ReadFile(fs, ignoreFile)
assert.NoError(t, err)
assert.Equal(t, expectedFileContent, string(bytesFromFile))
})
err = fs.Remove(ignoreFile)
assert.NoError(t, err)
}
| {
"content_hash": "1bb2988c0a13651c186ed01ff2b66aae",
"timestamp": "",
"source": "github",
"line_count": 251,
"max_line_length": 177,
"avg_line_length": 42.430278884462155,
"alnum_prop": 0.7490140845070422,
"repo_name": "thoughtworks/talisman",
"id": "2ddf2df0dc298e0137dd5fccc1cae5210d5f08b3",
"size": "10650",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "detector/helpers/detection_results_test.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "558"
},
{
"name": "Go",
"bytes": "2713786"
},
{
"name": "Shell",
"bytes": "63298"
}
],
"symlink_target": ""
} |
namespace theia {
// Estimate a model using EVSAC sampler.
template <class ModelEstimator>
class Evsac : public SampleConsensusEstimator<ModelEstimator> {
public:
typedef typename ModelEstimator::Datum Datum;
typedef typename ModelEstimator::Model Model;
typedef ModelEstimator Estimator;
// Params:
// sorted_distances: The matrix containing k L2 sorted distances. The
// matrix has num. of query features as rows and k columns.
// predictor_threshold: The threshold used to decide correct or
// incorrect matches/correspondences. The recommended value is 0.65.
// fitting_method: The fiting method MLE or QUANTILE_NLS (see statx doc).
// The recommended fitting method is the MLE estimation.
Evsac(const RansacParameters& ransac_params, ModelEstimator& estimator,
const Eigen::MatrixXd& sorted_distances,
const double predictor_threshold, const FittingMethod fitting_method)
: SampleConsensusEstimator<ModelEstimator>(ransac_params, estimator),
sorted_distances_(sorted_distances),
predictor_threshold_(predictor_threshold),
fitting_method_(fitting_method) {}
~Evsac() {}
bool Initialize() {
Sampler<Datum>* prosac_sampler = new EvsacSampler<Datum>(
this->estimator_.SampleSize(), this->sorted_distances_,
this->predictor_threshold_, this->fitting_method_);
return SampleConsensusEstimator<ModelEstimator>::Initialize(
prosac_sampler);
}
protected:
// L2 descriptor sorted distances.
// rows: num of reference features.
// cols: k-th smallest distances.
const Eigen::MatrixXd& sorted_distances_;
// Threshold for predictor (MR-Rayleigh).
const double predictor_threshold_;
// The fitting method.
const FittingMethod fitting_method_;
private:
DISALLOW_COPY_AND_ASSIGN(Evsac);
};
} // namespace theia
#endif // THEIA_SOLVERS_EVSAC_H_
| {
"content_hash": "a492dc3c79e2317dcf0bae702027a9dd",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 79,
"avg_line_length": 39.24,
"alnum_prop": 0.6952089704383282,
"repo_name": "klemmster/TheiaSfM",
"id": "969d7bce182f30e781dac7882baf967e08c8b1dc",
"size": "4002",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/theia/solvers/evsac.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "328025"
},
{
"name": "C++",
"bytes": "8752597"
},
{
"name": "CMake",
"bytes": "260198"
},
{
"name": "HTML",
"bytes": "1139"
},
{
"name": "Makefile",
"bytes": "10927"
},
{
"name": "Objective-C",
"bytes": "3962"
},
{
"name": "Python",
"bytes": "183962"
},
{
"name": "Shell",
"bytes": "304414"
}
],
"symlink_target": ""
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!--
| Generated by Apache Maven Doxia at 2016-10-07
| Rendered using Apache Maven Fluido Skin 1.2.1
-->
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>JasperStarter - Project License</title>
<link rel="stylesheet" href="./css/apache-maven-fluido.min.css" />
<link rel="stylesheet" href="./css/site.css" />
<link rel="stylesheet" href="./css/print.css" media="print" />
<script type="text/javascript" src="./js/apache-maven-fluido.min.js"></script>
<meta name="Date-Revision-yyyymmdd" content="20161007" />
<meta http-equiv="Content-Language" content="en" />
</head>
<body class="topBarDisabled">
<div class="container-fluid">
<div id="banner">
<div class="pull-left">
<div id="bannerLeft">
<h2>JasperStarter - Running JasperReports from command line</h2>
</div>
</div>
<div class="pull-right"> </div>
<div class="clear"><hr/></div>
</div>
<div id="breadcrumbs">
<ul class="breadcrumb">
<li id="projectVersion">Version: 3.1.0-SNAPSHOT</li>
<li class="pull-right"> <a href="cs/index.html" title="[cs]">[cs]</a>
</li>
<li class="divider pull-right">|</li>
<li class="pull-right"> <a href="de/index.html" title="[de]">[de]</a>
</li>
</ul>
</div>
<div class="row-fluid">
<div id="leftColumn" class="span3">
<div class="well sidebar-nav">
<h3>Overview</h3>
<ul>
<li class="none">
<a href="index.html" title="Introduction">Introduction</a>
</li>
<li class="none">
<a href="usage.html" title="Usage">Usage</a>
</li>
<li class="none">
<a href="screenshots.html" title="Screenshots">Screenshots</a>
</li>
<li class="none">
<a href="files.html" title="Files">Files</a>
</li>
<li class="none">
<a href="changes.html" title="Changes">Changes</a>
</li>
<li class="none">
<a href="http://sourceforge.net/projects/jasperstarter/files/" class="externalLink" title="Downloads">Downloads</a>
</li>
<li class="none">
<a href="source-repository.html" title="Sourcecode">Sourcecode</a>
</li>
<li class="none">
<a href="http://sourceforge.net/projects/jasperstarter/" class="externalLink" title="Project Site">Project Site</a>
</li>
<li class="none">
<a href="http://www.openhub.net/p/jasperstarter" class="externalLink" title="OpenHub">OpenHub</a>
</li>
</ul>
<h3>Howto</h3>
<ul>
<li class="none">
<a href="unicode-pdf-export.html" title="Unicode pdf export">Unicode pdf export</a>
</li>
</ul>
<h3>Project Documentation</h3>
<ul>
<li class="expanded">
<a href="project-info.html" title="Project Information">Project Information</a>
<ul>
<li class="none">
<a href="project-summary.html" title="Project Summary">Project Summary</a>
</li>
<li class="none">
<strong>Project License</strong>
</li>
<li class="none">
<a href="team-list.html" title="Project Team">Project Team</a>
</li>
<li class="none">
<a href="source-repository.html" title="Source Repository">Source Repository</a>
</li>
<li class="none">
<a href="issue-tracking.html" title="Issue Tracking">Issue Tracking</a>
</li>
<li class="none">
<a href="dependencies.html" title="Dependencies">Dependencies</a>
</li>
</ul>
</li>
</ul>
<div id="lastPublished">
<span id="publishDate">Last Published: 2016-10-07</span>
</div>
<hr class="divider" />
<div id="poweredBy">
<div class="clear"></div>
<div class="clear"></div>
<div id="twitter">
<a href="https://twitter.com/vosskaem" class="twitter-follow-button" data-show-count="false" data-align="left" data-size="medium" data-show-screen-name="false" data-lang="en">Follow vosskaem</a>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
</div>
<div class="clear"></div>
<a href="http://maven.apache.org/" title="Built by Maven" class="poweredBy">
<img class="poweredBy" alt="Built by Maven" src="./images/logos/maven-feather.png" />
</a>
</div>
</div>
</div>
<div id="bodyColumn" class="span9" >
<div class="section">
<h2>Overview<a name="Overview"></a></h2><a name="Overview"></a>
<p>Typically the licenses listed for the project are that of the project itself, and not of dependencies.</p></div>
<div class="section">
<h2>Project License<a name="Project_License"></a></h2><a name="Project_License"></a>
<div class="section">
<h3>The Apache Software License, Version 2.0<a name="The_Apache_Software_License_Version_2.0"></a></h3><a name="The_Apache_Software_License_Version_2.0"></a>
<div class="source">
<pre>
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
</pre></div></div></div>
</div>
</div>
<hr/>
<footer>
<div class="container-fluid">
<div class="row span16">Copyright © 2012-2016
<a href="http://www.cenote.de">Cenote GmbH</a>.
All Rights Reserved.
</div>
</div>
</footer>
</body>
</html>
| {
"content_hash": "48079b7e90971d07bc4ac2ae4949d491",
"timestamp": "",
"source": "github",
"line_count": 385,
"max_line_length": 251,
"avg_line_length": 49.25454545454546,
"alnum_prop": 0.6260612772240679,
"repo_name": "Dericktan/phpjasper",
"id": "ac8ee6ed3f84a00aa8ae08ce72e957fec4de761a",
"size": "18963",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/JasperStarter/docs/license.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3408"
},
{
"name": "HTML",
"bytes": "786373"
},
{
"name": "PHP",
"bytes": "7776"
},
{
"name": "Shell",
"bytes": "838"
}
],
"symlink_target": ""
} |
import sys
import os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
sys.path.insert(0, os.path.abspath('..'))
# -- General configuration ----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest',
'sphinx.ext.coverage', 'sphinx.ext.viewcode']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'pycodestyle'
authors = u'Johann C. Rocholl, Florent Xicluna, Ian Lee'
copyright = u'2006-2016, %s' % (authors)
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
pkg_version = __import__('pycodestyle').__version__.split('.')
# The short X.Y version.
version = '.'.join(pkg_version[:2])
# The full version, including alpha/beta/rc tags.
release = '.'.join(pkg_version)
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for
# all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output --------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
if not on_rtd: # only import and set the theme if we're building docs locally
import sphinx_rtd_theme
html_theme = 'sphinx_rtd_theme'
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
# html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'pycodestyledoc'
# -- Options for LaTeX output -------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto/manual]).
latex_documents = [
('index', 'pycodestyle.tex', u'pycodestyle documentation',
authors, 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output -------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'pycodestyle', u'pycodestyle documentation',
[authors], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output -----------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'pycodestyle', u'pycodestyle documentation', authors,
'pycodestyle', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
| {
"content_hash": "67921a363836f27e40f2e47b81365edd",
"timestamp": "",
"source": "github",
"line_count": 241,
"max_line_length": 79,
"avg_line_length": 32.79668049792531,
"alnum_prop": 0.6972419028340081,
"repo_name": "PyCQA/pep8",
"id": "7935b0b2f63c40a8b3d5e980fd2285ac90732072",
"size": "8328",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "docs/conf.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Makefile",
"bytes": "215"
},
{
"name": "Python",
"bytes": "160589"
}
],
"symlink_target": ""
} |
package com.facebook.litho.editor;
import com.facebook.litho.editor.model.EditorValue;
import java.lang.reflect.Field;
/**
* A class to operate on Component fields from an external editor such as Flipper.
*
* <p>It is meant to be implemented for a single class. This pairing [Class, Implementation] cannot
* be done in plain Java, so we rely on the implementor to pair it with its corresponding class in a
* Map such as the one in the EditorRegistry.
*
* @see com.facebook.litho.editor.EditorRegistry
*/
public interface Editor {
/**
* Receives the instance of the corresponding field, and expects the implementor to return an
* EditorValue representation of it. This structure will be replicated for the values received by
* {@link Editor#write(Field, Object, EditorValue)}
*/
EditorValue read(Field f, Object node);
/**
* Receives the instance of the corresponding field, and one or multiple values following the
* structure that was given in {@link Editor#read(Field, Object)}. Those values are meant to be
* applied back to the corresponding field.
*/
boolean write(Field f, Object node, EditorValue values);
}
| {
"content_hash": "7f6b1062b9f1b28f1a1093e1338aae39",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 100,
"avg_line_length": 37.41935483870968,
"alnum_prop": 0.7422413793103448,
"repo_name": "facebook/litho",
"id": "7dce51189ba265cd6980d6506f873326fb368947",
"size": "1778",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "litho-editor-core/src/main/java/com/facebook/litho/editor/Editor.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "3065"
},
{
"name": "C++",
"bytes": "382935"
},
{
"name": "CMake",
"bytes": "1490"
},
{
"name": "Haskell",
"bytes": "7720"
},
{
"name": "Java",
"bytes": "9413537"
},
{
"name": "JavaScript",
"bytes": "28046"
},
{
"name": "Kotlin",
"bytes": "1326831"
},
{
"name": "SCSS",
"bytes": "5360"
},
{
"name": "Shell",
"bytes": "12115"
},
{
"name": "Starlark",
"bytes": "241912"
}
],
"symlink_target": ""
} |
# spedycjacentrala
This application was generated using JHipster, you can find documentation and help at [https://jhipster.github.io](https://jhipster.github.io).
Before you can build this project, you must install and configure the following dependencies on your machine:
1. [Node.js][]: We use Node to run a development web server and build the project.
Depending on your system, you can install Node either from source or as a pre-packaged bundle.
After installing Node, you should be able to run the following command to install development tools (like
[Bower][] and [BrowserSync][]). You will only need to run this command when dependencies change in package.json.
npm install
We use [Grunt][] as our build system. Install the grunt command-line tool globally with:
npm install -g grunt-cli
Run the following commands in two separate terminals to create a blissful development experience where your browser
auto-refreshes when files change on your hard drive.
mvn
grunt
Bower is used to manage CSS and JavaScript dependencies used in this application. You can upgrade dependencies by
specifying a newer version in `bower.json`. You can also run `bower update` and `bower install` to manage dependencies.
Add the `-h` flag on any command to see how you can use it. For example, `bower update -h`.
# Building for production
To optimize the spedycjacentrala client for production, run:
mvn -Pprod clean package
This will concatenate and minify CSS and JavaScript files. It will also modify `index.html` so it references
these new files.
To ensure everything worked, run:
java -jar target/*.war --spring.profiles.active=prod
Then navigate to [http://localhost:8080](http://localhost:8080) in your browser.
# Testing
Unit tests are run by [Karma][] and written with [Jasmine][]. They're located in `src/test/javascript` and can be run with:
grunt test
UI end-to-end tests are powered by [Protractor][], which is built on top of WebDriverJS. They're located in `src/test/javascript/e2e`
and can be run by starting Spring Boot in one terminal (`mvn spring-boot:run`) and running the tests (`grunt itest`) in a second one.
# Continuous Integration
To setup this project in Jenkins, use the following configuration:
* Project name: `spedycjacentrala`
* Source Code Management
* Git Repository: `[email protected]:xxxx/spedycjacentrala.git`
* Branches to build: `*/master`
* Additional Behaviours: `Wipe out repository & force clone`
* Build Triggers
* Poll SCM / Schedule: `H/5 * * * *`
* Build
* Invoke Maven / Tasks: `-Pprod clean package`
* Execute Shell / Command:
````
mvn spring-boot:run &
bootPid=$!
sleep 30s
grunt itest
kill $bootPid
````
* Post-build Actions
* Publish JUnit test result report / Test Report XMLs: `build/test-results/*.xml,build/reports/e2e/*.xml`
[JHipster]: https://jhipster.github.io/
[Node.js]: https://nodejs.org/
[Bower]: http://bower.io/
[Grunt]: http://gruntjs.com/
[BrowserSync]: http://www.browsersync.io/
[Karma]: http://karma-runner.github.io/
[Jasmine]: http://jasmine.github.io/2.0/introduction.html
[Protractor]: https://angular.github.io/protractor/
| {
"content_hash": "f251a5db73383c0cd5635bb8c3b89beb",
"timestamp": "",
"source": "github",
"line_count": 84,
"max_line_length": 143,
"avg_line_length": 38.464285714285715,
"alnum_prop": 0.7294955122253173,
"repo_name": "wyzellak/sandbox-internet-apps-design",
"id": "c3c8e123a0bbe92fa90e44db5d6b3f1aa096db0d",
"size": "3231",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "centrala/README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "48278"
},
{
"name": "Batchfile",
"bytes": "10012"
},
{
"name": "CSS",
"bytes": "8840"
},
{
"name": "HTML",
"bytes": "308660"
},
{
"name": "Java",
"bytes": "558512"
},
{
"name": "JavaScript",
"bytes": "398525"
},
{
"name": "Shell",
"bytes": "14116"
}
],
"symlink_target": ""
} |
//
// AppDelegate.m
// StackTray
//
// Created by Remco on 27/04/14.
// Copyright (c) 2014 DutchCoders. All rights reserved.
//
#import "AppDelegate.h"
#import "PreferencesWindowController.h"
#import "AboutWindowController.h"
#import "ConsoleWindowController.h"
#import </Users/sunil/workspace/buffer/aws-sdk-ios/src/include/EC2/AmazonEC2Client.h>
#import "Stack.h"
@implementation AppDelegate
@synthesize managedObjectContext = __managedObjectContext;
@synthesize managedObjectModel = __managedObjectModel;
@synthesize persistentStoreCoordinator = __persistentStoreCoordinator;
+ (AppDelegate *)sharedAppDelegate
{
return (AppDelegate *)[[NSApplication sharedApplication] delegate];
}
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
[[NSUserNotificationCenter defaultUserNotificationCenter] setDelegate:self];
}
- (BOOL)userNotificationCenter:(NSUserNotificationCenter *)center shouldPresentNotification:(NSUserNotification *)notification{
return YES;
}
- (void)awakeFromNib
{
// Build the statusbar menu
statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:NSVariableStatusItemLength];
[statusItem setHighlightMode:YES];
[statusItem setTitle:[NSString stringWithFormat:@"%C",0x2601]];
[statusItem setEnabled:YES];
[self updateMenu];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(managedObjectContextObjectsDidChange:) name:NSManagedObjectContextObjectsDidChangeNotification object:nil];
}
/*
- (NSMenu *)applicationDockMenu:(NSApplication *)sender {
if (m_menu == nil) {
m_menu = [[NSMenu alloc] init];
id titleMenuItem = [[NSMenuItem alloc] initWithTitle:@"test" action:@selector(terminate:) keyEquivalent:@"q"];
[m_menu addItem:titleMenuItem];
[m_menu addItem:[NSMenuItem separatorItem]];
NSMenuItem *openMenuItem = [[NSMenuItem alloc] initWithTitle:@"Open in Browser" action:@selector(openUrl) keyEquivalent:@""];
[m_menu addItem:openMenuItem];
NSMenuItem *copyUrlMenuItem = [[NSMenuItem alloc] initWithTitle:@"Copy link to Clipboard" action:@selector(copyUrl) keyEquivalent:@""];
[m_menu addItem:copyUrlMenuItem];
// OSX will automatically add the Quit option
}
return m_menu;
}
*/
- (IBAction)connect:(id)sender {
NSMenuItem* menuItem= (NSMenuItem*)sender;
EC2Instance* instance = (EC2Instance*)menuItem.representedObject;
NSString* address = instance.publicIpAddress;
// instance.publicIpAddress;
if ([address length]==0) {
address = instance.publicDnsName;
}
NSString* pemFileLocation = [self getPemFileLocation];
NSString* scriptName = @"connectwithpem";
if(!pemFileLocation) {
scriptName = @"connectwithoutpem";
}
NSString* sshUser = [self getSSHUser];
// get from settings
NSString *path = [[NSBundle mainBundle] pathForResource:scriptName ofType:@"scpt"];
NSString *script = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
NSAppleScript *appleScript =
[[NSAppleScript alloc] initWithSource:[NSString stringWithFormat:script, address, sshUser, pemFileLocation]];
NSDictionary *error;
NSAppleEventDescriptor *result =
[appleScript executeAndReturnError:&error];
if (error!=nil) {
NSAlert *alert = [[NSAlert alloc] init];
[alert addButtonWithTitle:@"Close"];
[alert setMessageText:@"Error connecting to iTerm."];
[alert setInformativeText: [error objectForKey:@"NSAppleScriptErrorMessage"]];
[alert setAlertStyle:NSWarningAlertStyle];
[alert runModal];
}
}
- (IBAction)viewInAWS:(id) sender {
NSMenuItem* menuItem= (NSMenuItem*)sender;
EC2Instance* instance = (EC2Instance*)menuItem.representedObject;
}
- (IBAction)browse:(id)sender {
// http://lifehacker.com/5533695/open-links-in-your-macs-current-browser-instead-of-the-default
NSMenuItem* menuItem= (NSMenuItem*)sender;
EC2Instance* instance = (EC2Instance*)menuItem.representedObject;
NSString* address = instance.publicDnsName;
if ([address length]==0) {
address = instance.privateDnsName;
}
NSString *path = [[NSBundle mainBundle] pathForResource:@"browse" ofType:@"scpt"];
NSString *script = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
NSLog(@"%@", script);
NSAppleScript *appleScript =
[[NSAppleScript alloc] initWithSource:[NSString stringWithFormat:script, address]];
NSDictionary *error;
NSAppleEventDescriptor *result =
[appleScript executeAndReturnError:&error];
}
- (IBAction)reboot:(id)sender {
NSMenuItem* menuItem= (NSMenuItem*)sender;
AmazonEC2Client* client = (AmazonEC2Client*)[((NSDictionary*)menuItem.representedObject) objectForKey:@"client"];
EC2Instance* instance = (EC2Instance*)[((NSDictionary*)menuItem.representedObject) objectForKey:@"instance"];
EC2RebootInstancesRequest* rq = [[EC2RebootInstancesRequest alloc] initWithInstanceIds:[[NSMutableArray alloc] initWithObjects: instance.instanceId, nil]];
EC2RebootInstancesResponse* response = [client rebootInstances:(EC2RebootInstancesRequest *)rq];
// wait for reboot up status, then show notification
/*
NSUserNotification *notification = [[NSUserNotification alloc] init];
notification.title = @"Server rebooted";
notification.informativeText = [NSString stringWithFormat:@"Server %@ has been rebooted.", [instance instanceId]];
notification.soundName = NSUserNotificationDefaultSoundName;
[[NSUserNotificationCenter defaultUserNotificationCenter] deliverNotification:notification];
*/
}
- (IBAction)consoleOutput:(id)sender {
NSMenuItem* menuItem= (NSMenuItem*)sender;
AmazonEC2Client* client = (AmazonEC2Client*)[((NSDictionary*)menuItem.representedObject) objectForKey:@"client"];
EC2Instance* instance = (EC2Instance*)[((NSDictionary*)menuItem.representedObject) objectForKey:@"instance"];
EC2GetConsoleOutputRequest* rq = [[EC2GetConsoleOutputRequest alloc] initWithInstanceId:instance.instanceId];
@try {
EC2GetConsoleOutputResponse* response = [client getConsoleOutput:(EC2GetConsoleOutputRequest *)rq];
NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:[response output] options:0];
NSString *decodedString = [[NSString alloc] initWithData:decodedData encoding:NSUTF8StringEncoding];
ConsoleWindowController* consoleWindowController = [ConsoleWindowController sharedConsoleWindowController];
[consoleWindowController setOutput:decodedString];
[consoleWindowController showWindow:self];
[NSApp activateIgnoringOtherApps:YES];
[[consoleWindowController window] makeKeyAndOrderFront:nil];
}
@catch (AmazonClientException *exception) {
NSAlert *alert = [[NSAlert alloc] init];
[alert addButtonWithTitle:@"Close"];
[alert setMessageText:[exception name]];
[alert setInformativeText:[exception message]];
[alert setAlertStyle:NSWarningAlertStyle];
[alert runModal];
}
@catch (NSException *exception) {
NSLog(@"%@", exception);
}
}
- (IBAction)start:(id)sender {
NSMenuItem* menuItem= (NSMenuItem*)sender;
AmazonEC2Client* client = (AmazonEC2Client*)[((NSDictionary*)menuItem.representedObject) objectForKey:@"client"];
EC2Instance* instance = (EC2Instance*)[((NSDictionary*)menuItem.representedObject) objectForKey:@"instance"];
EC2StartInstancesRequest* rq = [[EC2StartInstancesRequest alloc] initWithInstanceIds:[[NSMutableArray alloc] initWithObjects: instance.instanceId, nil]];
@try {
EC2StartInstancesResponse* response = [client startInstances:(EC2StartInstancesRequest *)rq];
}
@catch (AmazonClientException *exception) {
NSAlert *alert = [[NSAlert alloc] init];
[alert addButtonWithTitle:@"Close"];
[alert setMessageText:[exception name]];
[alert setInformativeText:[exception message]];
[alert setAlertStyle:NSWarningAlertStyle];
[alert runModal];
}
@catch (NSException *exception) {
NSLog(@"%@", exception);
}
}
- (IBAction)stop:(id)sender {
NSMenuItem* menuItem= (NSMenuItem*)sender;
AmazonEC2Client* client = (AmazonEC2Client*)[((NSDictionary*)menuItem.representedObject) objectForKey:@"client"];
EC2Instance* instance = (EC2Instance*)[((NSDictionary*)menuItem.representedObject) objectForKey:@"instance"];
EC2StopInstancesRequest* rq = [[EC2StopInstancesRequest alloc] initWithInstanceIds:[[NSMutableArray alloc] initWithObjects: instance.instanceId, nil]];
@try {
EC2StopInstancesResponse* response = [client stopInstances:(EC2StopInstancesRequest *)rq];
}
@catch (AmazonClientException *exception) {
NSAlert *alert = [[NSAlert alloc] init];
[alert addButtonWithTitle:@"Close"];
[alert setMessageText:[exception name]];
[alert setInformativeText:[exception message]];
[alert setAlertStyle:NSWarningAlertStyle];
[alert runModal];
}
@catch (NSException *exception) {
NSLog(@"%@", exception);
}
}
- (IBAction)refresh:(id)sender {
[self updateMenu];
}
- (void)refresh {
[self updateMenu];
}
-(void)sortMenu:(NSMenu*)menu
{
// [CH] Get an array of all menu items.
NSArray* items = [menu itemArray];
[menu removeAllItems];
// [CH] Sort the array
NSSortDescriptor* alphaDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"title" ascending:YES];
items = [items sortedArrayUsingDescriptors:[NSArray arrayWithObjects:alphaDescriptor, nil]];
// [CH] ok, now set it back.
for(NSMenuItem* item in items){
[menu addItem:item];
/**
* [CH] The following code fixes NSPopUpButton's confusion that occurs when
* we sort this list. NSPopUpButton listens to the NSMenu's add notifications
* and hides the first item. Sorting this blows it up.
**/
if(item.isHidden){
item.hidden = false;
}
}
}
- (NSString*)getPemFileLocation {
NSManagedObjectContext *context = [self managedObjectContext];
NSError *error;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Stack" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
if (fetchedObjects.count>0) {
for (Stack *stack in fetchedObjects) {
if(stack.pemFileLocation) {
return stack.pemFileLocation;
}
}
}
return nil;
}
- (NSString*)getSSHUser {
NSManagedObjectContext *context = [self managedObjectContext];
NSError *error;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Stack" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
if (fetchedObjects.count>0) {
for (Stack *stack in fetchedObjects) {
if(stack.pemFileLocation) {
return stack.sshUser;
}
}
}
return nil;
}
-(NSString *) toLocalTime:(NSDate*)date
{
NSDateFormatter* df_local = [[NSDateFormatter alloc] init];
[df_local setTimeZone:[NSTimeZone defaultTimeZone]];
[df_local setDateFormat:@"MMM dd yyyy, hh:mm:ss aaa zzz"];
return [df_local stringFromDate:date];
}
- (void)updateMenu {
statusMenu = [[NSMenu alloc]initWithTitle: @"Tray"];
NSManagedObjectContext *context = [self managedObjectContext];
NSError *error;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Stack" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
bool useSubMenu = fetchedObjects.count > 1;
if (fetchedObjects.count>0) {
for (Stack *stack in fetchedObjects) {
if (stack.accessKey==nil || [stack.accessKey isEqualToString:@""]) {
continue;
}
if (stack.secretKey==nil || [stack.secretKey isEqualToString:@""]) {
continue;
}
if (stack.region == nil || [stack.region isEqualToString:@""]) {
continue;
}
@try {
AmazonEC2Client* client = [[AmazonEC2Client alloc] initWithAccessKey:stack.accessKey withSecretKey:stack.secretKey];
client.endpoint = [@"https://" stringByAppendingString:stack.region];
EC2DescribeInstancesRequest* rq = [EC2DescribeInstancesRequest alloc];
EC2DescribeInstancesResponse* response = [client describeInstances:(EC2DescribeInstancesRequest *)rq];
NSMenu* instancesMenu = statusMenu;
NSMenuItem* instancesMenuItem = nil;
if(useSubMenu) {
instancesMenu = [[NSMenu alloc]initWithTitle: stack.title];
instancesMenuItem = [[NSMenuItem alloc] initWithTitle:stack.title action:nil keyEquivalent:@"" ];
[instancesMenuItem setSubmenu:instancesMenu];
}
for (EC2Reservation* reservation in [response reservations]) {
for (EC2Instance* instance in [reservation instances]) {
[instances setObject:instance forKey:[instance instanceId]];
NSString* title=[instance instanceId];
for (EC2Tag* tag in [instance tags]) {
if ([tag.key caseInsensitiveCompare:@"Name"]==NSOrderedSame) {
title = tag.value;
}
}
NSMenu* instanceMenu = [[NSMenu alloc]initWithTitle: title];
NSMenuItem* subMenuItem = [[NSMenuItem alloc] initWithTitle:[NSString stringWithFormat:@"InstanceId: %@", [instance instanceId]] action:nil keyEquivalent:@""];
subMenuItem.representedObject=[instance instanceId];
[instanceMenu addItem:subMenuItem];
subMenuItem = [[NSMenuItem alloc] initWithTitle:[NSString stringWithFormat:@"Type: %@",[instance instanceType]] action:nil keyEquivalent:@""];
subMenuItem.representedObject=[instance instanceId];
[instanceMenu addItem:subMenuItem];
subMenuItem = [[NSMenuItem alloc] initWithTitle:[NSString stringWithFormat:@"State: %@", [[instance state] name ]] action:nil keyEquivalent:@""];
subMenuItem.representedObject=[instance instanceId];
[instanceMenu addItem:subMenuItem];
subMenuItem = [[NSMenuItem alloc] initWithTitle:[NSString stringWithFormat:@"Launch Time: %@", [self toLocalTime:[instance launchTime]]] action:nil keyEquivalent:@""];
subMenuItem.representedObject=[instance instanceId];
[instanceMenu addItem:subMenuItem];
[instanceMenu addItem:[NSMenuItem separatorItem]];
subMenuItem = [[NSMenuItem alloc] initWithTitle:@"Clipboard" action:nil keyEquivalent:@""];
[instanceMenu addItem:subMenuItem];
subMenuItem = [[NSMenuItem alloc] initWithTitle:[instance privateDnsName] action:@selector(copy:) keyEquivalent:@""];
subMenuItem.representedObject=[instance privateDnsName];
[instanceMenu addItem:subMenuItem];
NSString * ipAddress = instance.privateIpAddress ? instance.privateIpAddress : @"";
subMenuItem = [[NSMenuItem alloc] initWithTitle:ipAddress action:@selector(copy:) keyEquivalent:@""];
subMenuItem.representedObject=ipAddress;
[instanceMenu addItem:subMenuItem];
if ([[instance publicDnsName] length]>0) {
subMenuItem = [[NSMenuItem alloc] initWithTitle:[instance publicDnsName] action:@selector(copy:) keyEquivalent:@""];
subMenuItem.representedObject=[instance publicDnsName];
[instanceMenu addItem:subMenuItem];
}
if ([[instance publicIpAddress] length]>0) {
subMenuItem = [[NSMenuItem alloc] initWithTitle:[instance publicIpAddress] action:@selector(copy:) keyEquivalent:@""];
subMenuItem.representedObject=[instance publicIpAddress];
[instanceMenu addItem:subMenuItem];
}
NSMenuItem* instanceMenuItem = [[NSMenuItem alloc] initWithTitle:title action:nil keyEquivalent:@"" ];
//set the font and title for menu item
NSDictionary *attributes = @{
NSFontAttributeName: [NSFont fontWithName:@"Arial" size:15.0],
NSForegroundColorAttributeName: [self getInstanceStateFontColor:instance]
};
NSAttributedString *attributedTitle = [[NSAttributedString alloc] initWithString:[instanceMenuItem title] attributes:attributes];
[instanceMenuItem setAttributedTitle:attributedTitle];
// [instanceMenuItem setAttributedTitle:[[NSAttributedString alloc] initWithHTML:[[NSString stringWithFormat:@"<span style='color: red;'>%@</span>", title] dataUsingEncoding:NSUTF8StringEncoding] baseURL:nil documentAttributes:nil]];
// ●
[instanceMenu addItem:[NSMenuItem separatorItem]];
subMenuItem = [[NSMenuItem alloc] initWithTitle:@"Actions" action:nil keyEquivalent:@""];
[instanceMenu addItem:subMenuItem];
subMenuItem = [[NSMenuItem alloc] initWithTitle:@"Connect" action:@selector(connect:) keyEquivalent:@""];
subMenuItem.representedObject=instance;
[instanceMenu addItem:subMenuItem];
subMenuItem = [[NSMenuItem alloc] initWithTitle:@"Browse" action:@selector(browse:) keyEquivalent:@""];
subMenuItem.representedObject=instance;
[instanceMenu addItem:subMenuItem];
NSDictionary* dict= [[NSDictionary alloc] initWithObjectsAndKeys: instance, @"instance", client, @"client", nil];
/**
if ([[[instance state] name ] caseInsensitiveCompare:@"running"]==NSOrderedSame) {
subMenuItem = [[NSMenuItem alloc] initWithTitle:@"Stop" action:@selector(stop:) keyEquivalent:@""];
subMenuItem.representedObject=dict;
[instanceMenu addItem:subMenuItem];
} else {
subMenuItem = [[NSMenuItem alloc] initWithTitle:@"Start" action:@selector(start:) keyEquivalent:@""];
subMenuItem.representedObject=dict;
[instanceMenu addItem:subMenuItem];
}
subMenuItem = [[NSMenuItem alloc] initWithTitle:@"Reboot" action:@selector(reboot:) keyEquivalent:@""];
subMenuItem.representedObject=dict;
[instanceMenu addItem:subMenuItem];
*/
subMenuItem = [[NSMenuItem alloc] initWithTitle:@"Console output" action:@selector(consoleOutput:) keyEquivalent:@""];
subMenuItem.representedObject=dict;
[instanceMenu addItem:subMenuItem];
[instanceMenuItem setSubmenu:instanceMenu];
[instancesMenu addItem:instanceMenuItem];
}
}
[self sortMenu:instancesMenu];
if(useSubMenu) {
[statusMenu addItem:instancesMenuItem];
}
}
@catch (AmazonClientException *exception) {
NSLog(@"%@ error", exception);
/*
NSAlert *alert = [[NSAlert alloc] init];
[alert addButtonWithTitle:@"Close"];
[alert setMessageText:[exception name]];
[alert setInformativeText:[exception message]];
[alert setAlertStyle:NSWarningAlertStyle];
[alert runModal];
*/
}
@catch (NSException *exception) {
NSLog(@"%@", exception);
}
}
} else {
NSMenuItem* instancesMenuItem = [[NSMenuItem alloc] initWithTitle:@"No instances added yet" action:nil keyEquivalent:@"" ];
[statusMenu addItem:instancesMenuItem];
}
[statusMenu addItem:[NSMenuItem separatorItem]];
NSMenuItem* refreshMenuItem = [[NSMenuItem alloc] initWithTitle:@"Refresh..." action:@selector(refresh:) keyEquivalent:@"" ];
[statusMenu addItem:refreshMenuItem];
NSMenuItem* preferencesMenuItem = [[NSMenuItem alloc] initWithTitle:@"Open Preferences..." action:@selector(preferences:) keyEquivalent:@"" ];
[statusMenu addItem:preferencesMenuItem];
[statusMenu addItem:[NSMenuItem separatorItem]];
NSMenuItem* aboutMenuItem = [[NSMenuItem alloc] initWithTitle:@"About" action:@selector(about:) keyEquivalent:@"" ];
[statusMenu addItem:aboutMenuItem];
NSMenuItem* quitMenuItem = [[NSMenuItem alloc] initWithTitle:@"Quit StackTray" action:@selector(quit:) keyEquivalent:@"" ];
[statusMenu addItem:quitMenuItem];
[statusItem setAction:@selector(menuAction:)];
}
- (NSColor *) getInstanceStateFontColor:(EC2Instance *)instance {
if ([[[instance state] name] caseInsensitiveCompare:@"terminated"]==NSOrderedSame) {
return [NSColor redColor];
}
else if ([[[instance state] name] caseInsensitiveCompare:@"stopping"]==NSOrderedSame) {
return [NSColor orangeColor];
}
else {
return [NSColor blackColor];
}
}
- (void)menuAction:(id)sender {
NSLog(@"Refreshing details");
[self refresh];
[statusItem popUpStatusItemMenu:statusMenu];
}
- (IBAction)quit:(id)sender {
[[NSApplication sharedApplication] terminate:nil];
}
- (IBAction)preferences:(id)sender {
PreferencesWindowController* preferencesWindowController = [PreferencesWindowController sharedPreferencesWindowController];
[preferencesWindowController showWindow:self];
//Focus on window
[NSApp activateIgnoringOtherApps:YES];
[[preferencesWindowController window] makeKeyAndOrderFront:nil];
}
- (IBAction)about:(id)sender {
AboutWindowController* aboutWindowController = [AboutWindowController sharedAboutWindowController];
[aboutWindowController showWindow:self];
//Focus on window
[NSApp activateIgnoringOtherApps:YES];
[[aboutWindowController window] makeKeyAndOrderFront:nil];
}
#pragma mark - Core Data stack
// Returns the managed object context for the application.
// If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
- (NSManagedObjectContext *)managedObjectContext
{
if (__managedObjectContext != nil) {
return __managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
__managedObjectContext = [[NSManagedObjectContext alloc] init];
[__managedObjectContext setPersistentStoreCoordinator:coordinator];
}
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(managedObjectContextObjectsDidChange:) name:NSManagedObjectContextObjectsDidChangeNotification object:__managedObjectContext];
return __managedObjectContext;
}
// Returns the managed object model for the application.
// If the model doesn't already exist, it is created from the application's model.
- (NSManagedObjectModel *)managedObjectModel
{
if (__managedObjectModel != nil) {
return __managedObjectModel;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"StackTray" withExtension:@"momd"];
__managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return __managedObjectModel;
}
// Returns the persistent store coordinator for the application.
// If the coordinator doesn't already exist, it is created and the application's store added to it.
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (__persistentStoreCoordinator != nil) {
return __persistentStoreCoordinator;
}
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"StackTray.sqlite"];
NSError *error = nil;
__persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:@{NSMigratePersistentStoresAutomaticallyOption:@YES, NSInferMappingModelAutomaticallyOption:@YES} error:&error]) {
/*
Replace this implementation with code to handle the error appropriately.
abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
Typical reasons for an error here include:
* The persistent store is not accessible;
* The schema for the persistent store is incompatible with current managed object model.
Check the error message to determine what the actual problem was.
If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.
If you encounter schema incompatibility errors during development, you can reduce their frequency by:
* Simply deleting the existing store:
[[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]
* Performing automatic lightweight migration by passing the following dictionary as the options parameter:
[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.
*/
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
return __persistentStoreCoordinator;
}
- (NSURL *)applicationDocumentsDirectory
{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
- (IBAction)copy:(id)sender {
// EC2Instance
NSMenuItem* menuItem= (NSMenuItem*)sender;
NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
[pasteboard clearContents];
NSArray *copiedObjects = [NSArray arrayWithObject:(NSString*)menuItem.representedObject];
[pasteboard writeObjects:copiedObjects];
}
- (void)save:(id)sender {
NSError* error;
if (![[self managedObjectContext] save:&error]) {
NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
}
// AppDelegate * appDelegate = (AppDelegate *) [[NSApplication sharedApplication] delegate];
[self refresh];
}
- (void)managedObjectContextObjectsDidChange:(NSNotification *)notification;
{
[NSObject cancelPreviousPerformRequestsWithTarget:self];
[self performSelector:@selector(save:) withObject:NULL afterDelay:0.2];
}
@end
| {
"content_hash": "84079b69bdbb198a6283daabe858b7fe",
"timestamp": "",
"source": "github",
"line_count": 698,
"max_line_length": 257,
"avg_line_length": 42.03868194842407,
"alnum_prop": 0.6457417441979347,
"repo_name": "bufferapp/stacktray",
"id": "ec48357b395c8e161b9b60d48535fb8d2241b1d5",
"size": "29343",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "StackTray/AppDelegate.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "AppleScript",
"bytes": "874"
},
{
"name": "CSS",
"bytes": "11920"
},
{
"name": "JavaScript",
"bytes": "48"
},
{
"name": "Objective-C",
"bytes": "36960"
}
],
"symlink_target": ""
} |
package com.sangam.aditya.smarthelmet;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import java.io.IOException;
import java.util.List;
public class SetDestination extends ActionBarActivity {
Long longitude;
Long latitude;
Bundle savgt= new Bundle();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_set_destination);
savgt = savedInstanceState;
//sms part
// Initialize a Location manager variable
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// If there is no network connectivity alert the user with a dialog box, prompting him/her to get net access ASAP
if(!isNetworkConnected()){
createNetErrorDialog();
}
else if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
showGPSDisabledAlertToUser();
}
}
// IT does what its name says, pretty clear I hope.
private void showGPSDisabledAlertToUser(){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("GPS is disabled in your device. Would you like to enable it?")
.setCancelable(false)
.setPositiveButton("Go to Settings Page To Enable GPS",
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
Intent callGPSSettingIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(callGPSSettingIntent);
}
});
alertDialogBuilder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
// this generates a dialog box which tells the user that the application needs a network connection
// and the user can cancel, i.e exit the application or go to settings and do the needful
protected void createNetErrorDialog() {
// builds a alert with these things in order
// the message, the title, (the boolean which decides if the dialog can be cancelled, i.e just ignored),
// the intent to be launched in case the user hits the "positive" button and the one for the "negative" button
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("You need a network connection to use this application. Please turn on mobile network or Wi-Fi in Settings.")
.setTitle("Unable to connect")
.setCancelable(false)
.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent i = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
startActivity(i);
}
}
)
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
SetDestination.this.finish();
}
}
);
// used the attributes defined above crate a dialog
AlertDialog alert = builder.create();
// Show it
alert.show();
}
//a function to check if Internet is available
public boolean isNetworkConnected(){
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni == null) {
// There are no active networks.
return false;
} else {
return true;
}
}
// As I find that the Geocoding API which exists in the android API does not
// work on all devices, and returns null on a lot of devices.
// I am therefore suggesting using the Reverse Geocoding API which returns a JSON object
// Also TODO let the user decide if this is the place he meant, offer him alternatives.
public Address get_location_from_address(String Address){
try {
List<Address> result = new Geocoder(this).getFromLocationName(Address,1);
return result.get(0);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
// Launches the google maps application with the user's desired destination
public void launch_navigation(View v){
// Get the address the user entered
EditText source = (EditText)findViewById(R.id.editTextSource);
EditText destination = (EditText)findViewById(R.id.editTextDestination);
if(destination == null || destination.getText().toString().matches("")){
Toast.makeText(this, "Please enter destination address and try again", Toast.LENGTH_SHORT).show();
return;
}
else if (source == null || source.getText().toString().matches("")){
Toast.makeText(this, "Using current location as Source Location", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse("google.navigation:q="+destination.getText().toString()));
startActivity(intent);
return;
}
// Initialize a Location manager variable
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if(!isNetworkConnected()){
Toast.makeText(this, "Please Enable Internet and try again", Toast.LENGTH_SHORT).show();
return;
}
else if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
Toast.makeText(this, "Please Enable GPS and try again", Toast.LENGTH_SHORT).show();
return;
}
Address source_address = get_location_from_address(source.getText().toString());
Address destination_address = get_location_from_address(destination.getText().toString());
if (checkFuelAvailability(source_address,destination_address)) {
final Intent intent = new Intent(Intent.ACTION_VIEW,
/** Using the web based turn by turn directions url. */
Uri.parse(
"http://maps.google.com/maps?" +
"saddr=" + String.valueOf(source_address.getLatitude()) + "," + String.valueOf(source_address.getLongitude()) +
"&daddr=" + String.valueOf(destination_address.getLatitude()) + "," + String.valueOf(destination_address.getLongitude())));
/** Setting the Class Name that should handle
* this intent. We are setting the class name to
* the class name of the native maps activity.
* Android platform recognizes this and now knows that
* we want to open up the Native Maps application to
* handle the URL. Hence it does not give the choice of
* application to the user and directly opens the
* Native Google Maps application.
*/
intent.setClassName(
"com.google.android.apps.maps",
"com.google.android.maps.MapsActivity");
startActivity(intent);
} else {
Toast.makeText(v.getContext(), "You do not have the fuel required for this journey", Toast.LENGTH_LONG).show();
}
}
private Boolean checkFuelAvailability(Address s, Address d) {
Location me = new Location("");
Location dest = new Location("");
me.setLatitude(s.getLatitude());
me.setLongitude(s.getLongitude());
dest.setLatitude(d.getLatitude());
dest.setLongitude(d.getLongitude());
float dist = me.distanceTo(dest);
SharedPreferences pref = getApplicationContext().getSharedPreferences(Home.USER_FUEL, MODE_PRIVATE);
float fuelRemaining = Float.parseFloat(pref.getString(Home.USER_FUEL_REMAINING,"0"));
// TODO Mileage is HARDCODED!!
float fuelRequired = dist / 60 ;
Log.i("DEBUG",Float.toString(fuelRemaining)+" IS the remaining fuel");
Log.i("DEBUG",Float.toString(fuelRequired)+ " IS the required fuel");
if(fuelRemaining>fuelRequired){
return Boolean.TRUE;
}
else{
return Boolean.FALSE;
}
}
@Override
public void onResume()
{
super.onResume();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_set_destination, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| {
"content_hash": "be8224438e50a06917a52b947235a62b",
"timestamp": "",
"source": "github",
"line_count": 263,
"max_line_length": 159,
"avg_line_length": 39.97338403041825,
"alnum_prop": 0.6166650813278798,
"repo_name": "Aditya8795/Smart-Bike",
"id": "d4bd9b8a3c256c079238a3d8a543bdd48115fe5e",
"size": "10513",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/java/com/sangam/aditya/smarthelmet/SetDestination.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "81196"
},
{
"name": "Python",
"bytes": "4470"
}
],
"symlink_target": ""
} |
"""
SQLAlchemy-JSONAPI Example
Colton J. Provias - [email protected]
An example of basic usage of SQLAlchemy-JSONAPI
"""
from pprint import pprint
from sqlalchemy import create_engine, Column, Integer, Unicode, UnicodeText
from sqlalchemy import ForeignKey
from sqlalchemy.orm import relationship, backref
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy_jsonapi import JSONAPIMixin, JSONAPI, as_relationship
# Start your engines...and session.
engine = create_engine('sqlite:///:memory:')
Base = declarative_base()
session = sessionmaker(bind=engine)()
# Extend the JSONAPIMixin so we can convert numerial IDs into strings.
# This is not done automatically so as to be more back-end agnostic
class APIMixin(JSONAPIMixin):
jsonapi_columns_override = {
'id': lambda self: str(self.id)
}
# Model definitions
class User(APIMixin, Base):
__tablename__ = 'users'
# We don't want the password to be sent in the response, so we exclude it.
jsonapi_columns_exclude = ['password']
id = Column(Integer, primary_key=True)
username = Column(Unicode(30))
password = Column(Unicode(30))
class Post(APIMixin, Base):
__tablename__ = 'posts'
jsonapi_relationships_include = ['my_relationship']
id = Column(Integer, primary_key=True)
title = Column(Unicode(100))
content = Column(UnicodeText)
user_id = Column(Integer, ForeignKey('users.id'))
user = relationship('User', lazy='select',
backref=backref('posts', lazy='dynamic'))
@as_relationship()
def my_relationship(self):
return session.query(User).first()
class Comment(APIMixin, Base):
__tablename__ = 'comments'
id = Column(Integer, primary_key=True)
content = Column(UnicodeText)
user_id = Column(Integer, ForeignKey('users.id'))
post_id = Column(Integer, ForeignKey('posts.id'))
user = relationship('User', lazy='joined',
backref=backref('comments', lazy='dynamic'))
post = relationship('Post', lazy='joined',
backref=backref('comments', lazy='dynamic'))
# Initialize the database and fill it with some sample data
Base.metadata.create_all(engine)
user = User(username='sampleuser', password='Secret')
post = Post(title='Sample Post',
content='Lorem ipsum dolor sit amet fakus latinus',
user=user)
comment = Comment(content='Sample comment',
user=user, post=post)
session.add(user)
session.commit()
# Create the serializer and serialize a collection.
# Note: It MUST be a list or a collection. Individual objects require
# as_collection to be False in the call to serialize().
post_serializer = JSONAPI(Post)
query = session.query(Post)
json_api_dict = post_serializer.serialize(query)
# Finally, let's see what the output is.
pprint(json_api_dict)
"""
Output from the pprint statement:
{'linked': {'comments': [{'content': 'Sample comment',
'id': '1',
'links': {'post': '1', 'user': '1'}}],
'my_relationship': [{'id': '1',
'links': {},
'username': 'sampleuser'}],
'users': [{'id': '1', 'links': {}, 'username': 'sampleuser'}]},
'meta': {},
'posts': [{'content': 'Lorem ipsum dolor sit amet fakus latinus',
'id': '1',
'links': {'comments': ['1'], 'user': '1'},
'title': 'Sample Post'}]}
"""
| {
"content_hash": "98a9b4fcf4df4d5db7d9e18945d25957",
"timestamp": "",
"source": "github",
"line_count": 106,
"max_line_length": 78,
"avg_line_length": 33.301886792452834,
"alnum_prop": 0.639943342776204,
"repo_name": "18F/sqlalchemy-jsonapi",
"id": "59c74e29e5ba93bc523430bae93b2cc58b8d2ee4",
"size": "3530",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "example.py",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "2d602f8a8abcf3ff7082658abf850821",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.307692307692308,
"alnum_prop": 0.6940298507462687,
"repo_name": "mdoering/backbone",
"id": "a980661bed10196107803e857dae7cc0a39a68e6",
"size": "172",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Bacteria/Firmicutes/Clostridia/Clostridiales/Peptococcaceae/Desulfotomaculum/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
require 'asciidoctor'
require 'test/unit'
require_relative '../lib/extensions/html_postprocessor'
class TestHtmlPostprocessor < Test::Unit::TestCase
def test_single
input = 'A single test para'
assert_equal("<div class=\"paragraph\">\n<p>A single test para\n</div>",
Asciidoctor::Document.new(input).render)
end
end
| {
"content_hash": "185d75c30e094bf223dcb8bd4a4f6d47",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 76,
"avg_line_length": 28.916666666666668,
"alnum_prop": 0.6945244956772334,
"repo_name": "bsmith-n4/jekyll_aspec",
"id": "6cddb785631c50f1352bd13c240aaea54bc4cd8f",
"size": "347",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/html_postprocessor.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "50058"
},
{
"name": "Shell",
"bytes": "131"
}
],
"symlink_target": ""
} |
using System.Text.Json;
using Azure.Core;
namespace Azure.ResourceManager.Media.Models
{
public partial class SelectVideoTrackById : IUtf8JsonSerializable
{
void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
{
writer.WriteStartObject();
writer.WritePropertyName("trackId");
writer.WriteNumberValue(TrackId);
writer.WritePropertyName("@odata.type");
writer.WriteStringValue(OdataType);
writer.WriteEndObject();
}
internal static SelectVideoTrackById DeserializeSelectVideoTrackById(JsonElement element)
{
long trackId = default;
string odataType = default;
foreach (var property in element.EnumerateObject())
{
if (property.NameEquals("trackId"))
{
trackId = property.Value.GetInt64();
continue;
}
if (property.NameEquals("@odata.type"))
{
odataType = property.Value.GetString();
continue;
}
}
return new SelectVideoTrackById(odataType, trackId);
}
}
}
| {
"content_hash": "a9b235eca02d960642b38498af9cd92f",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 97,
"avg_line_length": 32.60526315789474,
"alnum_prop": 0.5544794188861986,
"repo_name": "Azure/azure-sdk-for-net",
"id": "5622a4ec6b9a9b3d687958e27f96a1c819a2fe12",
"size": "1377",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "sdk/mediaservices/Azure.ResourceManager.Media/src/Generated/Models/SelectVideoTrackById.Serialization.cs",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
CREATE OR REPLACE FUNCTION CC_TRANSLATE (
inValue VARCHAR2)
RETURN VARCHAR2
IS
outValue VARCHAR2(200);
BEGIN
outValue := upper(inValue);
For x in (select value_in, value_out
from CC_TRANSLATORS
order by order_numb) loop
outValue := replace(outValue, x.value_in, x.value_out);
End Loop;
RETURN outValue;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RETURN null;
END;
/
| {
"content_hash": "811f24e0f0660562d3bf6e9dc9961c0a",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 61,
"avg_line_length": 23.72222222222222,
"alnum_prop": 0.6440281030444965,
"repo_name": "NCIP/clinical-connector",
"id": "968b5e3c38ea085b873b4942437320f9486de16e",
"size": "427",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "software/C3DGridService/db/db-upgrade/oracle/base-upgrade/ProcsAndFuncs/CC_Translate.sql",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Java",
"bytes": "699172"
},
{
"name": "Shell",
"bytes": "6068"
}
],
"symlink_target": ""
} |
package org.spongepowered.forge.mixin.core.world.entity.projectile;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.projectile.ThrownEnderpearl;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;
@Mixin(ThrownEnderpearl.class)
public abstract class ThrownEnderpealMixin_Forge {
@Redirect(method = "changeDimension",
at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/projectile/ThrownEnderpearl;getOwner()Lnet/minecraft/world/entity/Entity;"))
private Entity forge$preventUnsetOwnerUntilLater(final ThrownEnderpearl thrownEnderpearl) {
// This allows us to ensure the if statement after is always false
// We deal with this later (see the common mixin)
return null;
}
}
| {
"content_hash": "1ec8e35db048eae32691aee34bf10030",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 153,
"avg_line_length": 40.95238095238095,
"alnum_prop": 0.7662790697674419,
"repo_name": "SpongePowered/Sponge",
"id": "ef47ed235d97ef7f24acbf36f7365797a308a881",
"size": "2107",
"binary": false,
"copies": "1",
"ref": "refs/heads/api-8",
"path": "forge/src/mixins/java/org/spongepowered/forge/mixin/core/world/entity/projectile/ThrownEnderpealMixin_Forge.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "12489815"
},
{
"name": "Kotlin",
"bytes": "73840"
},
{
"name": "Shell",
"bytes": "70"
}
],
"symlink_target": ""
} |
.class final Lmf/org/apache/xml/serialize/ObjectFactory$ConfigurationError;
.super Ljava/lang/Error;
.source "ObjectFactory.java"
# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
value = Lmf/org/apache/xml/serialize/ObjectFactory;
.end annotation
.annotation system Ldalvik/annotation/InnerClass;
accessFlags = 0x18
name = "ConfigurationError"
.end annotation
# static fields
.field static final serialVersionUID:J = 0xd033156a03d9206L
# instance fields
.field private exception:Ljava/lang/Exception;
# direct methods
.method constructor <init>(Ljava/lang/String;Ljava/lang/Exception;)V
.locals 0
invoke-direct {p0, p1}, Ljava/lang/Error;-><init>(Ljava/lang/String;)V
iput-object p2, p0, Lmf/org/apache/xml/serialize/ObjectFactory$ConfigurationError;->exception:Ljava/lang/Exception;
return-void
.end method
# virtual methods
.method getException()Ljava/lang/Exception;
.locals 1
iget-object v0, p0, Lmf/org/apache/xml/serialize/ObjectFactory$ConfigurationError;->exception:Ljava/lang/Exception;
return-object v0
.end method
| {
"content_hash": "d066b5bab1331106e5485037aaafc245",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 119,
"avg_line_length": 25,
"alnum_prop": 0.7681818181818182,
"repo_name": "BatMan-Rom/ModdedFiles",
"id": "a4c473505517f6f817d25b897dc9bd2ec976a664",
"size": "1100",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "services.jar.out/smali_classes2/mf/org/apache/xml/serialize/ObjectFactory$ConfigurationError.smali",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "GLSL",
"bytes": "15069"
},
{
"name": "HTML",
"bytes": "139176"
},
{
"name": "Smali",
"bytes": "541934400"
}
],
"symlink_target": ""
} |
package com.effektif.workflow.api.workflow.diagram;
/**
* The two-dimensional bounding box of a BPMN diagram, or of a node on the diagram.
*/
public class Bounds {
public Point lowerRight;
public Point upperLeft;
public Bounds() {
}
public Bounds(Point upperLeft, Point lowerRight) {
this.upperLeft = upperLeft;
this.lowerRight = lowerRight;
}
public Bounds(double ulx, double uly, double lrx, double lry) {
this.upperLeft = new Point(ulx, uly);
this.lowerRight = new Point(lrx, lry);
}
public Bounds(Point upperLeft, double width, double height) {
this.upperLeft = upperLeft;
this.lowerRight = upperLeft.translate(width, height);
}
public Bounds lowerRight(Point lowerRight) {
this.lowerRight = lowerRight;
return this;
}
public Bounds upperLeft(Point upperLeft) {
this.upperLeft = upperLeft;
return this;
}
public double getWidth() {
if (upperLeft == null || lowerRight == null) {
return 0;
}
return Math.abs(upperLeft.x - lowerRight.x);
}
public double getHeight() {
if (upperLeft == null || lowerRight == null) {
return 0;
}
return Math.abs(upperLeft.y - lowerRight.y);
}
/**
* Validates this Bounds and returns true if the distance between the two points is bigger than 0.0
* and at least one of the x and y values is different than 0.0.
*/
public boolean isValid() {
// upperLeft and lowerRight must exist
if (upperLeft == null || lowerRight == null) {
return false;
}
// either of the x values must be different than 0.0
if (upperLeft.x == 0.0 && lowerRight.x == 0.0) {
return false;
}
// either of the y values must be different than 0.0
if (upperLeft.y == 0.0 && lowerRight.y == 0.0) {
return false;
}
// the distance between the two points must be bigger than 0.0
if (upperLeft.distanceTo(lowerRight) == 0.0) {
return false;
}
return true;
}
public static Bounds of(double ulx, double uly, double lrx, double lry) {
return new Bounds(ulx, uly, lrx, lry);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((lowerRight == null) ? 0 : lowerRight.hashCode());
result = prime * result + ((upperLeft == null) ? 0 : upperLeft.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Bounds other = (Bounds) obj;
if (lowerRight == null) {
if (other.lowerRight != null)
return false;
} else if (!lowerRight.equals(other.lowerRight))
return false;
if (upperLeft == null) {
if (other.upperLeft != null)
return false;
} else if (!upperLeft.equals(other.upperLeft))
return false;
return true;
}
}
| {
"content_hash": "d32632450c6866f8513bb7d1bd2db7c1",
"timestamp": "",
"source": "github",
"line_count": 114,
"max_line_length": 102,
"avg_line_length": 26.789473684210527,
"alnum_prop": 0.6024885396201702,
"repo_name": "jblankendaal/effektif",
"id": "6c99d40347a191d85fec53b948ef512fbbb53060",
"size": "3661",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "effektif-workflow-api/src/main/java/com/effektif/workflow/api/workflow/diagram/Bounds.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "407"
},
{
"name": "Java",
"bytes": "1405902"
},
{
"name": "Scala",
"bytes": "2386"
},
{
"name": "Shell",
"bytes": "4050"
}
],
"symlink_target": ""
} |
import React from 'react';
import PropTypes from 'prop-types';
import TimePickerPanel from 'rc-time-picker/lib/Panel';
import classNames from 'classnames';
import { generateShowHourMinuteSecond } from '../time-picker';
import warning from '../_util/warning';
import { getComponentLocale } from '../_util/getLocale';
declare const require: Function;
function getColumns({ showHour, showMinute, showSecond, use12Hours }) {
let column = 0;
if (showHour) {
column += 1;
}
if (showMinute) {
column += 1;
}
if (showSecond) {
column += 1;
}
if (use12Hours) {
column += 1;
}
return column;
}
export default function wrapPicker(Picker, defaultFormat?: string): any {
return class PickerWrapper extends React.Component<any, any> {
static contextTypes = {
antLocale: PropTypes.object,
};
static defaultProps = {
format: defaultFormat || 'YYYY-MM-DD',
transitionName: 'slide-up',
popupStyle: {},
onChange() {
},
onOk() {
},
onOpenChange() {
},
locale: {},
prefixCls: 'ant-calendar',
inputPrefixCls: 'ant-input',
};
handleOpenChange = (open) => {
const { onOpenChange, toggleOpen } = this.props;
onOpenChange(open);
if (toggleOpen) {
warning(
false,
'`toggleOpen` is deprecated and will be removed in the future, ' +
'please use `onOpenChange` instead, see: http://u.ant.design/date-picker-on-open-change',
);
toggleOpen({ open });
}
}
render() {
const props = this.props;
const { prefixCls, inputPrefixCls } = props;
const pickerClass = classNames({
[`${prefixCls}-picker`]: true,
});
const pickerInputClass = classNames(`${prefixCls}-picker-input`, inputPrefixCls, {
[`${inputPrefixCls}-lg`]: props.size === 'large',
[`${inputPrefixCls}-sm`]: props.size === 'small',
[`${inputPrefixCls}-disabled`]: props.disabled,
});
const locale = getComponentLocale(
props, this.context, 'DatePicker',
() => require('./locale/zh_CN'),
);
const timeFormat = (props.showTime && props.showTime.format) || 'HH:mm:ss';
const rcTimePickerProps = {
...generateShowHourMinuteSecond(timeFormat),
format: timeFormat,
use12Hours: (props.showTime && props.showTime.use12Hours),
};
const columns = getColumns(rcTimePickerProps);
const timePickerCls = `${prefixCls}-time-picker-column-${columns}`;
const timePicker = props.showTime ? (
<TimePickerPanel
{...rcTimePickerProps}
{...props.showTime}
prefixCls={`${prefixCls}-time-picker`}
className={timePickerCls}
placeholder={locale.timePickerLocale.placeholder}
transitionName="slide-up"
/>
) : null;
return (
<Picker
{...props}
pickerClass={pickerClass}
pickerInputClass={pickerInputClass}
locale={locale}
timePicker={timePicker}
onOpenChange={this.handleOpenChange}
/>
);
}
};
}
| {
"content_hash": "eacdb98d29832e6ea19ae48ea9876fef",
"timestamp": "",
"source": "github",
"line_count": 110,
"max_line_length": 99,
"avg_line_length": 28.681818181818183,
"alnum_prop": 0.593026941362916,
"repo_name": "cigar/iwiw_design",
"id": "cf1ecee3b748c1613a7e9ce5c44b68ad7c092abb",
"size": "3155",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "components/date-picker/wrapPicker.tsx",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "365499"
},
{
"name": "HTML",
"bytes": "4859"
},
{
"name": "JavaScript",
"bytes": "186347"
},
{
"name": "Shell",
"bytes": "251"
},
{
"name": "TypeScript",
"bytes": "387939"
}
],
"symlink_target": ""
} |
package com.google.cloud.deploy.v1.samples;
// [START clouddeploy_v1_generated_CloudDeploy_ListRollouts_Paged_async]
import com.google.cloud.deploy.v1.CloudDeployClient;
import com.google.cloud.deploy.v1.ListRolloutsRequest;
import com.google.cloud.deploy.v1.ListRolloutsResponse;
import com.google.cloud.deploy.v1.ReleaseName;
import com.google.cloud.deploy.v1.Rollout;
import com.google.common.base.Strings;
public class AsyncListRolloutsPaged {
public static void main(String[] args) throws Exception {
asyncListRolloutsPaged();
}
public static void asyncListRolloutsPaged() throws Exception {
// This snippet has been automatically generated and should be regarded as a code template only.
// It will require modifications to work:
// - It may require correct/in-range values for request initialization.
// - It may require specifying regional endpoints when creating the service client as shown in
// https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
try (CloudDeployClient cloudDeployClient = CloudDeployClient.create()) {
ListRolloutsRequest request =
ListRolloutsRequest.newBuilder()
.setParent(
ReleaseName.of("[PROJECT]", "[LOCATION]", "[DELIVERY_PIPELINE]", "[RELEASE]")
.toString())
.setPageSize(883849137)
.setPageToken("pageToken873572522")
.setFilter("filter-1274492040")
.setOrderBy("orderBy-1207110587")
.build();
while (true) {
ListRolloutsResponse response = cloudDeployClient.listRolloutsCallable().call(request);
for (Rollout element : response.getRolloutsList()) {
// doThingsWith(element);
}
String nextPageToken = response.getNextPageToken();
if (!Strings.isNullOrEmpty(nextPageToken)) {
request = request.toBuilder().setPageToken(nextPageToken).build();
} else {
break;
}
}
}
}
}
// [END clouddeploy_v1_generated_CloudDeploy_ListRollouts_Paged_async]
| {
"content_hash": "574803e397936878ee9ee192471841c1",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 100,
"avg_line_length": 41.05882352941177,
"alnum_prop": 0.6867239732569246,
"repo_name": "googleapis/google-cloud-java",
"id": "a5f9f27250808b5dd751dfee6ad3243528b63d03",
"size": "2689",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "java-deploy/samples/snippets/generated/com/google/cloud/deploy/v1/clouddeploy/listrollouts/AsyncListRolloutsPaged.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "2614"
},
{
"name": "HCL",
"bytes": "28592"
},
{
"name": "Java",
"bytes": "826434232"
},
{
"name": "Jinja",
"bytes": "2292"
},
{
"name": "Python",
"bytes": "200408"
},
{
"name": "Shell",
"bytes": "97954"
}
],
"symlink_target": ""
} |
/*
* Created on 20-Jan-2005
*/
package com.jboss.transaction.txinterop.proxy;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
/**
* Sax parser for rewriting the XML via the proxy.
* @author kevin
*/
public class BaseHandler implements ContentHandler
{
/**
* The next handler in the sequence.
*/
private final ContentHandler nextHandler ;
/**
* Construct the base handler.
* @param nextHandler The next content handler.
*/
protected BaseHandler(final ContentHandler nextHandler)
{
this.nextHandler = nextHandler ;
}
/**
* Set the document locator.
* @param locator The document locator.
*/
public void setDocumentLocator(final Locator locator)
{
nextHandler.setDocumentLocator(locator) ;
}
/**
* Handle the procesing instruction.
* @param target The pi target.
* @param data The pi data.
* @throws SAXException for any errors.
*/
public void processingInstruction(final String target, final String data)
throws SAXException
{
nextHandler.processingInstruction(target, data) ;
}
/**
* Start the document.
* @throws SAXException for any errors.
*/
public void startDocument()
throws SAXException
{
nextHandler.startDocument() ;
}
/**
* End the document.
* @throws SAXException for any errors.
*/
public void endDocument()
throws SAXException
{
nextHandler.endDocument() ;
}
/**
* Start a prefix mapping.
* @param prefix The namespace prefix.
* @param uri The namespace uri.
* @throws SAXException for any errors.
*/
public void startPrefixMapping(final String prefix, final String uri)
throws SAXException
{
nextHandler.startPrefixMapping(prefix, uri) ;
}
/**
* End the prefix mapping.
* @param prefix The namespace prefix.
* @throws SAXException for any errors.
*/
public void endPrefixMapping(final String prefix)
throws SAXException
{
nextHandler.endPrefixMapping(prefix) ;
}
/**
* Start an element.
* @param uri The uri.
* @param localName The local name.
* @param qName The qualified name.
* @param attributes The element attributes.
* @throws SAXException for any errors.
*/
public void startElement(final String uri, final String localName, final String qName,
final Attributes attributes)
throws SAXException
{
nextHandler.startElement(uri, localName, qName, attributes) ;
}
/**
* End an element.
* @param uri The uri.
* @param localName The local name.
* @param qName The qualified name.
* @throws SAXException for any errors.
*/
public void endElement(final String uri, final String localName, final String qName)
throws SAXException
{
nextHandler.endElement(uri, localName, qName) ;
}
/**
* Process character text.
* @param chars The character array.
* @param start The start index.
* @param length The length of this section.
* @throws SAXException for any errors.
*/
public void characters(char[] chars, int start, int length)
throws SAXException
{
nextHandler.characters(chars, start, length) ;
}
/**
* Process ignorable white space.
* @param chars The character array.
* @param start The start index.
* @param length The length of this section.
* @throws SAXException for any errors.
*/
public void ignorableWhitespace(char[] chars, int start, int length)
throws SAXException
{
nextHandler.ignorableWhitespace(chars, start, length) ;
}
/**
* Skip an entity.
* @throws SAXException for any errors.
*/
public void skippedEntity(final String name)
throws SAXException
{
nextHandler.skippedEntity(name) ;
}
/**
* Get the next handler.
* @return The next handler.
*/
protected final ContentHandler getNextHandler()
{
return nextHandler ;
}
}
| {
"content_hash": "bdc19551fa895950f99c0072d56dbca6",
"timestamp": "",
"source": "github",
"line_count": 168,
"max_line_length": 90,
"avg_line_length": 24.988095238095237,
"alnum_prop": 0.6369699857074798,
"repo_name": "nmcl/wfswarm-example-arjuna-old",
"id": "637eed5267a32bb0ed32c6a979ad6c0017233a76",
"size": "5176",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "graalvm/transactions/fork/narayana/XTS/localjunit/WSTX11-interop/src/main/java/com/jboss/transaction/txinterop/proxy/BaseHandler.java",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "6903"
}
],
"symlink_target": ""
} |
#include "Filter_Updater.h"
Filter_Updater::Filter_Updater(Model_Refiner& refiner) :
filter(parallel), _refiner(refiner) {
}
Filter_Updater::~Filter_Updater() {
}
void* Filter_Updater::operator ()(void *token) {
return _refiner.update(token);
}
| {
"content_hash": "41b8914af7596f255267fbb6daaf12cd",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 56,
"avg_line_length": 19.76923076923077,
"alnum_prop": 0.6926070038910506,
"repo_name": "shravanmn/Yahoo_LDA",
"id": "af61bd538f4b1724b12d1efce39f1ec236069c51",
"size": "1136",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "src/commons/TopicLearner/Filter_Updater.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
describe EvilEvents::Core::Events::AbstractEvent do
it_behaves_like 'dispatchable interface' do
let(:dispatchable) { Class.new(described_class) }
end
it_behaves_like 'manageable interface' do
let(:manageable) { Class.new(described_class) }
end
it_behaves_like 'observable interface' do
let(:observable) { Class.new(described_class) }
end
it_behaves_like 'serializable interface' do
let(:serializable) { Class.new(described_class).new }
end
it_behaves_like 'payloadable interface' do
let(:payloadable_abstraction) { described_class }
end
it_behaves_like 'metadata extendable interface' do
let(:metadata_extendable_abstraction) { described_class }
end
it_behaves_like 'metadata extendable interface' do
let(:metadata_extendable_abstraction) { described_class }
end
it_behaves_like 'class signature interface' do
let(:event_class) { described_class }
end
it_behaves_like 'hookable interface' do
let(:hookable) { Class.new(described_class) }
end
it_behaves_like 'type aliasing interface' do
let(:pseudo_identifiable) { Class.new(described_class) }
describe 'domain instance interface' do
describe '#type' do
it 'returns previously defined string alias of event type' do
event_class = Class.new(pseudo_identifiable) { type 'test_specification_event' }
expect(event_class.type).to eq('test_specification_event')
end
specify ':type attribute works correctly (with #type alias)' do
event_class = Class.new(pseudo_identifiable) do
type 'non_misconfigurated_event'
payload :type
end
event_instance = event_class.new(payload: { type: 'kek' })
expect(event_instance.type).to eq('non_misconfigurated_event')
expect(event_instance.payload[:type]).to eq('kek')
end
end
end
end
# TODO: dry with <payload entity component>
it_behaves_like 'metadata entity component' do
let(:metadata_abstraction) { described_class }
describe 'domain instance interface' do
describe '#metadata' do
let(:event_instance) do
Class.new(metadata_abstraction) do
metadata :sum, EvilEvents::Types::Strict::Integer.default(proc { 123_456 })
metadata :sys, EvilEvents::Types::String
metadata :type, EvilEvents::Types::Strict::Symbol.default(proc { :lols })
end.new(metadata: { sys: 'lol' })
end
it 'metadata can be received via #metadata method in a hash format' do
expect(event_instance.metadata).to match(sum: 123_456, sys: 'lol', type: :lols)
end
it 'returned hash object doesnt affects any event attributes or #metadata result' do
expect(event_instance.metadata.object_id).not_to eq(event_instance.metadata.object_id)
end
end
end
end
# TODO: dry with <metadata entity component>
it_behaves_like 'payload entity component' do
let(:payload_abstraction) { described_class }
describe 'domain instance interface' do
describe '#payload' do
let(:event_instance) do
Class.new(payload_abstraction) do
payload :sum, EvilEvents::Types::Strict::Integer.default(proc { 123_456 })
payload :sys, EvilEvents::Types::String
payload :type, EvilEvents::Types::Strict::Symbol.default(proc { :lols })
end.new(payload: { sys: 'lol' })
end
it 'all defined attributes can be received via #payload method in a hash format' do
expect(event_instance.payload).to match(sum: 123_456, sys: 'lol', type: :lols)
end
it 'returned hash object doesnt affects any event attributes or #payload result' do
expect(event_instance.payload.object_id).not_to eq(event_instance.payload.object_id)
end
end
end
end
describe 'instance attributes' do
describe '#id' do
specify 'each event instance has own #id' do
uniq_events = Array.new(100) { Class.new(described_class).new }.tap do |events|
events.uniq!(&:id)
end
expect(uniq_events.size).to eq(100)
end
end
end
end
| {
"content_hash": "e881da45977e5ae0397988161ef2f52f",
"timestamp": "",
"source": "github",
"line_count": 124,
"max_line_length": 96,
"avg_line_length": 33.87903225806452,
"alnum_prop": 0.654606046179481,
"repo_name": "0exp/evil_events",
"id": "279bc52103f80cdc8741456223122de9944fd095",
"size": "4232",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/units/evil_events/core/events/abstract_event_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "463816"
},
{
"name": "Shell",
"bytes": "131"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML>
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (11.0.5) on Thu Mar 18 22:21:49 NZDT 2021 -->
<title>Uses of Class io.ebean.config.dbplatform.DbType (ebean api 12.8.0 API)</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="dc.created" content="2021-03-18">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../../jquery/jquery-ui.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script>
<script type="text/javascript" src="../../../../../jquery/jszip/dist/jszip.min.js"></script>
<script type="text/javascript" src="../../../../../jquery/jszip-utils/dist/jszip-utils.min.js"></script>
<!--[if IE]>
<script type="text/javascript" src="../../../../../jquery/jszip-utils/dist/jszip-utils-ie.min.js"></script>
<![endif]-->
<script type="text/javascript" src="../../../../../jquery/jquery-3.4.1.js"></script>
<script type="text/javascript" src="../../../../../jquery/jquery-ui.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class io.ebean.config.dbplatform.DbType (ebean api 12.8.0 API)";
}
}
catch(err) {
}
//-->
var pathtoroot = "../../../../../";
var useModuleDirectories = true;
loadScripts(document, 'script');</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<header role="banner">
<nav role="navigation">
<div class="fixedNav">
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a id="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a id="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../index.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../DbType.html" title="enum in io.ebean.config.dbplatform">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses.html">All Classes</a></li>
</ul>
<ul class="navListSearch">
<li><label for="search">SEARCH:</label>
<input type="text" id="search" value="search" disabled="disabled">
<input type="reset" id="reset" value="reset" disabled="disabled">
</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>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
</div>
<a id="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
</div>
<div class="navPadding"> </div>
<script type="text/javascript"><!--
$('.navPadding').css('padding-top', $('.fixedNav').css("height"));
//-->
</script>
</nav>
</header>
<main role="main">
<div class="header">
<h2 title="Uses of Class io.ebean.config.dbplatform.DbType" class="title">Uses of Class<br>io.ebean.config.dbplatform.DbType</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary">
<caption><span>Packages that use <a href="../DbType.html" title="enum in io.ebean.config.dbplatform">DbType</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<th class="colFirst" scope="row"><a href="#io.ebean.config">io.ebean.config</a></th>
<td class="colLast">
<div class="block">Configuration settings for Database construction</div>
</td>
</tr>
<tr class="rowColor">
<th class="colFirst" scope="row"><a href="#io.ebean.config.dbplatform">io.ebean.config.dbplatform</a></th>
<td class="colLast">
<div class="block">Database platform specific support</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList">
<section role="region"><a id="io.ebean.config">
<!-- -->
</a>
<h3>Uses of <a href="../DbType.html" title="enum in io.ebean.config.dbplatform">DbType</a> in <a href="../../package-summary.html">io.ebean.config</a></h3>
<table class="useSummary">
<caption><span>Methods in <a href="../../package-summary.html">io.ebean.config</a> that return <a href="../DbType.html" title="enum in io.ebean.config.dbplatform">DbType</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colSecond" scope="col">Method</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../DbType.html" title="enum in io.ebean.config.dbplatform">DbType</a></code></td>
<th class="colSecond" scope="row"><span class="typeNameLabel">CustomDbTypeMapping.</span><code><span class="memberNameLink"><a href="../../CustomDbTypeMapping.html#getType()">getType</a></span>()</code></th>
<td class="colLast">
<div class="block">Return the DB type the mapping applies to.</div>
</td>
</tr>
</tbody>
</table>
<table class="useSummary">
<caption><span>Methods in <a href="../../package-summary.html">io.ebean.config</a> with parameters of type <a href="../DbType.html" title="enum in io.ebean.config.dbplatform">DbType</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colSecond" scope="col">Method</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<th class="colSecond" scope="row"><span class="typeNameLabel">DatabaseConfig.</span><code><span class="memberNameLink"><a href="../../DatabaseConfig.html#addCustomMapping(io.ebean.config.dbplatform.DbType,java.lang.String)">addCustomMapping</a></span>​(<a href="../DbType.html" title="enum in io.ebean.config.dbplatform">DbType</a> type,
<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang" class="externalLink">String</a> columnDefinition)</code></th>
<td class="colLast">
<div class="block">Add a custom type mapping that applies to all platforms.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<th class="colSecond" scope="row"><span class="typeNameLabel">DatabaseConfig.</span><code><span class="memberNameLink"><a href="../../DatabaseConfig.html#addCustomMapping(io.ebean.config.dbplatform.DbType,java.lang.String,io.ebean.annotation.Platform)">addCustomMapping</a></span>​(<a href="../DbType.html" title="enum in io.ebean.config.dbplatform">DbType</a> type,
<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang" class="externalLink">String</a> columnDefinition,
io.ebean.annotation.Platform platform)</code></th>
<td class="colLast">
<div class="block">Add a custom type mapping.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<th class="colSecond" scope="row"><span class="typeNameLabel">PlatformConfig.</span><code><span class="memberNameLink"><a href="../../PlatformConfig.html#addCustomMapping(io.ebean.config.dbplatform.DbType,java.lang.String)">addCustomMapping</a></span>​(<a href="../DbType.html" title="enum in io.ebean.config.dbplatform">DbType</a> type,
<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang" class="externalLink">String</a> columnDefinition)</code></th>
<td class="colLast">
<div class="block">Add a custom type mapping that applies to all platforms.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<th class="colSecond" scope="row"><span class="typeNameLabel">PlatformConfig.</span><code><span class="memberNameLink"><a href="../../PlatformConfig.html#addCustomMapping(io.ebean.config.dbplatform.DbType,java.lang.String,io.ebean.annotation.Platform)">addCustomMapping</a></span>​(<a href="../DbType.html" title="enum in io.ebean.config.dbplatform">DbType</a> type,
<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang" class="externalLink">String</a> columnDefinition,
io.ebean.annotation.Platform platform)</code></th>
<td class="colLast">
<div class="block">Add a custom type mapping.</div>
</td>
</tr>
</tbody>
</table>
<table class="useSummary">
<caption><span>Constructors in <a href="../../package-summary.html">io.ebean.config</a> with parameters of type <a href="../DbType.html" title="enum in io.ebean.config.dbplatform">DbType</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Constructor</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="../../CustomDbTypeMapping.html#%3Cinit%3E(io.ebean.config.dbplatform.DbType,java.lang.String)">CustomDbTypeMapping</a></span>​(<a href="../DbType.html" title="enum in io.ebean.config.dbplatform">DbType</a> type,
<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang" class="externalLink">String</a> columnDefinition)</code></th>
<td class="colLast">
<div class="block">Create a mapping that should apply to all the database platforms.</div>
</td>
</tr>
<tr class="rowColor">
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="../../CustomDbTypeMapping.html#%3Cinit%3E(io.ebean.config.dbplatform.DbType,java.lang.String,io.ebean.annotation.Platform)">CustomDbTypeMapping</a></span>​(<a href="../DbType.html" title="enum in io.ebean.config.dbplatform">DbType</a> type,
<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang" class="externalLink">String</a> columnDefinition,
io.ebean.annotation.Platform platform)</code></th>
<td class="colLast">
<div class="block">Create a mapping.</div>
</td>
</tr>
</tbody>
</table>
</section>
</li>
<li class="blockList">
<section role="region"><a id="io.ebean.config.dbplatform">
<!-- -->
</a>
<h3>Uses of <a href="../DbType.html" title="enum in io.ebean.config.dbplatform">DbType</a> in <a href="../package-summary.html">io.ebean.config.dbplatform</a></h3>
<table class="useSummary">
<caption><span>Methods in <a href="../package-summary.html">io.ebean.config.dbplatform</a> that return <a href="../DbType.html" title="enum in io.ebean.config.dbplatform">DbType</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colSecond" scope="col">Method</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>static <a href="../DbType.html" title="enum in io.ebean.config.dbplatform">DbType</a></code></td>
<th class="colSecond" scope="row"><span class="typeNameLabel">DbType.</span><code><span class="memberNameLink"><a href="../DbType.html#valueOf(java.lang.String)">valueOf</a></span>​(<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang" class="externalLink">String</a> name)</code></th>
<td class="colLast">
<div class="block">Returns the enum constant of this type with the specified name.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static <a href="../DbType.html" title="enum in io.ebean.config.dbplatform">DbType</a>[]</code></td>
<th class="colSecond" scope="row"><span class="typeNameLabel">DbType.</span><code><span class="memberNameLink"><a href="../DbType.html#values()">values</a></span>()</code></th>
<td class="colLast">
<div class="block">Returns an array containing the constants of this enum type, in
the order they are declared.</div>
</td>
</tr>
</tbody>
</table>
<table class="useSummary">
<caption><span>Methods in <a href="../package-summary.html">io.ebean.config.dbplatform</a> with parameters of type <a href="../DbType.html" title="enum in io.ebean.config.dbplatform">DbType</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colSecond" scope="col">Method</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../DbPlatformType.html" title="class in io.ebean.config.dbplatform">DbPlatformType</a></code></td>
<th class="colSecond" scope="row"><span class="typeNameLabel">DbPlatformTypeMapping.</span><code><span class="memberNameLink"><a href="../DbPlatformTypeMapping.html#get(io.ebean.config.dbplatform.DbType)">get</a></span>​(<a href="../DbType.html" title="enum in io.ebean.config.dbplatform">DbType</a> dbType)</code></th>
<td class="colLast">
<div class="block">Return the type for a given jdbc type.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<th class="colSecond" scope="row"><span class="typeNameLabel">DbPlatformTypeMapping.</span><code><span class="memberNameLink"><a href="../DbPlatformTypeMapping.html#put(io.ebean.config.dbplatform.DbType,io.ebean.config.dbplatform.DbPlatformType)">put</a></span>​(<a href="../DbType.html" title="enum in io.ebean.config.dbplatform">DbType</a> type,
<a href="../DbPlatformType.html" title="class in io.ebean.config.dbplatform">DbPlatformType</a> platformType)</code></th>
<td class="colLast">
<div class="block">Override the type for a given JDBC type.</div>
</td>
</tr>
</tbody>
</table>
</section>
</li>
</ul>
</li>
</ul>
</div>
</main>
<footer role="contentinfo">
<nav role="navigation">
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a id="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a id="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../index.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../DbType.html" title="enum in io.ebean.config.dbplatform">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses.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>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
</div>
<a id="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</nav>
<p class="legalCopy"><small>Copyright © 2021. All rights reserved.</small></p>
</footer>
</body>
</html>
| {
"content_hash": "639f7a7a616f0d48bd917c8df2bdfded",
"timestamp": "",
"source": "github",
"line_count": 328,
"max_line_length": 377,
"avg_line_length": 48.8719512195122,
"alnum_prop": 0.6752339363693075,
"repo_name": "ebean-orm/ebean-orm.github.io",
"id": "e0cf3cfc96f18219d5f3baee7a4a1450e44e1a06",
"size": "16030",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "apidoc/12/io/ebean/config/dbplatform/class-use/DbType.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "133613"
},
{
"name": "HTML",
"bytes": "49047496"
},
{
"name": "Java",
"bytes": "2615"
},
{
"name": "JavaScript",
"bytes": "74774"
},
{
"name": "Kotlin",
"bytes": "1347"
},
{
"name": "Shell",
"bytes": "1829"
}
],
"symlink_target": ""
} |
package org.sti.jagu;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.*;
import java.io.IOException;
import java.net.URI;
/**
* Created by stitakis on 30.05.15.
*/
public interface RepositoryManager {
Git cloneRepository(URI remoteRepo) throws GitAPIException;
Git cloneRemoteRepository(URI remoteRepo) throws GitAPIException;
boolean updateAvailable() throws IOException, GitAPIException;
boolean update(boolean resetFirst) throws IOException, GitAPIException;
void addUpdateAvailableListener(UpdateAvailableListener updateAvailableListener);
boolean localRepositoryExists() throws IOException;
}
| {
"content_hash": "e345309b3e9f526d691eb2fa59252492",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 85,
"avg_line_length": 27.166666666666668,
"alnum_prop": 0.7898773006134969,
"repo_name": "stitakis/jagu",
"id": "e771dd77fe1f0ac1741cc900e9230d77afff3f36",
"size": "652",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/java/launcher/org/sti/jagu/RepositoryManager.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "26913"
}
],
"symlink_target": ""
} |
namespace {
//"This object file does not define any previously undefined public symbols, so it will not be used by any link operation that consumes this library"
int dummy_to_avoid_msvc_linker_warning_LNK4221;
}
#endif
| {
"content_hash": "74146bb1aaff38dd6b3806a6eda0965c",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 150,
"avg_line_length": 44.2,
"alnum_prop": 0.7828054298642534,
"repo_name": "TyRoXx/silicium",
"id": "d39e7b715e9cf28d9a1bc8a4c3d664c91d5c8026",
"size": "277",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test_includes/sources/make_destructor.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "559514"
},
{
"name": "CMake",
"bytes": "18089"
},
{
"name": "Python",
"bytes": "546"
}
],
"symlink_target": ""
} |
package main
import (
"fmt"
"io/ioutil"
"net/http"
"os"
"os/exec"
"strings"
"time"
"github.com/go-check/check"
)
type testCondition func() bool
type testRequirement struct {
Condition testCondition
SkipMessage string
}
// List test requirements
var (
DaemonIsWindows = testRequirement{
func() bool { return daemonPlatform == "windows" },
"Test requires a Windows daemon",
}
DaemonIsLinux = testRequirement{
func() bool { return daemonPlatform == "linux" },
"Test requires a Linux daemon",
}
NotArm = testRequirement{
func() bool { return os.Getenv("DOCKER_ENGINE_GOARCH") != "arm" },
"Test requires a daemon not running on ARM",
}
SameHostDaemon = testRequirement{
func() bool { return isLocalDaemon },
"Test requires docker daemon to run on the same machine as CLI",
}
UnixCli = testRequirement{
func() bool { return isUnixCli },
"Test requires posix utilities or functionality to run.",
}
ExecSupport = testRequirement{
func() bool { return supportsExec },
"Test requires 'docker exec' capabilities on the tested daemon.",
}
Network = testRequirement{
func() bool {
// Set a timeout on the GET at 15s
var timeout = time.Duration(15 * time.Second)
var url = "https://hub.docker.com"
client := http.Client{
Timeout: timeout,
}
resp, err := client.Get(url)
if err != nil && strings.Contains(err.Error(), "use of closed network connection") {
panic(fmt.Sprintf("Timeout for GET request on %s", url))
}
if resp != nil {
resp.Body.Close()
}
return err == nil
},
"Test requires network availability, environment variable set to none to run in a non-network enabled mode.",
}
Apparmor = testRequirement{
func() bool {
buf, err := ioutil.ReadFile("/sys/module/apparmor/parameters/enabled")
return err == nil && len(buf) > 1 && buf[0] == 'Y'
},
"Test requires apparmor is enabled.",
}
RegistryHosting = testRequirement{
func() bool {
// for now registry binary is built only if we're running inside
// container through `make test`. Figure that out by testing if
// registry binary is in PATH.
_, err := exec.LookPath(v2binary)
return err == nil
},
fmt.Sprintf("Test requires an environment that can host %s in the same host", v2binary),
}
NotaryHosting = testRequirement{
func() bool {
// for now notary binary is built only if we're running inside
// container through `make test`. Figure that out by testing if
// notary-server binary is in PATH.
_, err := exec.LookPath(notaryBinary)
return err == nil
},
fmt.Sprintf("Test requires an environment that can host %s in the same host", notaryBinary),
}
NotOverlay = testRequirement{
func() bool {
cmd := exec.Command("grep", "^overlay / overlay", "/proc/mounts")
if err := cmd.Run(); err != nil {
return true
}
return false
},
"Test requires underlying root filesystem not be backed by overlay.",
}
IPv6 = testRequirement{
func() bool {
cmd := exec.Command("test", "-f", "/proc/net/if_inet6")
if err := cmd.Run(); err != nil {
return true
}
return false
},
"Test requires support for IPv6",
}
NotGCCGO = testRequirement{
func() bool {
out, err := exec.Command("go", "version").Output()
if err == nil && strings.Contains(string(out), "gccgo") {
return false
}
return true
},
"Test requires native Golang compiler instead of GCCGO",
}
NotUserNamespace = testRequirement{
func() bool {
root := os.Getenv("DOCKER_REMAP_ROOT")
if root != "" {
return false
}
return true
},
"Test cannot be run when remapping root",
}
)
// testRequires checks if the environment satisfies the requirements
// for the test to run or skips the tests.
func testRequires(c *check.C, requirements ...testRequirement) {
for _, r := range requirements {
if !r.Condition() {
fmt.Printf("\n [Skip] - %s", r.SkipMessage)
c.Skip(r.SkipMessage)
}
}
}
| {
"content_hash": "fa0b59cce6c133932173d2e06fe8e6b9",
"timestamp": "",
"source": "github",
"line_count": 148,
"max_line_length": 111,
"avg_line_length": 26.60135135135135,
"alnum_prop": 0.6631953263906528,
"repo_name": "hyperhq/hypercli",
"id": "7d07c125ccf681ace024bdad340a6c40825b8a49",
"size": "3937",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "integration-cli/requirements.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "3652"
},
{
"name": "Dockerfile",
"bytes": "38641"
},
{
"name": "Go",
"bytes": "4407418"
},
{
"name": "Makefile",
"bytes": "5344"
},
{
"name": "PowerShell",
"bytes": "5978"
},
{
"name": "Shell",
"bytes": "375483"
},
{
"name": "Vim script",
"bytes": "1332"
}
],
"symlink_target": ""
} |
using System;
using System.Linq;
using log4net;
using PostSharp.Aspects;
namespace FP.PostSharpSamples.DAL
{
[Serializable]
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property, Inherited = true)]
public class WrapDALExceptionAspect : OnExceptionAspect
{
[NonSerialized]
private static ILog Logger = LogManager.GetLogger(typeof(WrapDALExceptionAspect));
public override void OnException(MethodExecutionArgs args)
{
Logger.Error(string.Format("DAL error in method {0} Arguments {1}", args.Method.Name,
string.Join(";", args.Arguments.Select(x => x == null ? "<null>" : x.ToString()).ToArray())), args.Exception);
throw new DALException(args.Method.Name, args.Exception, args.Arguments.ToArray());
}
}
}
| {
"content_hash": "bfc2200e5fe8845d6c03bb876651d576",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 144,
"avg_line_length": 39.68181818181818,
"alnum_prop": 0.6907216494845361,
"repo_name": "fpommerening/PostSharpSamples",
"id": "6afc0ae9edbf7c3bb89e265b7e9546033091a546",
"size": "875",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "WrapException/FP.PostSharpSamples.DAL/WrapDALExceptionAspect.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "106"
},
{
"name": "C#",
"bytes": "127645"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE ldml SYSTEM "../../common/dtd/ldml.dtd">
<ldml>
<identity>
<version number="$Revision: 1.51 $"/>
<generation date="$Date: 2009/05/05 23:06:34 $"/>
<language type="ar"/>
<territory type="SA"/>
</identity>
<localeDisplayNames>
<scripts>
<script type="Ital">اللأيطالية القديمة</script>
</scripts>
</localeDisplayNames>
<dates>
<calendars>
<calendar type="gregorian">
<days>
<dayContext type="format">
<dayWidth type="abbreviated">
<day type="sun">الأحد</day>
<day type="mon">الاثنين</day>
<day type="tue">الثلاثاء</day>
<day type="wed">الأربعاء</day>
<day type="thu">الخميس</day>
<day type="fri">الجمعة</day>
<day type="sat">السبت</day>
</dayWidth>
</dayContext>
</days>
</calendar>
</calendars>
</dates>
<numbers>
<decimalFormats>
<decimalFormatLength>
<decimalFormat>
<pattern>#0.###;#0.###-</pattern>
</decimalFormat>
</decimalFormatLength>
</decimalFormats>
<currencyFormats>
<currencyFormatLength>
<currencyFormat>
<pattern>¤#0.00</pattern>
</currencyFormat>
</currencyFormatLength>
</currencyFormats>
</numbers>
</ldml>
| {
"content_hash": "6d130009a7d645e3395a5ce8df5697b5",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 51,
"avg_line_length": 24.62,
"alnum_prop": 0.6108854589764419,
"repo_name": "markdev/markandkitty",
"id": "cd85b30e5bb7348e3999ba46cdb633d908d7ef8d",
"size": "1294",
"binary": false,
"copies": "11",
"ref": "refs/heads/master",
"path": "concrete/libraries/3rdparty/Zend/Locale/Data/ar_SA.xml",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
"use strict";
exports.TEST_COMPLETE = 'TEST_COMPLETE';
exports.TEST_LOAD = 'TEST_LOAD';
exports.TEST_RESULT = 'TEST_RESULT';
exports.TEST_RUN = 'TEST_RUN';
//# sourceMappingURL=types.js.map | {
"content_hash": "e3ba812e861ebd5846899a51705e0c70",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 40,
"avg_line_length": 31.5,
"alnum_prop": 0.7248677248677249,
"repo_name": "coderoad/core-coderoad",
"id": "dcc02972372214ca657e98e01eb86d554e725c4f",
"size": "189",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/modules/tests/types.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "5057"
},
{
"name": "HTML",
"bytes": "63219"
},
{
"name": "JavaScript",
"bytes": "5512"
},
{
"name": "TypeScript",
"bytes": "115133"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Consp. fl. afric. 5:774. 1894
#### Original name
null
### Remarks
null | {
"content_hash": "fdc1731aa4dea70cf169496b6b341703",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 12.23076923076923,
"alnum_prop": 0.6855345911949685,
"repo_name": "mdoering/backbone",
"id": "0579ee13a818a4a0e818f00f6a7cad1a44f3a068",
"size": "228",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Liliopsida/Poales/Poaceae/Setaria/Setaria nigrirostris/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
set -euxo pipefail
export GHCVER=8.6.1
# Download and unpack the stack executable
mkdir -p ~/.local/bin
export PATH=$HOME/.local/bin:$PATH
curl -L https://www.stackage.org/stack/linux-x86_64 | tar xz --wildcards --strip-components=1 -C ~/.local/bin '*/stack'
# Get stackage-curator
wget https://s3.amazonaws.com/stackage-travis/stackage-curator/stackage-curator.bz2
bunzip2 stackage-curator.bz2
chmod +x stackage-curator
mv stackage-curator ~/.local/bin
# Install GHC
stack setup $GHCVER
# Update the index
stack update
# Check
exec stack --resolver ghc-$GHCVER exec stackage-curator check
| {
"content_hash": "3ddef4cd011e36f6e85b076374c499cd",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 119,
"avg_line_length": 25.91304347826087,
"alnum_prop": 0.7600671140939598,
"repo_name": "Shimuuar/stackage",
"id": "27c860e09d40fff13b811a80a692d28c23ecd883",
"size": "617",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "etc/ci-script.sh",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "441"
},
{
"name": "Emacs Lisp",
"bytes": "154"
},
{
"name": "Haskell",
"bytes": "475"
},
{
"name": "Shell",
"bytes": "21397"
}
],
"symlink_target": ""
} |
from JumpScale import j
import JumpScale.baselib.redis
from CmdRouter import CmdRouter
class CmdRouterFactory:
"""
"""
def get(self,path):
return CmdRouter(path)
| {
"content_hash": "2087a657c288599d316efef2be48d987",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 15.615384615384615,
"alnum_prop": 0.6354679802955665,
"repo_name": "Jumpscale/jumpscale6_core",
"id": "ce1b67f9a8e87a2d7cf2ba31639fb6e9d2f8a33b",
"size": "203",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/JumpScale/baselib/cmdrouter/CmdRouterFactory.py",
"mode": "33261",
"license": "bsd-2-clause",
"language": [
{
"name": "CSS",
"bytes": "3681"
},
{
"name": "HTML",
"bytes": "11738"
},
{
"name": "JavaScript",
"bytes": "70132"
},
{
"name": "Lua",
"bytes": "2162"
},
{
"name": "Python",
"bytes": "5848017"
},
{
"name": "Shell",
"bytes": "7692"
}
],
"symlink_target": ""
} |
name 'postfix'
maintainer 'Chef Software, Inc.'
maintainer_email '[email protected]'
license 'Apache-2.0'
description 'Installs and configures postfix for client or outbound relayhost, or to do SASL auth'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version '5.1.1'
recipe 'postfix', 'Installs and configures postfix'
recipe 'postfix::sasl_auth', 'Set up postfix to auth to a server with sasl'
recipe 'postfix::aliases', 'Manages /etc/aliases'
recipe 'postfix::transports', 'Manages /etc/postfix/transport'
recipe 'postfix::access', 'Manages /etc/postfix/access'
recipe 'postfix::virtual_aliases', 'Manages /etc/postfix/virtual'
recipe 'postfix::client', 'Searches for the relayhost based on an attribute'
recipe 'postfix::server', 'Sets the mail_type attribute to master'
recipe 'postfix::maps', 'Manages any number of any type postfix lookup tables'
%w(ubuntu debian redhat centos amazon oracle scientific smartos fedora).each do |os|
supports os
end
source_url 'https://github.com/chef-cookbooks/postfix'
issues_url 'https://github.com/chef-cookbooks/postfix/issues'
chef_version '>= 12.1' if respond_to?(:chef_version)
| {
"content_hash": "725549fe2507ac6e6ae738e425ffe243",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 98,
"avg_line_length": 46.24,
"alnum_prop": 0.7621107266435986,
"repo_name": "mawatech/postfix",
"id": "4c5c70ced6943c0982efeae29a86c7ffdd7c6488",
"size": "1156",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "metadata.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "8203"
},
{
"name": "Ruby",
"bytes": "53267"
}
],
"symlink_target": ""
} |
module Course::Assessment::Answer::ProgrammingTestCaseHelper
# Get a hint message. Use the one from test_result if available, else fallback to the one from
# the test case.
#
# @param [Course::Assessment::Question::ProgrammingTestCase] The test case
# @param [Course::Assessment::Answer::ProgrammingAutoGradingTestResult] The test result
# @return [String] The hint, or an empty string if there isn't one
def get_hint(test_case, test_case_result)
hint = test_case_result.messages['hint'] if test_case_result
hint ||= test_case.hint
hint || ''
end
# Get the output message for the tutors to see when grading. Use the output meta attribute if
# available, else fallback to the failure message, error message, and finally empty string.
#
# @param [Course::Assessment::Answer::ProgrammingAutoGradingTestResult] The test result
# @return [String] The output, failure message, error message or empty string
# if the previous 3 don't exist.
def get_output(test_case_result)
if test_case_result
output = test_case_result.messages['output']
output = test_case_result.messages['failure'] if output.blank?
output = test_case_result.messages['error'] if output.blank?
end
output || ''
end
# If the test case type has a failed test case, return the first one.
#
# @param [Hash] test_cases_by_type The test cases and their results keyed by type
# @return [Hash] Failed test case and its result, if any
def get_failed_test_cases_by_type(test_cases_and_results)
{}.tap do |result|
test_cases_and_results.each do |test_case_type, test_cases_and_results_of_type|
result[test_case_type] = get_first_failed_test(test_cases_and_results_of_type)
end
end
end
# Organize the test cases and test results into a hash, keyed by test case type.
# If there is no test result, the test case key points to nil.
# nil is needed to make sure test cases are still displayed before they have a test result.
# Currently test_cases are ordered by sorting on the identifier of the ProgrammingTestCase.
# e.g. { 'public_test': { test_case_1: result_1, test_case_2: result_2, test_case_3: nil },
# 'private_test': { priv_case_1: priv_result_1 },
# 'evaluation_test': { eval_case1: eval_result_1 } }
#
# @param [Hash] test_cases_by_type The test cases keyed by type
# @param [Course::Assessment::Answer::ProgrammingAutoGrading] auto_grading Auto grading object
# @return [Hash] The hash structure described above
def get_test_cases_and_results(test_cases_by_type, auto_grading)
results_hash = auto_grading ? auto_grading.test_results.group_by(&:test_case) : {}
test_cases_by_type.each do |type, test_cases|
test_cases_by_type[type] =
test_cases.map { |test_case| [test_case, results_hash[test_case]&.first] }.
sort_by { |test_case, _| test_case.identifier }.to_h
end
end
private
# Return a hash of the first failing test case and its test result
#
# @param [Hash] test_cases_and_results_of_type A hash of test cases and results keyed by type
# @return [Hash] the failed test case and result, nil if all tests passed
def get_first_failed_test(test_cases_and_results_of_type)
test_cases_and_results_of_type.each do |test_case, test_result|
return [[test_case, test_result]].to_h if test_result && !test_result.passed?
end
nil
end
end
| {
"content_hash": "611857b56d70db20a59fca626219d5a3",
"timestamp": "",
"source": "github",
"line_count": 73,
"max_line_length": 96,
"avg_line_length": 46.9041095890411,
"alnum_prop": 0.6977219626168224,
"repo_name": "cysjonathan/coursemology2",
"id": "d8ea0bf4dfe59dad382797a24cd1d26fbd67c287",
"size": "3454",
"binary": false,
"copies": "2",
"ref": "refs/heads/group",
"path": "app/helpers/course/assessment/answer/programming_test_case_helper.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "20648"
},
{
"name": "HTML",
"bytes": "158329"
},
{
"name": "JavaScript",
"bytes": "55522"
},
{
"name": "Ruby",
"bytes": "1696355"
}
],
"symlink_target": ""
} |
OctoClient (Github API)
=======================
A ruby gem for accessing the Github API - provides extensive stubbing support
Distributed under the MIT license - see LICENSE file for details
| {
"content_hash": "8ef2af768ff2342fbf0f6abbb120737d",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 77,
"avg_line_length": 32.166666666666664,
"alnum_prop": 0.7046632124352331,
"repo_name": "tansaku/octoclient",
"id": "0c4413f666aadbc2fd28b08abbb8f597392305b5",
"size": "193",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "25976"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Licensed to the Apache Software Foundation (ASF) under one
~ or more contributor license agreements. See the NOTICE file
~ distributed with this work for additional information
~ regarding copyright ownership. The ASF licenses this file
~ to you under the Apache License, Version 2.0 (the
~ "License"); you may not use this file except in compliance
~ with the License. You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>druid-website</artifactId>
<name>druid-website</name>
<description>Website for druid.apache.org</description>
<parent>
<groupId>org.apache.druid</groupId>
<artifactId>druid</artifactId>
<version>0.22.0-SNAPSHOT</version>
</parent>
<properties>
<!-- src repo of druid website, the artifacts of this build will be placed here -->
<website.src>../../druid-website-src</website.src>
<!--
'version' of website to build, by default it is the Druid version we are building, but can be set explicitly
to stage documentation for an unreleased version
-->
<website.version>${project.parent.version}</website.version>
<node.version>v10.24.1</node.version>
<npm.version>6.14.12</npm.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>com.github.eirslett</groupId>
<artifactId>frontend-maven-plugin</artifactId>
<executions>
<execution>
<id>install-node-and-npm</id>
<goals>
<goal>install-node-and-npm</goal>
</goals>
<configuration>
<nodeVersion>${node.version}</nodeVersion>
<npmVersion>${npm.version}</npmVersion>
<workingDirectory>${project.build.directory}</workingDirectory>
<installDirectory>${project.build.directory}</installDirectory>
</configuration>
</execution>
<execution>
<id>npm-install</id>
<goals>
<goal>npm</goal>
</goals>
<configuration>
<arguments>ci</arguments>
<installDirectory>${project.build.directory}</installDirectory>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<executions>
<execution>
<id>build-docs</id>
<phase>compile</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<environmentVariables><PATH>${project.build.directory}/node:${env.PATH}</PATH></environmentVariables>
<executable>script/build-to-docs</executable>
<arguments>
<argument>${website.version}</argument>
<argument>${website.version}</argument>
<argument>${website.src}</argument>
</arguments>
</configuration>
</execution>
<execution>
<id>build-latest-docs</id>
<phase>compile</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<environmentVariables><PATH>${project.build.directory}/node:${env.PATH}</PATH></environmentVariables>
<executable>script/build-to-docs</executable>
<arguments>
<argument>latest</argument>
<argument>${website.version}</argument>
<argument>${website.src}</argument>
</arguments>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
| {
"content_hash": "93450ca070693b66139a912dfb7507fd",
"timestamp": "",
"source": "github",
"line_count": 116,
"max_line_length": 201,
"avg_line_length": 37.724137931034484,
"alnum_prop": 0.5987202925045704,
"repo_name": "mghosh4/druid",
"id": "4be642b60a008c6aee1949a45f9898eb488e2a76",
"size": "4376",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "website/pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "5360"
},
{
"name": "CSS",
"bytes": "3878"
},
{
"name": "Dockerfile",
"bytes": "8766"
},
{
"name": "HTML",
"bytes": "2536"
},
{
"name": "Java",
"bytes": "34944606"
},
{
"name": "JavaScript",
"bytes": "59220"
},
{
"name": "Makefile",
"bytes": "659"
},
{
"name": "PostScript",
"bytes": "5"
},
{
"name": "Python",
"bytes": "66994"
},
{
"name": "R",
"bytes": "17002"
},
{
"name": "Roff",
"bytes": "3617"
},
{
"name": "SCSS",
"bytes": "109536"
},
{
"name": "Shell",
"bytes": "81730"
},
{
"name": "Smarty",
"bytes": "3517"
},
{
"name": "Stylus",
"bytes": "7682"
},
{
"name": "TeX",
"bytes": "399468"
},
{
"name": "Thrift",
"bytes": "1003"
},
{
"name": "TypeScript",
"bytes": "1224966"
}
],
"symlink_target": ""
} |
package com.example.physics;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Contact extends ActionBarActivity{
//declaring all fields in xml
EditText toField, subjectField, messageField, edTestOne;
String msg ="android";
Button send, mainMenu;
//declaring variables needed
String email, subject, message;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
//set page to open contactus xml
setContentView(R.layout.contactus);
//call prepopulate and setUp methods
prePopulateFields();
toField = (EditText) findViewById(R.id.etTo);
edTestOne = (EditText) findViewById(R.id.edTest);
subjectField = (EditText) findViewById(R.id.etSubject);
messageField = (EditText) findViewById(R.id.etMessage);
Log.d(msg, "inside here");
edTestOne.setText("test".toString());
send = (Button) findViewById(R.id.btnSend);
send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
sendEmail();
}
});
mainMenu=(Button)findViewById(R.id.btnMain);
mainMenu.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
setContentView(R.layout.activity_main);
}
});
}
//private void setUp() {
// TODO Auto-generated method stub
//setting all variables to the actual id given to fields in xml
//}
//public void onClick(View v){
//switch (v.getId()){
//if select the variable assigned to send the button then call sendEmail method then stop working
//case R.id.btnSend:
//sendEmail();
//break;
//case R.id.btnHome:
//if user selects the home button display home xml
//startActivity(new Intent("com.example.physics.SPLASH"));
//break;
//default:
//break;
//}
//}
private void prePopulateFields() {
//asking it to always populate this field with my email
toField.setText("[email protected]");
}
private void sendEmail() {
// TODO Auto-generated method stub
if (toField.getText().toString().length()==0){
//if to field empty display message
Toast.makeText(Contact.this,
"An e-mail address must be entered", Toast.LENGTH_SHORT).show();
//if subject field empty display message
}else if (subjectField.getText().toString().length() == 0){
Toast.makeText(Contact.this,
"A Subject must be entered", Toast.LENGTH_SHORT).show();
//if message field empty display message
}else if (messageField.getText().toString().length() == 0){
Toast.makeText(Contact.this,
"A message must be entered", Toast.LENGTH_SHORT).show();
}else {
//call details from form method
detailsFromForm();
String emailAddress[] = { email };
//new intent to send email
Intent sendEmail = new Intent (android.content.Intent.ACTION_SEND);
sendEmail.putExtra(android.content.Intent.EXTRA_EMAIL, emailAddress);
sendEmail.putExtra(android.content.Intent.EXTRA_SUBJECT, emailAddress);
sendEmail.putExtra(android.content.Intent.EXTRA_TEXT, emailAddress);
sendEmail.setType("Plain/text");
//start send email activity
startActivity(sendEmail);
}
}
private void detailsFromForm() {
// TODO Auto-generated method stub
//store in email what the user enters in the to field
email = toField.getText().toString();
subject = subjectField.getText().toString();
message = messageField.getText().toString();
}
}
| {
"content_hash": "3848f1e1d9e5bb6e33200c8653b8b75a",
"timestamp": "",
"source": "github",
"line_count": 124,
"max_line_length": 98,
"avg_line_length": 31.04032258064516,
"alnum_prop": 0.6879709015328657,
"repo_name": "LouJones/ProjectX",
"id": "cab7d17392f97a91cb118d1add3cf53b83f1ff7d",
"size": "3849",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Contact.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "27270"
}
],
"symlink_target": ""
} |
.. _article3:
=============
Article 3
=============
In the works of Eco, a predominant concept is the distinction between ground and figure. The characteristic theme of Porter’s[7] essay on textual deconstruction is the role of the reader as artist. It could be said that Baudrillard promotes the use of socialist realism to read and modify sexual identity.
“Society is intrinsically impossible,” says Lyotard. Foucault uses the term ‘textual deconstruction’ to denote the stasis, and eventually the collapse, of constructivist consciousness. Therefore, the primary theme of the works of Fellini is the common ground between society and class.
If one examines subtextual construction, one is faced with a choice: either accept socialist realism or conclude that expression is a product of communication. Subdialectic desublimation implies that the raison d’etre of the observer is significant form. Thus, the main theme of Prinn’s[8] critique of subtextual construction is the role of the reader as poet.
Several narratives concerning a pretextual reality may be discovered. Therefore, the subject is interpolated into a socialist realism that includes reality as a paradox.
Sartre uses the term ‘dialectic discourse’ to denote the dialectic, and some would say the collapse, of subcapitalist narrativity. It could be said that the characteristic theme of the works of Fellini is the role of the reader as observer.
The subject is contextualised into a socialist realism that includes truth as a whole. But the primary theme of McElwaine’s[9] essay on textual deconstruction is not desituationism as such, but neodesituationism.
Debord suggests the use of socialist realism to challenge sexism. However, Humphrey[10] states that we have to choose between subtextual construction and semioticist predialectic theory.
| {
"content_hash": "eeb3daf7ab55ec6837bbac851da2d28b",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 360,
"avg_line_length": 96.05263157894737,
"alnum_prop": 0.8038356164383562,
"repo_name": "laufercenter/meld",
"id": "bee791a02a728f5937ba2f948567ae5c59bd9dda",
"size": "1845",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/userguide/article3.rst",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "427299"
}
],
"symlink_target": ""
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>tesseract: /home/stweil/src/github/tesseract-ocr/tesseract/unittest/include_gunit.h File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtreedata.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
</script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">tesseract
 <span id="projectnumber">4.00.00dev</span>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.13 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<script type="text/javascript" src="menudata.js"></script>
<script type="text/javascript" src="menu.js"></script>
<script type="text/javascript">
$(function() {
initMenu('',true,false,'search.php','Search');
$(document).ready(function() { init_search(); });
});
</script>
<div id="main-nav"></div>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
<div id="nav-sync" class="sync"></div>
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){initNavTree('a01589.html','');});
</script>
<div id="doc-content">
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div class="header">
<div class="headertitle">
<div class="title">include_gunit.h File Reference</div> </div>
</div><!--header-->
<div class="contents">
<div class="textblock"><code>#include "gtest/gtest.h"</code><br />
</div>
<p><a href="a01589_source.html">Go to the source code of this file.</a></p>
</div><!-- contents -->
</div><!-- doc-content -->
<!-- start footer part -->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
<ul>
<li class="navelem"><a class="el" href="dir_244674c763b96fdad0a6ffe8d0250e08.html">unittest</a></li><li class="navelem"><a class="el" href="a01589.html">include_gunit.h</a></li>
<li class="footer">Generated on Wed Mar 28 2018 19:53:41 for tesseract by
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.13 </li>
</ul>
</div>
</body>
</html>
| {
"content_hash": "90511dbc5b7efed69506a0e19fb38ce9",
"timestamp": "",
"source": "github",
"line_count": 102,
"max_line_length": 181,
"avg_line_length": 38.490196078431374,
"alnum_prop": 0.6749872643912379,
"repo_name": "stweil/tesseract-ocr.github.io",
"id": "bb932c64379aa0268099d6967a0d9cb21808bb2e",
"size": "3926",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "4.0.0-beta.1/a01589.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "1481625"
},
{
"name": "CSS",
"bytes": "136547"
},
{
"name": "HTML",
"bytes": "489171589"
},
{
"name": "JavaScript",
"bytes": "9187479"
}
],
"symlink_target": ""
} |
/*
jQuery(document).foundation();
jQuery(".off-canvas-submenu").hide();
jQuery(".off-canvas-submenu-call").click(function() {
var icon = jQuery(this).parent().next(".off-canvas-submenu").is(':visible') ? '+' : '-';
jQuery(this).parent().next(".off-canvas-submenu").slideToggle('fast');
jQuery(this).find("span").text(icon);
});
jQuery(document).foundation();
*/ | {
"content_hash": "e33b15cec4ef80c984ee3455c5f213de",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 92,
"avg_line_length": 27,
"alnum_prop": 0.6402116402116402,
"repo_name": "haa-gg/TastesLikeNeonThrashMetal",
"id": "b695016ffdd3f92ae02f0d8b988c22438c02433f",
"size": "378",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "contractor-page/assets/js/haa-script.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "147475"
},
{
"name": "HTML",
"bytes": "52266"
},
{
"name": "JavaScript",
"bytes": "24200"
},
{
"name": "PHP",
"bytes": "167346"
}
],
"symlink_target": ""
} |
package amazed.maze;
public class Case extends CaseAbstraite {
private boolean nord = false;
private boolean sud = false;
private boolean est = false;
private boolean ouest = false;
public Case(boolean nord, boolean sud, boolean est, boolean ouest){
this.nord = nord;
this.sud = sud;
this.est = est;
this.ouest = ouest;
}
public Case(){}
public Case(boolean full){
nord = full;
sud = full;
est = full;
ouest = full;
dansLaby = !full;
}
public boolean getNord(){
return nord;
}
public boolean getSud(){
return sud;
}
public boolean getEst(){
return est;
}
public boolean getOuest(){
return ouest;
}
public void setNord(boolean full){
nord = full;
}
public void setSud(boolean full){
sud = full;
}
public void setEst(boolean full){
est = full;
}
public void setOuest(boolean full){
ouest = full;
}
public Case clone() {
Case caseClone = new Case(nord,sud,est,ouest);
return caseClone;
}
}
| {
"content_hash": "44d9a471bd42e24191580ac2ce4f13d8",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 68,
"avg_line_length": 16.444444444444443,
"alnum_prop": 0.6187258687258688,
"repo_name": "xavierhardy/amazed",
"id": "a13d293787a5eaeee1de9977d4085796b0e0d42e",
"size": "2120",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "src/amazed/maze/Case.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "130628"
}
],
"symlink_target": ""
} |
package springfox.documentation.service;
import springfox.documentation.schema.ModelSpecification;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static java.util.stream.Collectors.*;
@SuppressWarnings("deprecation")
public class ApiListing {
private final String apiVersion;
private final String basePath;
private final String resourcePath;
private final Set<String> produces;
private final Set<String> consumes;
private final String host;
private final Set<String> protocols;
private final List<SecurityReference> securityReferences;
private final List<ApiDescription> apis;
private final Map<String, springfox.documentation.schema.Model> models;
private final Map<String, ModelSpecification> modelSpecifications;
private final ModelNamesRegistry modelNamesRegistry;
// private Map<String, ApiResponse> responses = null;
// private Map<String, Parameter> parameters = null;
// private Map<String, Example> examples = null;
// private Map<String, RequestBody> requestBodies = null;
// private Map<String, Header> headers = null;
// private Map<String, Link> links = null;
// private Map<String, Callback> callbacks = null;
private final String description;
private final int position;
private final Set<Tag> tags;
@SuppressWarnings("ParameterNumber")
public ApiListing(
String apiVersion,
String basePath,
String resourcePath,
Set<String> produces,
Set<String> consumes,
String host,
Set<String> protocols,
List<SecurityReference> securityReferences,
List<ApiDescription> apis,
Map<String, springfox.documentation.schema.Model> models,
Map<String, ModelSpecification> modelSpecifications,
ModelNamesRegistry modelNamesRegistry,
String description,
int position,
Set<Tag> tags) {
this.apiVersion = apiVersion;
this.basePath = basePath;
this.resourcePath = resourcePath;
this.produces = produces;
this.consumes = consumes;
this.host = host;
this.protocols = protocols;
this.securityReferences = securityReferences;
this.apis = apis.stream()
.sorted(byPath()).collect(toList());
this.models = models;
this.modelSpecifications = modelSpecifications;
this.modelNamesRegistry = modelNamesRegistry;
this.description = description;
this.position = position;
this.tags = tags;
}
public String getApiVersion() {
return apiVersion;
}
public String getBasePath() {
return basePath;
}
public String getResourcePath() {
return resourcePath;
}
public Set<String> getProduces() {
return produces;
}
public Set<String> getConsumes() {
return consumes;
}
public String getHost() {
return host;
}
public Set<String> getProtocols() {
return protocols;
}
public List<SecurityReference> getSecurityReferences() {
return securityReferences;
}
public List<ApiDescription> getApis() {
return apis;
}
public Map<String, springfox.documentation.schema.Model> getModels() {
return models;
}
public String getDescription() {
return description;
}
public int getPosition() {
return position;
}
public Set<Tag> getTags() {
return tags;
}
private Comparator<ApiDescription> byPath() {
return Comparator.comparing(ApiDescription::getPath);
}
public Map<String, ModelSpecification> getModelSpecifications() {
return modelSpecifications;
}
public ModelNamesRegistry getModelNamesRegistry() {
return modelNamesRegistry;
}
}
| {
"content_hash": "c28941afeb62fff01e6d463ca4b52463",
"timestamp": "",
"source": "github",
"line_count": 140,
"max_line_length": 73,
"avg_line_length": 25.728571428571428,
"alnum_prop": 0.7187673514714048,
"repo_name": "springfox/springfox",
"id": "23b69582af711c88c026403db0b14280598d3852",
"size": "4243",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "springfox-core/src/main/java/springfox/documentation/service/ApiListing.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "2894"
},
{
"name": "Groovy",
"bytes": "158286"
},
{
"name": "HTML",
"bytes": "3157"
},
{
"name": "Java",
"bytes": "491049"
},
{
"name": "JavaScript",
"bytes": "10748"
},
{
"name": "Shell",
"bytes": "337"
},
{
"name": "Vim Snippet",
"bytes": "1990"
}
],
"symlink_target": ""
} |
#ifndef SRC_CPP_SVCS_STMGR_SRC_MANAGER_TMASTER_CLIENT_H_
#define SRC_CPP_SVCS_STMGR_SRC_MANAGER_TMASTER_CLIENT_H_
#include <set>
#include <string>
#include <vector>
#include "network/network_error.h"
#include "proto/messages.h"
#include "network/network.h"
#include "basics/basics.h"
namespace heron {
namespace stmgr {
class TMasterClient : public Client {
public:
TMasterClient(EventLoop* eventLoop, const NetworkOptions& _options, const sp_string& _stmgr_id,
const sp_string& _stmgr_host, sp_int32 _data_port, sp_int32 _local_data_port,
sp_int32 _shell_port,
VCallback<proto::system::PhysicalPlan*> _pplan_watch,
VCallback<sp_string> _stateful_checkpoint_watch,
VCallback<sp_string, sp_int64> _restore_topology_watch,
VCallback<sp_string> _start_stateful_watch);
virtual ~TMasterClient();
// Told by the upper layer to disconnect and self destruct
void Die();
// Sets the instances that belong to us
void SetInstanceInfo(const std::vector<proto::system::Instance*>& _instances);
// returns the tmaster address "host:port" form.
sp_string getTmasterHostPort();
// Send a InstanceStateStored message to tmaster
void SavedInstanceState(const proto::system::Instance& _instance,
const std::string& _checkpoint_id);
// Send RestoreTopologyStateResponse to tmaster
void SendRestoreTopologyStateResponse(proto::system::StatusCode _status,
const std::string& _checkpoint_id,
sp_int64 _txid);
// Send ResetTopologyState message to tmaster
void SendResetTopologyState(const std::string& _dead_stmgr,
int32_t _dead_instance,
const std::string& _reason);
protected:
virtual void HandleConnect(NetworkErrorCode status);
virtual void HandleClose(NetworkErrorCode status);
private:
void HandleRegisterResponse(void*, proto::tmaster::StMgrRegisterResponse* _response,
NetworkErrorCode);
void HandleHeartbeatResponse(void*, proto::tmaster::StMgrHeartbeatResponse* response,
NetworkErrorCode);
void HandleNewAssignmentMessage(proto::stmgr::NewPhysicalPlanMessage* _message);
void HandleStatefulCheckpointMessage(proto::ckptmgr::StartStatefulCheckpoint* _message);
void HandleRestoreTopologyStateRequest(proto::ckptmgr::RestoreTopologyStateRequest* _message);
void HandleStartStmgrStatefulProcessing(proto::ckptmgr::StartStmgrStatefulProcessing* _msg);
void OnReConnectTimer();
void OnHeartbeatTimer();
void SendRegisterRequest();
void SendHeartbeatRequest();
void CleanInstances();
sp_string stmgr_id_;
sp_string stmgr_host_;
sp_int32 data_port_;
sp_int32 local_data_port_;
sp_int32 shell_port_;
// Set of instances to be reported to tmaster
std::set<proto::system::Instance*> instances_;
bool to_die_;
// We invoke this callback upon a new physical plan from tmaster
VCallback<proto::system::PhysicalPlan*> pplan_watch_;
// We invoke this callback upon receiving a checkpoint message from tmaster
// passing in the checkpoint id
VCallback<sp_string> stateful_checkpoint_watch_;
// We invoke this callback upon receiving a restore topology message from tmaster
// passing in the checkpoint id and the txid
VCallback<sp_string, sp_int64> restore_topology_watch_;
// We invoke this callback upon receiving a StartStatefulProcessing message from tmaster
// passing in the checkpoint id
VCallback<sp_string> start_stateful_watch_;
// Configs to be read
sp_int32 reconnect_tmaster_interval_sec_;
sp_int32 stream_to_tmaster_heartbeat_interval_sec_;
sp_int64 reconnect_timer_id;
sp_int64 heartbeat_timer_id;
// Counter for reconnect attempts
sp_int32 reconnect_attempts_;
sp_int32 reconnect_max_attempt_;
// Permanent timer callbacks
VCallback<> reconnect_timer_cb;
VCallback<> heartbeat_timer_cb;
};
} // namespace stmgr
} // namespace heron
#endif // SRC_CPP_SVCS_STMGR_SRC_MANAGER_TMASTER_CLIENT_H_
| {
"content_hash": "8d2434715f7899680adf7af034bbae9d",
"timestamp": "",
"source": "github",
"line_count": 114,
"max_line_length": 97,
"avg_line_length": 36.3859649122807,
"alnum_prop": 0.7034715525554484,
"repo_name": "lucperkins/heron",
"id": "656115930d086062f3fb207c59fdb6bf3be66fab",
"size": "4742",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "heron/stmgr/src/cpp/manager/tmaster-client.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "11709"
},
{
"name": "C++",
"bytes": "1623239"
},
{
"name": "CSS",
"bytes": "109554"
},
{
"name": "HCL",
"bytes": "2115"
},
{
"name": "HTML",
"bytes": "156820"
},
{
"name": "Java",
"bytes": "4466689"
},
{
"name": "JavaScript",
"bytes": "1110981"
},
{
"name": "M4",
"bytes": "17941"
},
{
"name": "Makefile",
"bytes": "1046"
},
{
"name": "Objective-C",
"bytes": "1929"
},
{
"name": "Python",
"bytes": "1537910"
},
{
"name": "Ruby",
"bytes": "1930"
},
{
"name": "Scala",
"bytes": "72781"
},
{
"name": "Shell",
"bytes": "166876"
},
{
"name": "Smarty",
"bytes": "528"
},
{
"name": "Thrift",
"bytes": "915"
}
],
"symlink_target": ""
} |
<?php
namespace ALawrence\LaravelWonde;
use Illuminate\Contracts\Container\Container;
use Illuminate\Foundation\Application as LaravelApplication;
use Illuminate\Support\ServiceProvider;
use Laravel\Lumen\Application as LumenApplication;
use Wonde\Client as WondeClient;
/**
* This is the main Wonde service provider class.
*
* @author Anthony Lawrence <[email protected]>
*/
class WondeServiceProvider extends ServiceProvider
{
/**
* Boot the service provider.
*
* @return void
*/
public function boot()
{
$this->setupConfig();
}
/**
* Setup the config.
*
* @return void
*/
protected function setupConfig()
{
$source = realpath(__DIR__.'/../config/wonde.php');
if ($this->app instanceof LaravelApplication && $this->app->runningInConsole()) {
$this->publishes([$source => config_path('wonde.php')]);
} elseif ($this->app instanceof LumenApplication) {
$this->app->configure('wonde');
}
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->registerFactory();
$this->registerManager();
$this->registerBindings();
}
/**
* Register the Wonde factory class.
*
* @return void
*/
protected function registerFactory()
{
$this->app->singleton('wonde.factory', function (Container $app) {
return new WondeFactory();
});
$this->app->alias('wonde.factory', WondeFactory::class);
}
/**
* Register the manager class.
*
* @return void
*/
protected function registerManager()
{
$this->app->singleton('wonde', function (Container $app) {
$config = $app['config'];
$factory = $app['wonde.factory'];
return new WondeManager($config, $factory);
});
$this->app->alias('wonde', WondeManager::class);
}
/**
* Register bindings.
*
* @return void
*/
protected function registerBindings()
{
$this->app->bind('wonde.connection', function (Container $app) {
$manager = $app['wonde'];
return $manager->connection();
});
$this->app->alias('wonde.connection', WondeClient::class);
}
/**
* Get the services provided by the provider.
*
* @return string[]
*/
public function provides()
{
return [
'wonde.factory',
'wonde',
'wonde.connection',
];
}
}
| {
"content_hash": "979681513e3a123a69c18db8b644910e",
"timestamp": "",
"source": "github",
"line_count": 118,
"max_line_length": 89,
"avg_line_length": 22.271186440677965,
"alnum_prop": 0.5593607305936074,
"repo_name": "A-Lawrence/laravel-wonde",
"id": "d1c31f24f4c1c420ee23b4116b0873358b543785",
"size": "2926",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/WondeServiceProvider.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "8085"
}
],
"symlink_target": ""
} |
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
$Id: CmsCount.hbm.xml 3932 2010-10-26 12:05:48Z orangeforjava $
-->
<hibernate-mapping>
<class entity-name="CmsCount" table="cms_count">
<id name="indexId" type="long">
<column name="indexId" />
<generator class="assigned" />
</id>
<property name="contentId" type="long">
<column name="contentId" not-null="true" />
</property>
<property name="nodeId" type="long">
<column name="nodeId" not-null="true" />
</property>
<property name="tableId" type="long">
<column name="tableId" not-null="true" />
</property>
<property name="hitsTotal" type="long">
<column name="hitsTotal" not-null="true" />
</property>
<property name="hitsToday" type="long">
<column name="hitsToday" not-null="true" />
</property>
<property name="hitsWeek" type="long">
<column name="hitsWeek" not-null="true" />
</property>
<property name="hitsMonth" type="long">
<column name="hitsMonth" not-null="true" />
</property>
<property name="commentNum" type="long">
<column name="commentNum" not-null="true" />
</property>
<property name="hitsDate" type="long">
<column name="hitsDate" not-null="true" />
</property>
</class>
</hibernate-mapping>
| {
"content_hash": "a5849ee147c52a941912141bf4599279",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 79,
"avg_line_length": 38.707317073170735,
"alnum_prop": 0.5639571518588532,
"repo_name": "juweiping/ocms",
"id": "45b9f578b8dcf2abf44134c8469dd8fa0a29a3e8",
"size": "1587",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "web/WEB-INF/uapHome/hibernate/oracle/CmsCount.hbm.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "434506"
},
{
"name": "ColdFusion",
"bytes": "5390"
},
{
"name": "Java",
"bytes": "2714260"
},
{
"name": "JavaScript",
"bytes": "2290371"
},
{
"name": "PHP",
"bytes": "7226"
},
{
"name": "Perl",
"bytes": "4746"
}
],
"symlink_target": ""
} |
This script generates prometheus rules set for alertmanager from any properly formatted kubernetes yaml based on defined input, splitting rules to separate files based on group name.
Currently following imported:
- [coreos/kube-prometheus rules set](https://github.com/coreos/kube-prometheus/master/manifests/prometheus-rules.yaml)
- In order to modify these rules:
- prepare and merge PR into [kubernetes-mixin](https://github.com/kubernetes-monitoring/kubernetes-mixin/tree/master/rules) master and/or release branch
- run import inside your fork of [coreos/kube-prometheus](https://github.com/coreos/kube-prometheus/tree/master)
```bash
jb update
make generate-in-docker
```
- prepare and merge PR with imported changes into coreos/kube-prometheus master and/or release branch
- run sync_prometheus_rules.py inside your fork of this repo
- send PR with changes to this repo
- [etcd-io/etc rules set](https://github.com/etcd-io/etcd/blob/master/Documentation/op-guide/etcd3_alert.rules.yml)
- In order to modify these rules:
- prepare and merge PR into [etcd-io/etcd](https://github.com/etcd-io/etcd/blob/master/Documentation/op-guide/grafana.json) repo
- run sync_prometheus_rules.py inside your fork of this repo
- send PR with changes to this repo
## [sync_grafana_dashboards.py](sync_grafana_dashboards.py)
This script generates grafana dashboards from json files, splitting them to separate files based on group name.
Currently following imported:
- [coreos/kube-prometheus dashboards](https://github.com/coreos/kube-prometheus/manifests/grafana-deployment.yaml)
- In order to modify these dashboards:
- prepare and merge PR into [kubernetes-mixin](https://github.com/kubernetes-monitoring/kubernetes-mixin/tree/master/dashboards) master and/or release branch
- run import inside your fork of [coreos/kube-prometheus](https://github.com/coreos/kube-prometheus/tree/master)
```bash
jb update
make generate-in-docker
```
- prepare and merge PR with imported changes into coreos/kube-prometheus master and/or release branch
- run sync_grafana_dashboards.py inside your fork of this repo
- send PR with changes to this repo
- [etcd-io/etc dashboard](https://github.com/etcd-io/etcd/blob/master/Documentation/op-guide/grafana.json)
- In order to modify this dashboard:
- prepare and merge PR into [etcd-io/etcd](https://github.com/etcd-io/etcd/blob/master/Documentation/op-guide/grafana.json) repo
- run sync_grafana_dashboards.py inside your fork of this repo
- send PR with changes to this repo
[CoreDNS dashboard](https://github.com/helm/charts/blob/master/stable/prometheus-operator/templates/grafana/dashboards-1.14/k8s-coredns.yaml) is the only dashboard which is maintained in this repo and can be changed without import.
| {
"content_hash": "a64036805877895df05af5fab6ee3625",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 231,
"avg_line_length": 58.244897959183675,
"alnum_prop": 0.7610371408549405,
"repo_name": "helm/charts",
"id": "d383726d9bd3c6ef1105963470446aeb039c4644",
"size": "2940",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "stable/prometheus-operator/hack/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "4338"
},
{
"name": "Go",
"bytes": "805085"
},
{
"name": "HTML",
"bytes": "13"
},
{
"name": "Makefile",
"bytes": "1666"
},
{
"name": "Python",
"bytes": "26797"
},
{
"name": "Shell",
"bytes": "60424"
}
],
"symlink_target": ""
} |
mxArray *message(std::vector<nix::valid::Message> mes) {
const mwSize size = static_cast<mwSize>(mes.size());
mxArray *list = mxCreateCellArray(1, &size);
for (size_t i = 0; i < mes.size(); i++) {
nix::valid::Message curr = mes[i];
struct_builder msb({ 1 }, { "id", "msg" });
msb.set(curr.id);
msb.set(curr.msg);
mxSetCell(list, i, msb.array());
}
return list;
}
namespace nixfile {
void open(const extractor &input, infusor &output) {
std::string name = input.str(1);
uint8_t omode = input.num<uint8_t>(2);
nix::FileMode mode;
switch (omode) {
case 0: mode = nix::FileMode::ReadOnly; break;
case 1: mode = nix::FileMode::ReadWrite; break;
case 2: mode = nix::FileMode::Overwrite; break;
default: throw std::invalid_argument("unkown open mode");
}
nix::File fn = nix::File::open(name, mode);
handle h = handle(fn);
output.set(0, h);
}
void fileMode(const extractor &input, infusor &output) {
nix::File currObj = input.entity<nix::File>(1);
nix::FileMode mode = currObj.fileMode();
uint8_t omode;
switch (mode) {
case nix::FileMode::ReadOnly: omode = 0; break;
case nix::FileMode::ReadWrite: omode = 1; break;
case nix::FileMode::Overwrite: omode = 2; break;
default: throw std::invalid_argument("unknown open mode");
}
output.set(0, omode);
}
void validate(const extractor &input, infusor &output) {
nix::File f = input.entity<nix::File>(1);
nix::valid::Result res = f.validate();
std::vector<nix::valid::Message> err = res.getErrors();
mxArray *err_list = message(err);
std::vector<nix::valid::Message> warn = res.getWarnings();
mxArray *warn_list = message(warn);
struct_builder sb({ 1 }, { "ok", "hasErrors", "hasWarnings", "errors", "warnings" });
sb.set(res.ok());
sb.set(res.hasErrors());
sb.set(res.hasWarnings());
sb.set(err_list);
sb.set(warn_list);
output.set(0, sb.array());
}
mxArray *describe(const nix::File &fd) {
struct_builder sb({ 1 }, { "format", "version", "location", "createdAt", "updatedAt" });
sb.set(fd.format());
sb.set(fd.version());
sb.set(fd.location());
sb.set(static_cast<uint64_t>(fd.createdAt()));
sb.set(static_cast<uint64_t>(fd.updatedAt()));
return sb.array();
}
void openBlockIdx(const extractor &input, infusor &output) {
nix::File currObj = input.entity<nix::File>(1);
nix::ndsize_t idx = (nix::ndsize_t)input.num<double>(2);
output.set(0, currObj.getBlock(idx));
}
void openSectionIdx(const extractor &input, infusor &output) {
nix::File currObj = input.entity<nix::File>(1);
nix::ndsize_t idx = (nix::ndsize_t)input.num<double>(2);
output.set(0, currObj.getSection(idx));
}
void sectionsFiltered(const extractor &input, infusor &output) {
nix::File currObj = input.entity<nix::File>(1);
std::vector<nix::Section> res = filterNameTypeEntity<nix::Section>(input,
[currObj](const nix::util::Filter<nix::Section>::type &filter) {
return currObj.sections(filter);
});
output.set(0, res);
}
void blocksFiltered(const extractor &input, infusor &output) {
nix::File currObj = input.entity<nix::File>(1);
std::vector<nix::Block> res = filterNameTypeEntity<nix::Block>(input,
[currObj](const nix::util::Filter<nix::Block>::type &filter) {
return currObj.blocks(filter);
});
output.set(0, res);
}
void findSections(const extractor &input, infusor &output) {
nix::File currObj = input.entity<nix::File>(1);
size_t max_depth = (size_t)input.num<double>(2);
uint8_t filter_id = input.num<uint8_t>(3);
std::vector<nix::Section> res = filterNameTypeEntity<nix::Section>(input, filter_id, 4, max_depth,
[currObj](const nix::util::Filter<nix::Section>::type &filter, size_t &md) {
return currObj.findSections(filter, md);
});
output.set(0, res);
}
} // namespace nixfile
| {
"content_hash": "2839207efa7c6481e3e00a48da261391",
"timestamp": "",
"source": "github",
"line_count": 127,
"max_line_length": 108,
"avg_line_length": 34.54330708661417,
"alnum_prop": 0.5698655117392295,
"repo_name": "mpsonntag/nix-mx",
"id": "c83c6f1cd34d301b336358448ffc0f6bf5786dc8",
"size": "4885",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/nixfile.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "6577"
},
{
"name": "C++",
"bytes": "133354"
},
{
"name": "CMake",
"bytes": "18475"
},
{
"name": "M",
"bytes": "85"
},
{
"name": "Matlab",
"bytes": "491710"
}
],
"symlink_target": ""
} |
package twitter4j.auth;
import twitter4j.*;
import twitter4j.conf.Configuration;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.*;
/**
* @author Yusuke Yamamoto - yusuke at mac.com
* @see <a href="http://oauth.net/core/1.0a/">OAuth Core 1.0a</a>
*/
public class OAuthAuthorization implements Authorization, java.io.Serializable, OAuthSupport {
private static final long serialVersionUID = -886869424811858868L;
private final Configuration conf;
private transient static HttpClient http;
private static final String HMAC_SHA1 = "HmacSHA1";
private static final HttpParameter OAUTH_SIGNATURE_METHOD = new HttpParameter("oauth_signature_method", "HMAC-SHA1");
private static final Logger logger = Logger.getLogger(OAuthAuthorization.class);
private String consumerKey = "";
private String consumerSecret;
private String realm = null;
private OAuthToken oauthToken = null;
// constructors
/**
* @param conf configuration
*/
public OAuthAuthorization(Configuration conf) {
this.conf = conf;
http = HttpClientFactory.getInstance(conf.getHttpClientConfiguration());
setOAuthConsumer(conf.getOAuthConsumerKey(), conf.getOAuthConsumerSecret());
if (conf.getOAuthAccessToken() != null && conf.getOAuthAccessTokenSecret() != null) {
setOAuthAccessToken(new AccessToken(conf.getOAuthAccessToken(), conf.getOAuthAccessTokenSecret()));
}
}
// implementations for Authorization
@Override
public String getAuthorizationHeader(HttpRequest req) {
return generateAuthorizationHeader(req.getMethod().name(), req.getURL(), req.getParameters(), oauthToken);
}
private void ensureTokenIsAvailable() {
if (null == oauthToken) {
throw new IllegalStateException("No Token available.");
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean isEnabled() {
return oauthToken != null && oauthToken instanceof AccessToken;
}
// implementation for OAuthSupport interface
@Override
public RequestToken getOAuthRequestToken() throws TwitterException {
return getOAuthRequestToken(null, null, null);
}
@Override
public RequestToken getOAuthRequestToken(String callbackURL) throws TwitterException {
return getOAuthRequestToken(callbackURL, null, null);
}
@Override
public RequestToken getOAuthRequestToken(String callbackURL, String xAuthAccessType) throws TwitterException {
return getOAuthRequestToken(callbackURL, xAuthAccessType, null);
}
@Override
public RequestToken getOAuthRequestToken(String callbackURL, String xAuthAccessType, String xAuthMode) throws TwitterException {
if (oauthToken instanceof AccessToken) {
throw new IllegalStateException("Access token already available.");
}
List<HttpParameter> params = new ArrayList<HttpParameter>();
if (callbackURL != null) {
params.add(new HttpParameter("oauth_callback", callbackURL));
}
if (xAuthAccessType != null) {
params.add(new HttpParameter("x_auth_access_type", xAuthAccessType));
}
if (xAuthMode != null) {
params.add(new HttpParameter("x_auth_mode", xAuthMode));
}
oauthToken = new RequestToken(http.post(conf.getOAuthRequestTokenURL(), params.toArray(new HttpParameter[params.size()]), this, null), this);
return (RequestToken) oauthToken;
}
@Override
public AccessToken getOAuthAccessToken() throws TwitterException {
ensureTokenIsAvailable();
if (oauthToken instanceof AccessToken) {
return (AccessToken) oauthToken;
}
oauthToken = new AccessToken(http.post(conf.getOAuthAccessTokenURL(), null, this, null));
return (AccessToken) oauthToken;
}
@Override
public AccessToken getOAuthAccessToken(String oauthVerifier) throws TwitterException {
ensureTokenIsAvailable();
oauthToken = new AccessToken(http.post(conf.getOAuthAccessTokenURL()
, new HttpParameter[]{new HttpParameter("oauth_verifier", oauthVerifier)}, this, null));
return (AccessToken) oauthToken;
}
@Override
public AccessToken getOAuthAccessToken(RequestToken requestToken) throws TwitterException {
this.oauthToken = requestToken;
return getOAuthAccessToken();
}
@Override
public AccessToken getOAuthAccessToken(RequestToken requestToken, String oauthVerifier) throws TwitterException {
this.oauthToken = requestToken;
return getOAuthAccessToken(oauthVerifier);
}
@Override
public AccessToken getOAuthAccessToken(String screenName, String password) throws TwitterException {
try {
String url = conf.getOAuthAccessTokenURL();
if (0 == url.indexOf("http://")) {
// SSL is required
// @see https://dev.twitter.com/docs/oauth/xauth
url = "https://" + url.substring(7);
}
oauthToken = new AccessToken(http.post(url, new HttpParameter[]{
new HttpParameter("x_auth_username", screenName),
new HttpParameter("x_auth_password", password),
new HttpParameter("x_auth_mode", "client_auth")
}, this, null));
return (AccessToken) oauthToken;
} catch (TwitterException te) {
throw new TwitterException("The screen name / password combination seems to be invalid.", te, te.getStatusCode());
}
}
@Override
public void setOAuthAccessToken(AccessToken accessToken) {
this.oauthToken = accessToken;
}
/**
* Sets the OAuth realm
*
* @param realm OAuth realm
* @since Twitter 2.1.4
*/
public void setOAuthRealm(String realm) {
this.realm = realm;
}
/*package*/ String generateAuthorizationHeader(String method, String url, HttpParameter[] params, String nonce, String timestamp, OAuthToken otoken) {
if (null == params) {
params = new HttpParameter[0];
}
List<HttpParameter> oauthHeaderParams = new ArrayList<HttpParameter>(5);
oauthHeaderParams.add(new HttpParameter("oauth_consumer_key", consumerKey));
oauthHeaderParams.add(OAUTH_SIGNATURE_METHOD);
oauthHeaderParams.add(new HttpParameter("oauth_timestamp", timestamp));
oauthHeaderParams.add(new HttpParameter("oauth_nonce", nonce));
oauthHeaderParams.add(new HttpParameter("oauth_version", "1.0"));
if (otoken != null) {
oauthHeaderParams.add(new HttpParameter("oauth_token", otoken.getToken()));
}
List<HttpParameter> signatureBaseParams = new ArrayList<HttpParameter>(oauthHeaderParams.size() + params.length);
signatureBaseParams.addAll(oauthHeaderParams);
if (!HttpParameter.containsFile(params)) {
signatureBaseParams.addAll(toParamList(params));
}
parseGetParameters(url, signatureBaseParams);
StringBuilder base = new StringBuilder(method).append("&")
.append(HttpParameter.encode(constructRequestURL(url))).append("&");
base.append(HttpParameter.encode(normalizeRequestParameters(signatureBaseParams)));
String oauthBaseString = base.toString();
logger.debug("OAuth base string: ", oauthBaseString);
String signature = generateSignature(oauthBaseString, otoken);
logger.debug("OAuth signature: ", signature);
oauthHeaderParams.add(new HttpParameter("oauth_signature", signature));
// http://oauth.net/core/1.0/#rfc.section.9.1.1
if (realm != null) {
oauthHeaderParams.add(new HttpParameter("realm", realm));
}
return "OAuth " + encodeParameters(oauthHeaderParams, ",", true);
}
private void parseGetParameters(String url, List<HttpParameter> signatureBaseParams) {
int queryStart = url.indexOf("?");
if (-1 != queryStart) {
String[] queryStrs = url.substring(queryStart + 1).split("&");
try {
for (String query : queryStrs) {
String[] split = query.split("=");
if (split.length == 2) {
signatureBaseParams.add(
new HttpParameter(URLDecoder.decode(split[0],
"UTF-8"), URLDecoder.decode(split[1],
"UTF-8"))
);
} else {
signatureBaseParams.add(
new HttpParameter(URLDecoder.decode(split[0],
"UTF-8"), "")
);
}
}
} catch (UnsupportedEncodingException ignore) {
}
}
}
private static final Random RAND = new Random();
/**
* @return generated authorization header
* @see <a href="http://oauth.net/core/1.0a/#rfc.section.5.4.1">OAuth Core - 5.4.1. Authorization Header</a>
*/
/*package*/ String generateAuthorizationHeader(String method, String url, HttpParameter[] params, OAuthToken token) {
long timestamp = System.currentTimeMillis() / 1000;
long nonce = timestamp + RAND.nextInt();
return generateAuthorizationHeader(method, url, params, String.valueOf(nonce), String.valueOf(timestamp), token);
}
public List<HttpParameter> generateOAuthSignatureHttpParams(String method, String url) {
long timestamp = System.currentTimeMillis() / 1000;
long nonce = timestamp + RAND.nextInt();
List<HttpParameter> oauthHeaderParams = new ArrayList<HttpParameter>(5);
oauthHeaderParams.add(new HttpParameter("oauth_consumer_key", consumerKey));
oauthHeaderParams.add(OAUTH_SIGNATURE_METHOD);
oauthHeaderParams.add(new HttpParameter("oauth_timestamp", timestamp));
oauthHeaderParams.add(new HttpParameter("oauth_nonce", nonce));
oauthHeaderParams.add(new HttpParameter("oauth_version", "1.0"));
if (oauthToken != null) {
oauthHeaderParams.add(new HttpParameter("oauth_token", oauthToken.getToken()));
}
List<HttpParameter> signatureBaseParams = new ArrayList<HttpParameter>(oauthHeaderParams.size());
signatureBaseParams.addAll(oauthHeaderParams);
parseGetParameters(url, signatureBaseParams);
StringBuilder base = new StringBuilder(method).append("&")
.append(HttpParameter.encode(constructRequestURL(url))).append("&");
base.append(HttpParameter.encode(normalizeRequestParameters(signatureBaseParams)));
String oauthBaseString = base.toString();
String signature = generateSignature(oauthBaseString, oauthToken);
oauthHeaderParams.add(new HttpParameter("oauth_signature", signature));
return oauthHeaderParams;
}
/**
* Computes RFC 2104-compliant HMAC signature.
*
* @param data the data to be signed
* @param token the token
* @return signature
* @see <a href="http://oauth.net/core/1.0a/#rfc.section.9.2.1">OAuth Core - 9.2.1. Generating Signature</a>
*/
/*package*/ String generateSignature(String data, OAuthToken token) {
byte[] byteHMAC = null;
try {
Mac mac = Mac.getInstance(HMAC_SHA1);
SecretKeySpec spec;
if (null == token) {
String oauthSignature = HttpParameter.encode(consumerSecret) + "&";
spec = new SecretKeySpec(oauthSignature.getBytes(), HMAC_SHA1);
} else {
spec = token.getSecretKeySpec();
if (null == spec) {
String oauthSignature = HttpParameter.encode(consumerSecret) + "&" + HttpParameter.encode(token.getTokenSecret());
spec = new SecretKeySpec(oauthSignature.getBytes(), HMAC_SHA1);
token.setSecretKeySpec(spec);
}
}
mac.init(spec);
byteHMAC = mac.doFinal(data.getBytes());
} catch (InvalidKeyException ike) {
logger.error("Failed initialize \"Message Authentication Code\" (MAC)", ike);
throw new AssertionError(ike);
} catch (NoSuchAlgorithmException nsae) {
logger.error("Failed to get HmacSHA1 \"Message Authentication Code\" (MAC)", nsae);
throw new AssertionError(nsae);
}
return BASE64Encoder.encode(byteHMAC);
}
/*package*/
String generateSignature(String data) {
return generateSignature(data, null);
}
/**
* The request parameters are collected, sorted and concatenated into a normalized string:<br>
* • Parameters in the OAuth HTTP Authorization header excluding the realm parameter.<br>
* • Parameters in the HTTP POST request body (with a content-type of application/x-www-form-urlencoded).<br>
* • HTTP GET parameters added to the URLs in the query part (as defined by [RFC3986] section 3).<br>
* <br>
* The oauth_signature parameter MUST be excluded.<br>
* The parameters are normalized into a single string as follows:<br>
* 1. Parameters are sorted by name, using lexicographical byte value ordering. If two or more parameters share the same name, they are sorted by their value. For example:<br>
* 2. a=1, c=hi%20there, f=25, f=50, f=a, z=p, z=t<br>
* 3. <br>
* 4. Parameters are concatenated in their sorted order into a single string. For each parameter, the name is separated from the corresponding value by an ‘=’ character (ASCII code 61), even if the value is empty. Each name-value pair is separated by an ‘&’ character (ASCII code 38). For example:<br>
* 5. a=1&c=hi%20there&f=25&f=50&f=a&z=p&z=t<br>
* 6. <br>
*
* @param params parameters to be normalized and concatenated
* @return normalized and concatenated parameters
* @see <a href="http://oauth.net/core/1.0#rfc.section.9.1.1">OAuth Core - 9.1.1. Normalize Request Parameters</a>
*/
static String normalizeRequestParameters(HttpParameter[] params) {
return normalizeRequestParameters(toParamList(params));
}
private static String normalizeRequestParameters(List<HttpParameter> params) {
Collections.sort(params);
return encodeParameters(params);
}
private static List<HttpParameter> toParamList(HttpParameter[] params) {
List<HttpParameter> paramList = new ArrayList<HttpParameter>(params.length);
paramList.addAll(Arrays.asList(params));
return paramList;
}
/**
* @param httpParams parameters to be encoded and concatenated
* @return encoded string
* @see <a href="http://wiki.oauth.net/TestCases">OAuth / TestCases</a>
* @see <a href="http://groups.google.com/group/oauth/browse_thread/thread/a8398d0521f4ae3d/9d79b698ab217df2?hl=en&lnk=gst&q=space+encoding#9d79b698ab217df2">Space encoding - OAuth | Google Groups</a>
*/
public static String encodeParameters(List<HttpParameter> httpParams) {
return encodeParameters(httpParams, "&", false);
}
public static String encodeParameters(List<HttpParameter> httpParams, String splitter, boolean quot) {
StringBuilder buf = new StringBuilder();
for (HttpParameter param : httpParams) {
if (!param.isFile() && !param.isJson()) {
if (buf.length() != 0) {
if (quot) {
buf.append("\"");
}
buf.append(splitter);
}
buf.append(HttpParameter.encode(param.getName())).append("=");
if (quot) {
buf.append("\"");
}
buf.append(HttpParameter.encode(param.getValue()));
}
}
if (buf.length() != 0) {
if (quot) {
buf.append("\"");
}
}
return buf.toString();
}
/**
* The Signature Base String includes the request absolute URL, tying the signature to a specific endpoint. The URL used in the Signature Base String MUST include the scheme, authority, and path, and MUST exclude the query and fragment as defined by [RFC3986] section 3.<br>
* If the absolute request URL is not available to the Service Provider (it is always available to the Consumer), it can be constructed by combining the scheme being used, the HTTP Host header, and the relative HTTP request URL. If the Host header is not available, the Service Provider SHOULD use the host name communicated to the Consumer in the documentation or other means.<br>
* The Service Provider SHOULD document the form of URL used in the Signature Base String to avoid ambiguity due to URL normalization. Unless specified, URL scheme and authority MUST be lowercase and include the port number; http default port 80 and https default port 443 MUST be excluded.<br>
* <br>
* For example, the request:<br>
* HTTP://Example.com:80/resource?id=123<br>
* Is included in the Signature Base String as:<br>
* http://example.com/resource
*
* @param url the url to be normalized
* @return the Signature Base String
* @see <a href="http://oauth.net/core/1.0#rfc.section.9.1.2">OAuth Core - 9.1.2. Construct Request URL</a>
*/
static String constructRequestURL(String url) {
int index = url.indexOf("?");
if (-1 != index) {
url = url.substring(0, index);
}
int slashIndex = url.indexOf("/", 8);
String baseURL = url.substring(0, slashIndex).toLowerCase();
int colonIndex = baseURL.indexOf(":", 8);
if (-1 != colonIndex) {
// url contains port number
if (baseURL.startsWith("http://") && baseURL.endsWith(":80")) {
// http default port 80 MUST be excluded
baseURL = baseURL.substring(0, colonIndex);
} else if (baseURL.startsWith("https://") && baseURL.endsWith(":443")) {
// http default port 443 MUST be excluded
baseURL = baseURL.substring(0, colonIndex);
}
}
url = baseURL + url.substring(slashIndex);
return url;
}
@Override
public void setOAuthConsumer(String consumerKey, String consumerSecret) {
this.consumerKey = consumerKey != null ? consumerKey : "";
this.consumerSecret = consumerSecret != null ? consumerSecret : "";
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof OAuthSupport)) return false;
OAuthAuthorization that = (OAuthAuthorization) o;
if (consumerKey != null ? !consumerKey.equals(that.consumerKey) : that.consumerKey != null)
return false;
if (consumerSecret != null ? !consumerSecret.equals(that.consumerSecret) : that.consumerSecret != null)
return false;
if (oauthToken != null ? !oauthToken.equals(that.oauthToken) : that.oauthToken != null)
return false;
return true;
}
@Override
public int hashCode() {
int result = consumerKey != null ? consumerKey.hashCode() : 0;
result = 31 * result + (consumerSecret != null ? consumerSecret.hashCode() : 0);
result = 31 * result + (oauthToken != null ? oauthToken.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "OAuthAuthorization{" +
"consumerKey='" + consumerKey + '\'' +
", consumerSecret='******************************************\'" +
", oauthToken=" + oauthToken +
'}';
}
}
| {
"content_hash": "7afb9b3f2288e3d3939d6f37bcc19d94",
"timestamp": "",
"source": "github",
"line_count": 465,
"max_line_length": 385,
"avg_line_length": 43.37204301075269,
"alnum_prop": 0.6329829432764776,
"repo_name": "takke/twitter4j",
"id": "bbd73079ec7f6d6dd77713bede6eeddc784d6e4e",
"size": "20781",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "twitter4j-core/src/main/java/twitter4j/auth/OAuthAuthorization.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "18620"
},
{
"name": "Java",
"bytes": "2301280"
},
{
"name": "Shell",
"bytes": "29526"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starters</artifactId>
<version>2.0.0.BUILD-SNAPSHOT</version>
</parent>
<artifactId>spring-boot-starter-web</artifactId>
<name>Spring Boot Web Starter</name>
<description>Starter for building web, including RESTful, applications using Spring
MVC. Uses Tomcat as the default embedded container</description>
<url>http://projects.spring.io/spring-boot/</url>
<organization>
<name>Pivotal Software, Inc.</name>
<url>http://www.spring.io</url>
</organization>
<properties>
<main.basedir>${basedir}/../..</main.basedir>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-json</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.basepom.maven</groupId>
<artifactId>duplicate-finder-maven-plugin</artifactId>
<executions>
<execution>
<id>duplicate-dependencies</id>
<phase>validate</phase>
<goals>
<goal>check</goal>
</goals>
<configuration>
<ignoredClassPatterns>
<ignoredClassPattern>javax.annotation.*</ignoredClassPattern>
</ignoredClassPatterns>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
| {
"content_hash": "2dcb3bc39fc246de343965644cc4a856",
"timestamp": "",
"source": "github",
"line_count": 69,
"max_line_length": 204,
"avg_line_length": 32.231884057971016,
"alnum_prop": 0.7050359712230215,
"repo_name": "deki/spring-boot",
"id": "c849cd9d1735fe882c8cfa63489768a21de67aea",
"size": "2224",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spring-boot-starters/spring-boot-starter-web/pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "6942"
},
{
"name": "CSS",
"bytes": "5769"
},
{
"name": "FreeMarker",
"bytes": "3599"
},
{
"name": "Groovy",
"bytes": "49424"
},
{
"name": "HTML",
"bytes": "69585"
},
{
"name": "Java",
"bytes": "11702550"
},
{
"name": "JavaScript",
"bytes": "37789"
},
{
"name": "Ruby",
"bytes": "1307"
},
{
"name": "Shell",
"bytes": "27326"
},
{
"name": "Smarty",
"bytes": "2885"
},
{
"name": "XSLT",
"bytes": "34105"
}
],
"symlink_target": ""
} |
UndoFX
======
UndoFX is a general-purpose undo manager for JavaFX (or Java applications in general).
Highlights
----------
**Arbitrary type of change objects.** Change objects don't have to implement any special interface, such as `UndoableEdit` in Swing.
**No requirements on the API of the control.** To add undo support for a control, you don't need the control to have a special API, such as `addUndoableEditListener(UndoableEditListener)` in Swing. This means you can add undo support to components that were not designed with undo support in mind, as long as you are able to observe changes on the component and the component provides API (of any sort) to reverse and reapply the effects of the changes.
**Immutable change objects** are encouraged. In contrast, `UndoableEdit` from Swing is mutable by design.
Suppports **merging of successive changes.**
Supports **marking** a state (position in the history) when the document was last saved.
API
---
```java
public interface UndoManager {
boolean undo();
boolean redo();
ObservableBooleanValue undoAvailableProperty();
boolean isUndoAvailable();
ObservableBooleanValue redoAvailableProperty();
boolean isRedoAvailable();
void preventMerge();
void forgetHistory();
void mark();
UndoPosition getCurrentPosition();
ObservableBooleanValue atMarkedPositionProperty();
boolean isAtMarkedPosition();
void close();
interface UndoPosition {
void mark();
boolean isValid();
}
}
```
`undo()` undoes the most recent change, if there is any change to undo. Returns `true` if a change was undone, `false` otherwise.
`redo()` reapplies a previously undone change, if there is any change to reapply. Returns `true` if a change was reapplied, `false` otherwise.
`undoAvailable` and `redoAvailable` properties indicate whether there is a change to be undone or redone, respectively.
`preventMerge()` explicitly prevents the next (upcoming) change from being merged with the latest one.
`forgetHistory()` forgets all changes prior to the current position in the change history.
`mark()` sets a mark at the current position in the change history. This is meant to be used when the document is saved.
`getCurrentPosition()` returns a handle to the current position in the change history. This handle can be used to mark this position later, even if it is not the current position anymore.
`atMarkedPosition` property indicates whether the mark is set on the current position in the change history. This can be used to tell whether there are any unsaved changes.
`close()` stops observing change events and should be called when the UndoManager is not used anymore to prevent leaks.
Getting an `UndoManager` instance
---------------------------------
To get an instance of `UndoManager` you need:
* a **stream of change events**.
* a function to **invert** a change.
* a function to **apply** a change. This function must reinsert its parameter into the stream of change events.
* optionally, a function to **merge** two subsequent changes into a single change. The first parameter is the old change, and the second parameter is the newer change.
The _stream of change events_ is a [ReactFX](http://www.reactfx.org/) `EventStream`. For an example of how you can construct one, have a look at the source code of the [demo below](#demo).
The _invert_, _apply_, and _merge_ functions are all instances of [functional interfaces](http://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html) from JDK8, and thus can be instantiated using lambda expressions.
You also need to make sure that your change objects properly implement `equals`.
Once you have all these, you can use one of the factory methods from [UndoManagerFactory](http://www.fxmisc.org/undo/javadoc/org/fxmisc/undo/UndoManagerFactory.html) to get an instance.
```java
EventStream<MyChange> changes = ...;
UndoManager undoManager = UndoManagerFactory.unlimitedHistoryUndoManager(
changes,
change -> invertChange(change),
change -> applyChange(change),
(c1, c2) -> mergeChanges(c1, c2));
```
Demo
----
This demo lets the user change the color, radius and position of a circle, and subsequently undo and redo the performed changes.
Multiple changes of one property in a row are merged together, so, for example, multiple radius changes in a row are tracked as one change.
There is also a "Save" button that fakes a save operation. It is enabled only when changes have been made or undone since the last save.

### Run from the pre-built JAR
[Download](https://github.com/TomasMikula/UndoFX/releases/download/v2.1.0/undofx-demos-fat-2.1.0.jar) the pre-built "fat" JAR file and run
java -cp undofx-demos-fat-2.1.0.jar org.fxmisc.undo.demo.CircleProperties
### Run from the source repo
gradle CircleProperties
### Source code
[CircleProperties.java](https://github.com/TomasMikula/UndoFX/blob/master/undofx-demos/src/main/java/org/fxmisc/undo/demo/CircleProperties.java#L180-L202). See the highlighted lines for the gist of how the undo functionality is set up.
Requirements
------------
[JDK8](https://jdk8.java.net/download.html)
Dependencies
------------
[ReactFX](https://github.com/TomasMikula/ReactFX). If you don't use Maven/Gradle/Sbt/Ivy to manage your dependencies, you will have to either place the ReactFX JAR on the classpath, or download the UndoFX _fat_ JAR (see below) that has ReactFX included.
Use UndoFX in your project
--------------------------
### Maven coordinates
| Group ID | Artifact ID | Version |
| :-------------: | :---------: | :-----: |
| org.fxmisc.undo | undofx | 2.1.1 |
### Gradle example
```groovy
dependencies {
compile group: 'org.fxmisc.undo', name: 'undofx', version: '2.1.1'
}
```
### Sbt example
```scala
libraryDependencies += "org.fxmisc.undo" % "undofx" % "2.1.1"
```
### Manual download
Download [the JAR file](https://github.com/TomasMikula/UndoFX/releases/download/v2.1.1/undofx-2.1.1.jar) or [the fat JAR file (including dependencies)](https://github.com/TomasMikula/UndoFX/releases/download/v2.1.1/undofx-fat-2.1.1.jar) and place it on your classpath.
License
-------
[BSD 2-Clause License](http://opensource.org/licenses/BSD-2-Clause)
Links
-----
[API Documentation (Javadoc)](http://fxmisc.github.io/undo/javadoc/2.1.0/org/fxmisc/undo/package-summary.html)
| {
"content_hash": "13c34928ffa8bdc8c80c1a431bf6d034",
"timestamp": "",
"source": "github",
"line_count": 175,
"max_line_length": 453,
"avg_line_length": 37.51428571428571,
"alnum_prop": 0.7313023610053313,
"repo_name": "TomasMikula/UndoFX",
"id": "d951fa69cbda7d5cbbc507bba8bd6d64c0b3c122",
"size": "6565",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Java",
"bytes": "59600"
}
],
"symlink_target": ""
} |
using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using AH.DUtility;
using AH.ModuleController.DMSSR;
using AH.ModuleController.UI.ACCMS.Reports.Viewer;
namespace AH.ModuleController.UI.DMS.Forms
{
public partial class frmAccountsCollection : AH.Shared.UI.frmSmartFormStandard
{
DMSSR.DMSWSClient dmsSC = new DMSSR.DMSWSClient();
public frmAccountsCollection()
{
InitializeComponent();
}
private void FormatGrid()
{
dgvCollection.ColumnCount = 5;
this.dgvCollection.DefaultCellStyle.Font = new Font("Tahoma", 10);
dgvCollection.ColumnHeadersDefaultCellStyle.Font = new Font("Tahoma", 12);
dgvCollection.Font = new Font("Tahoma", 12);
dgvCollection.Columns[0].Name = "Cash Amount";
dgvCollection.Columns[0].ReadOnly = true;
dgvCollection.Columns[0].Width = 180;
dgvCollection.Columns[1].Name = "Debit Card Amount";
dgvCollection.Columns[1].ReadOnly = true;
dgvCollection.Columns[1].Width = 180;
dgvCollection.Columns[2].Name = "Credit Card Amount";
dgvCollection.Columns[2].ReadOnly = true;
dgvCollection.Columns[2].Width = 180;
dgvCollection.Columns[3].Name = "Total Collection";
dgvCollection.Columns[3].ReadOnly = true;
dgvCollection.Columns[3].Width = 200;
dgvCollection.Columns[4].Name = "Total Refund";
dgvCollection.Columns[4].ReadOnly = true;
dgvCollection.Columns[4].Width = 180;
}
private void frmAccountsCollection_Load(object sender, EventArgs e)
{
try
{
FormatGrid();
txtUserID.Text = Utility.UserId;
txtUserName.Text = Utility.UserName;
}
catch (System.ServiceModel.CommunicationException commp)
{
MessageBox.Show(Utility.CommunicationErrorMsg, Utility.MessageCaptionMsg, MessageBoxButtons.OK, MessageBoxIcon.Warning);
this.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), Utility.MessageCaptionMsg, MessageBoxButtons.OK, MessageBoxIcon.Warning);
this.Close();
}
}
private void LoadGridView(string CollectionDate,string UserID)
{
dgvCollection.Rows.Clear();
int i = 0;
double payment = 0;
List<AccountsPayment> oAccounts = dmsSC.GetAccountsPayment(dtCollDate.Text.ToString(),txtUserID.Text.ToString()).ToList();
if (oAccounts.Count > 0)
{
foreach (AccountsPayment oAccount in oAccounts)
{
dgvCollection.Rows.Add(1);
dgvCollection.Rows[i].Cells[0].Value = oAccount.CashAmount;
dgvCollection.Rows[i].Cells[1].Value = oAccount.DebitCardAmount;
dgvCollection.Rows[i].Cells[2].Value = oAccount.CreditCardAmount;
dgvCollection.Rows[i].Cells[3].Value = oAccount.TotalCollection;
dgvCollection.Rows[i].Cells[4].Value = oAccount.RefundAmount;
payment =Convert.ToDouble(dgvCollection.Rows[i].Cells[3].Value) - Convert.ToDouble(dgvCollection.Rows[i].Cells[4].Value);
i = i + 1;
}
txtFinalPayment.Text = payment.ToString();
}
}
private void btnShow_Click(object sender, EventArgs e)
{
try
{
List<string> vf = new List<string>() { "dtCollDate", "txtEmpID" };
Control control = Utility.ReqFieldValidator(this, vf);
if (control != null)
{
MessageBox.Show(Utility.getFMS(control.Name) + Utility.Req, Utility.MessageCaptionMsg, MessageBoxButtons.OK, MessageBoxIcon.Warning);
control.Focus();
return;
}
LoadGridView(dtCollDate.Text.ToString(), txtUserID.Text.ToString());
}
catch (System.ServiceModel.CommunicationException commp)
{
MessageBox.Show(Utility.CommunicationErrorMsg, Utility.MessageCaptionMsg, MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), Utility.MessageCaptionMsg, MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private AccountsPayment PopulateAccountsPayment()
{
AccountsPayment oAccountObj = new AccountsPayment();
for (int i = 0; i < dgvCollection.Rows.Count; i++)
{
oAccountObj.UserID = txtUserID.Text;
oAccountObj.CashAmount =Convert.ToDouble(dgvCollection.Rows[i].Cells[0].Value.ToString());
oAccountObj.CreditCardAmount = Convert.ToDouble(dgvCollection.Rows[i].Cells[2].Value.ToString());
oAccountObj.DebitCardAmount = Convert.ToDouble(dgvCollection.Rows[i].Cells[1].Value.ToString());
oAccountObj.PaymentAmount = Convert.ToDouble(txtFinalPayment.Text.ToString());
oAccountObj.Remarks = txtRemarks.Text;
oAccountObj.CollectionDate = dtCollDate.Text.ToString();
EntryParameter ep = new EntryParameter();
ep.EntryBy = Utility.UserId;
ep.CompanyID = Utility.CompanyID;
ep.LocationID = Utility.LocationID;
ep.MachineID = Utility.MachineID;
oAccountObj.EntryParameter = ep;
}
return oAccountObj;
}
private void btnSave_Click(object sender, EventArgs e)
{
List<string> vf = new List<string>() { "txtEmpID"};
Control control = Utility.ReqFieldValidator(this, vf);
if (control != null)
{
MessageBox.Show(Utility.getFMS(control.Name) + Utility.Req, Utility.MessageCaptionMsg, MessageBoxButtons.OK, MessageBoxIcon.Warning);
control.Focus();
return;
}
if(dgvCollection.Rows.Count==0)
{
MessageBox.Show("No Collection Have to Sent..", Utility.MessageCaptionMsg, MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
int FinalPayment =Convert.ToInt32(txtFinalPayment.Text.ToString());
if (FinalPayment <= 0)
{
MessageBox.Show("No Collection!Please Wait For Collection..", Utility.MessageCaptionMsg, MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
for (int i = 0; i < dgvCollection.Rows.Count; i++)
{
if(Convert.ToDouble(dgvCollection.Rows[i].Cells[0].Value)<0)
{
MessageBox.Show("Please Wait For Cash Collection..", Utility.MessageCaptionMsg, MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
}
try
{
AccountsPayment oAccountObj = this.PopulateAccountsPayment();
string i = dmsSC.SaveAccountsPayment(oAccountObj);
if (i == "0")
{
MessageBox.Show(Utility.InsertMsg, Utility.MessageCaptionMsg, MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else if (i != "0")
{
MessageBox.Show(Utility.InsertMsg, Utility.MessageSuccessCaption, MessageBoxButtons.OK, MessageBoxIcon.Information);
dgvCollection.Rows.Clear();
btnShow_Click(sender, e);
txtVoucherNo.Text =i;
PrintVoucher(txtVoucherNo.Text);
}
}
catch (System.ServiceModel.CommunicationException commp)
{
MessageBox.Show(Utility.CommunicationErrorMsg, Utility.MessageCaptionMsg, MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), Utility.MessageCaptionMsg, MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private void PrintVoucher(string VoucherNo)
{
frmReportViewer frm = new frmReportViewer();
frm.selector = ViewerSelector.Pvoucher;
frm.intVoucherType = 2;
frm.WhereCondition = VoucherNo.ToString();
frm.Where2 = "N";
frm.strFromDate = DateTime.Now.ToString("dd/MM/yyyy");
frm.strToDate = DateTime.Now.ToString("dd/MM/yyyy");
frm.strBranchID = "0001";
frm.strControls = "Individual";
frm.ShowDialog();
}
#region CashManagemnt
private void UpdateTotalAmount(string OneThou,string FiveHun,string OneHun,string Fitfy,string Twenty,string Ten,string Five,string Two,string One)
{
double sum = 0;
sum = Convert.ToDouble(OneThou.ToString()) + Convert.ToDouble(FiveHun.ToString()) + Convert.ToDouble(OneHun.ToString()) +
Convert.ToDouble(Fitfy.ToString()) + Convert.ToDouble(Twenty.ToString()) + Convert.ToDouble(Ten.ToString()) +
Convert.ToDouble(Five.ToString()) + Convert.ToDouble(Two.ToString()) + Convert.ToDouble(One.ToString());
lblTotal.Text = sum.ToString();
}
private void txt1000_TextChanged(object sender, EventArgs e)
{
if (txt1000.Text != "")
{
txtTotal1000.Text = (1000 * Convert.ToDouble(txt1000.Text.ToString())).ToString();
}
else
{
txtTotal1000.Text = "0";
}
UpdateTotalAmount(txtTotal1000.Text, "0", "0", "0", "0", "0", "0", "0", "0");
}
private void txt500_TextChanged(object sender, EventArgs e)
{
if (txt500.Text != "")
{
txtTotal500.Text = (500 * Convert.ToDouble(txt500.Text.ToString())).ToString();
}
else
{
txtTotal500.Text = "0";
}
UpdateTotalAmount(txtTotal1000.Text, txtTotal500.Text, "0", "0", "0", "0", "0", "0", "0");
}
private void txt100_TextChanged(object sender, EventArgs e)
{
if (txt100.Text != "")
{
txtTotal100.Text = (100 * Convert.ToDouble(txt100.Text.ToString())).ToString();
}
else
{
txtTotal100.Text = "0";
}
UpdateTotalAmount(txtTotal1000.Text, txtTotal500.Text, txtTotal100.Text, "0", "0", "0", "0", "0", "0");
}
private void txt50_TextChanged(object sender, EventArgs e)
{
if (txt50.Text != "")
{
txtTotal50.Text = (50 * Convert.ToDouble(txt50.Text.ToString())).ToString();
}
else
{
txtTotal50.Text = "0";
}
UpdateTotalAmount(txtTotal1000.Text, txtTotal500.Text, txtTotal100.Text, txtTotal50.Text, "0", "0", "0", "0", "0");
}
private void txt20_TextChanged(object sender, EventArgs e)
{
if (txt20.Text != "")
{
txtTotal20.Text = (20 * Convert.ToDouble(txt20.Text.ToString())).ToString();
}
else
{
txtTotal20.Text = "0";
}
UpdateTotalAmount(txtTotal1000.Text, txtTotal500.Text, txtTotal100.Text, txtTotal50.Text, txtTotal20.Text, "0", "0", "0", "0");
}
private void txt10_TextChanged(object sender, EventArgs e)
{
if (txt10.Text != "")
{
txtTotal10.Text = (10 * Convert.ToDouble(txt10.Text.ToString())).ToString();
}
else
{
txtTotal10.Text = "0";
}
UpdateTotalAmount(txtTotal1000.Text, txtTotal500.Text, txtTotal100.Text, txtTotal50.Text, txtTotal20.Text, txtTotal10.Text, "0", "0", "0");
}
private void txt5_TextChanged(object sender, EventArgs e)
{
if (txt5.Text != "")
{
txtTotal5.Text = (5 * Convert.ToDouble(txt5.Text.ToString())).ToString();
}
else
{
txtTotal5.Text = "0";
}
UpdateTotalAmount(txtTotal1000.Text, txtTotal500.Text, txtTotal100.Text, txtTotal50.Text, txtTotal20.Text, txtTotal10.Text, txtTotal5.Text, "0", "0");
}
private void txt2_TextChanged(object sender, EventArgs e)
{
if (txt2.Text != "")
{
txtTotal2.Text = (2 * Convert.ToDouble(txt2.Text.ToString())).ToString();
}
else
{
txtTotal2.Text = "0";
}
UpdateTotalAmount(txtTotal1000.Text, txtTotal500.Text, txtTotal100.Text, txtTotal50.Text, txtTotal20.Text, txtTotal10.Text, txtTotal5.Text, txtTotal2.Text, "0");
}
private void txt1_TextChanged(object sender, EventArgs e)
{
if (txt1.Text != "")
{
txtTotal1.Text = (1 * Convert.ToDouble(txt1.Text.ToString())).ToString();
}
else
{
txtTotal1.Text = "0";
}
UpdateTotalAmount(txtTotal1000.Text, txtTotal500.Text, txtTotal100.Text, txtTotal50.Text, txtTotal20.Text, txtTotal10.Text, txtTotal5.Text, txtTotal2.Text, txtTotal1.Text);
}
#endregion
}
}
| {
"content_hash": "9fd680497166ce435fc65fdf9d6996f9",
"timestamp": "",
"source": "github",
"line_count": 337,
"max_line_length": 184,
"avg_line_length": 41.833827893175076,
"alnum_prop": 0.548162859980139,
"repo_name": "atiq-shumon/DotNetProjects",
"id": "5137da8c1bb573a283ecd4c5267d974817dbc9ca",
"size": "14100",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Hospital_ERP_VS13-WCF_WF/AH.ModuleController/UI/DMS/Forms/frmAccountsCollection.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "1059021"
},
{
"name": "C#",
"bytes": "39389238"
},
{
"name": "CSS",
"bytes": "683218"
},
{
"name": "HTML",
"bytes": "44772"
},
{
"name": "JavaScript",
"bytes": "1343054"
},
{
"name": "PLpgSQL",
"bytes": "340074"
},
{
"name": "Pascal",
"bytes": "81971"
},
{
"name": "PowerShell",
"bytes": "175142"
},
{
"name": "Puppet",
"bytes": "2111"
},
{
"name": "Smalltalk",
"bytes": "9"
},
{
"name": "XSLT",
"bytes": "12347"
}
],
"symlink_target": ""
} |
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
req.output.title = "Gateways | Status";
res.render('gateways', req.output);
});
/* GET gateway id page. */
router.get('/:*', function(req, res, next) {
req.output.title = "Gateways | Status";
console.log(req.path.split(":")[1]);
res.render('gateways', req.output);
});
router.post('/add', function(req, res, next) {
req.output.title = "Welcome | IOTGroup";
var users = req.db.get("users");
users.findOne({email: req.session.user.email},function(err,docs){
if (typeof docs.gateways !== "undefined")
{
docs.gateways.push(req.body);
users.update({email: req.session.user.email},{$set: docs});
console.log(docs);
}
});
res.redirect("/gateways");
});
router.post('/edit', function(req, res, next) {
req.output.title = "Welcome | IOTGroup";
var users = req.db.get("users");
users.findOne({email: req.session.user.email},function(err,docs){
if (typeof docs.gateways !== "undefined")
{
docs.gateways.forEach(function(gateway){
if (gateway.serial == req.body.serial)
{
gateway.name = req.body.name;
}
});
users.update({email: req.session.user.email},{$set: docs});
}
});
res.redirect("/gateways");
});
router.post('/del', function(req, res, next) {
req.output.title = "Welcome | IOTGroup";
var users = req.db.get("users");
users.findOne({email: req.session.user.email},function(err,docs){
if (typeof docs.gateways !== "undefined")
{
console.log(docs.gateways);
var gateways = [];
docs.gateways.forEach(function(gateway,i){
if (gateway.serial != req.body.serial)
gateways.push(gateway);
});
docs.gateways = gateways;
console.log(docs.gateways);
users.update({email: req.session.user.email},{$set: docs});
}
});
res.redirect("/gateways");
});
router.post('/nodes/edit', function(req, res, next) {
req.output.title = "Welcome | IOTGroup";
var users = req.db.get("users");
users.findOne({email: req.session.user.email},function(err,docs){
if (typeof docs.gateways !== "undefined")
{
docs.gateways.forEach(function(gateway){
if (gateway.serial == req.body.gateway_serial)
{
console.log("Found Gateway in user")
var bigdata = req.db.get("bigdata");
bigdata.findOne({serial: req.body.gateway_serial},function(err,docs){
console.log("Found Gateway in bigdata")
docs.nodes.forEach(function(node){
if (node.serial == req.body.serial)
{
console.log("Found Node",req.body)
node.desc = req.body.desc;
node.location.lat = req.body.lat;
node.location.lon = req.body.lon;
}
});
bigdata.update({serial: req.body.gateway_serial},{$set: docs});
});
}
});
}
});
res.redirect("/gateways");
});
module.exports = router;
| {
"content_hash": "ebf38983962eefd7048c230afba713aa",
"timestamp": "",
"source": "github",
"line_count": 100,
"max_line_length": 81,
"avg_line_length": 31.45,
"alnum_prop": 0.575516693163752,
"repo_name": "JacoBezuidenhout/NodeProjects",
"id": "1055e894db3b579af1a2167242fe1f0a48b48711",
"size": "3145",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "MTGGroup/old_projects/iot/routes/gateways.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "266890"
},
{
"name": "HTML",
"bytes": "746448"
},
{
"name": "Handlebars",
"bytes": "275369"
},
{
"name": "JavaScript",
"bytes": "8932132"
},
{
"name": "PHP",
"bytes": "2244"
},
{
"name": "Python",
"bytes": "1354"
}
],
"symlink_target": ""
} |
using System.Collections.Generic;
namespace Papper.Internal
{
internal static class InternalExtensions
{
/// <summary>
/// Removes an element from the middle of a queue without disrupting the other elements.
/// </summary>
/// <typeparam name="T">The element to remove.</typeparam>
/// <param name="queue">The queue to modify.</param>
/// <param name="valueToRemove">The value to remove.</param>
/// <remarks>
/// If a value appears multiple times in the queue, only its first entry is removed.
/// </remarks>
internal static bool RemoveMidQueue<TQueue>(this Queue<TQueue> queue, TQueue valueToRemove) where TQueue : class
{
int originalCount = queue.Count;
int dequeueCounter = 0;
bool found = false;
while (dequeueCounter < originalCount)
{
dequeueCounter++;
TQueue dequeued = queue.Dequeue();
if (!found && dequeued == valueToRemove)
{
// only find 1 match
found = true;
}
else
{
queue.Enqueue(dequeued);
}
}
return found;
}
}
}
| {
"content_hash": "f35b88aa801233807fb80cb24c8bbdd1",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 120,
"avg_line_length": 32.9,
"alnum_prop": 0.5159574468085106,
"repo_name": "proemmer/papper",
"id": "38ff8ad7d973d45d224821f32fb269dff2f6f83c",
"size": "1318",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Papper/src/Papper/Internal/InternalExtensions.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "1114160"
},
{
"name": "Smalltalk",
"bytes": "262"
}
],
"symlink_target": ""
} |
sea-b20-day16hw-MeanMedianModeBackbone
======================================
Mean, Median, and Mode (now with Backbone!)
To test (or use) run server.js and grunt watchForBuild.
Enter numbers as a comma separated list of values, ie:
``` 1,1999,5,5,18,0,16,404,16 ```

| {
"content_hash": "89c6bd79f1d59ec7413675e01e0fb78c",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 83,
"avg_line_length": 29.666666666666668,
"alnum_prop": 0.648876404494382,
"repo_name": "MJGrant/sea-b20-day16hw-MeanMedianModeBackbone",
"id": "5b7c96c589b5d050c139a99efd3e544d9950bda7",
"size": "356",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1636"
},
{
"name": "JavaScript",
"bytes": "1039923"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>classical-realizability: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.8.0 / classical-realizability - 8.10.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
classical-realizability
<small>
8.10.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-11-04 17:24:13 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-11-04 17:24:13 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-num base Num library distributed with the OCaml compiler
base-threads base
base-unix base
camlp5 7.14 Preprocessor-pretty-printer of OCaml
conf-findutils 1 Virtual package relying on findutils
conf-perl 2 Virtual package relying on perl
coq 8.8.0 Formal proof management system
num 0 The Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.03.0 The OCaml compiler (virtual package)
ocaml-base-compiler 4.03.0 Official 4.03.0 release
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.5 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "[email protected]"
homepage: "https://github.com/coq-contribs/classical-realizability"
license: "BSD"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/ClassicalRealizability"]
depends: [
"ocaml"
"coq" {>= "8.10" & < "8.11~"}
]
tags: [
"keyword: classical realizability"
"keyword: Krivine's realizability"
"keyword: primitive datatype"
"keyword: non determinism"
"keyword: quote"
"keyword: axiom of countable choice"
"keyword: real numbers"
"category: Mathematics/Logic/Foundations"
]
authors: [
"Lionel Rieg <[email protected]>"
]
bug-reports: "https://github.com/coq-contribs/classical-realizability/issues"
dev-repo: "git+https://github.com/coq-contribs/classical-realizability.git"
synopsis: "Krivine's classical realizability"
description: """
The aim of this Coq library is to provide a framework for checking
proofs in Krivine's classical realizability for second-order Peano arithmetic.
It is designed to be as extensible as the original theory by Krivine and to
support on-the-fly extensions by new instructions with their evaluation
rules."""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/classical-realizability/archive/v8.10.0.tar.gz"
checksum: "md5=988099e8c3d1b7110aa0faf0a2a21128"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-classical-realizability.8.10.0 coq.8.8.0</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.8.0).
The following dependencies couldn't be met:
- coq-classical-realizability -> coq >= 8.10 -> ocaml >= 4.05.0
base of this switch (use `--unlock-base' to force)
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-classical-realizability.8.10.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "549fcc32f5ad4e22fa04b8456db9ad56",
"timestamp": "",
"source": "github",
"line_count": 179,
"max_line_length": 159,
"avg_line_length": 41.87150837988827,
"alnum_prop": 0.5611741160773849,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "5884f14468d460e469ffa2761b086655f8f91426",
"size": "7520",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.03.0-2.0.5/released/8.8.0/classical-realizability/8.10.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
import logging
import grpc
from pkg.apis.manager.v1beta1.python import api_pb2
from pkg.apis.manager.v1beta1.python import api_pb2_grpc
from pkg.suggestion.v1beta1.internal.search_space import HyperParameterSearchSpace
from pkg.suggestion.v1beta1.internal.trial import Trial, Assignment
from pkg.suggestion.v1beta1.hyperopt.base_service import BaseHyperoptService
from pkg.suggestion.v1beta1.internal.base_health_service import HealthServicer
logger = logging.getLogger(__name__)
class HyperoptService(api_pb2_grpc.SuggestionServicer, HealthServicer):
def __init__(self):
super(HyperoptService, self).__init__()
self.base_service = None
self.is_first_run = True
def GetSuggestions(self, request, context):
"""
Main function to provide suggestion.
"""
name, config = OptimizerConfiguration.convert_algorithm_spec(
request.experiment.spec.algorithm)
if self.is_first_run:
search_space = HyperParameterSearchSpace.convert(request.experiment)
self.base_service = BaseHyperoptService(
algorithm_name=name,
algorithm_conf=config,
search_space=search_space)
self.is_first_run = False
trials = Trial.convert(request.trials)
new_assignments = self.base_service.getSuggestions(trials, request.current_request_number)
return api_pb2.GetSuggestionsReply(
parameter_assignments=Assignment.generate(new_assignments)
)
def ValidateAlgorithmSettings(self, request, context):
is_valid, message = OptimizerConfiguration.validate_algorithm_spec(
request.experiment.spec.algorithm)
if not is_valid:
context.set_code(grpc.StatusCode.INVALID_ARGUMENT)
context.set_details(message)
logger.error(message)
return api_pb2.ValidateAlgorithmSettingsReply()
class OptimizerConfiguration:
__conversion_dict = {
'tpe': {
'gamma': lambda x: float(x),
'prior_weight': lambda x: float(x),
'n_EI_candidates': lambda x: int(x),
"random_state": lambda x: int(x),
},
"random": {
"random_state": lambda x: int(x),
}
}
@classmethod
def convert_algorithm_spec(cls, algorithm_spec):
ret = {}
setting_schema = cls.__conversion_dict[algorithm_spec.algorithm_name]
for s in algorithm_spec.algorithm_settings:
if s.name in setting_schema:
ret[s.name] = setting_schema[s.name](s.value)
return algorithm_spec.algorithm_name, ret
@classmethod
def validate_algorithm_spec(cls, algorithm_spec):
algo_name = algorithm_spec.algorithm_name
if algo_name == 'tpe':
return cls._validate_tpe_setting(algorithm_spec.algorithm_settings)
elif algo_name == 'random':
return cls._validate_random_setting(algorithm_spec.algorithm_settings)
else:
return False, "unknown algorithm name {}".format(algo_name)
@classmethod
def _validate_tpe_setting(cls, algorithm_settings):
for s in algorithm_settings:
try:
if s.name == 'gamma':
if not 1 > float(s.value) > 0:
return False, "gamma should be in the range of (0, 1)"
elif s.name == 'prior_weight':
if not float(s.value) > 0:
return False, "prior_weight should be great than zero"
elif s.name == 'n_EI_candidates':
if not int(s.value) > 0:
return False, "n_EI_candidates should be great than zero"
elif s.name == 'random_state':
if not int(s.value) >= 0:
return False, "random_state should be great or equal than zero"
else:
return False, "unknown setting {} for algorithm tpe".format(s.name)
except Exception as e:
return False, "failed to validate {name}({value}): {exception}".format(
name=s.name, value=s.value, exception=e)
return True, ""
@classmethod
def _validate_random_setting(cls, algorithm_settings):
for s in algorithm_settings:
try:
if s.name == 'random_state':
if not (int(s.value) >= 0):
return False, "random_state should be great or equal than zero"
else:
return False, "unknown setting {} for algorithm random".format(s.name)
except Exception as e:
return False, "failed to validate {name}({value}): {exception}".format(
name=s.name, value=s.value, exception=e)
return True, ""
| {
"content_hash": "064aedb403fcf895cba130fae8c11b0d",
"timestamp": "",
"source": "github",
"line_count": 123,
"max_line_length": 98,
"avg_line_length": 39.58536585365854,
"alnum_prop": 0.5970425138632163,
"repo_name": "kubeflow/katib",
"id": "854f2447131638e3f7dee18941b2ed88dacff751",
"size": "5454",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pkg/suggestion/v1beta1/hyperopt/service.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "892"
},
{
"name": "Dockerfile",
"bytes": "17663"
},
{
"name": "Go",
"bytes": "762583"
},
{
"name": "HTML",
"bytes": "112818"
},
{
"name": "JavaScript",
"bytes": "325581"
},
{
"name": "Makefile",
"bytes": "5703"
},
{
"name": "Python",
"bytes": "884171"
},
{
"name": "SCSS",
"bytes": "4261"
},
{
"name": "Shell",
"bytes": "60643"
},
{
"name": "TypeScript",
"bytes": "193459"
}
],
"symlink_target": ""
} |
define([
'underscore',
'event-emitter',
'./http-client',
'./priority-queue'],
function (_, EventEmitter, HttpClient, PriorityQueue) {
/**
* Generates an RFC4122-compliant GUID.
* See http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript.
* @returns {String} A unique RFC4122-compliant GUID.
*/
var _generateGuid = function () {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,
function (c) {
var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
}).toUpperCase();
};
/**
* Compares the priority of two http requests and decides which is higher priority.
* @param {Object} a The left operand.
* @param {Object} b The right operand.
* @return {Number} The result of the comparison of the two requests.
*/
var _requestPriorityComparer = function (a, b) {
if (a.priority === b.priority) {
return 0;
}
if (a.priority > b.priority) {
return 1;
}
return -1;
};
var restque = function () {
this._http_client = new HttpClient();
this._queue = new PriorityQueue(_requestPriorityComparer);
this._id = _generateGuid();
this._requests_in_progress = {};
this._requests_in_progress_count = 0;
this._max_requests = 2;
this._queue_timer_interval = 500;
};
restque.prototype = Object.create(EventEmitter.prototype);
restque.prototype._setQueueTimer = function () {
if (this._processQueueTimer) {
clearTimeout(this._processQueueTimer);
}
var self = this;
this._processQueueTimer = setTimeout(
function () {
self._processQueue.call(self, false);
},
this._queue_timer_interval);
};
restque.prototype._shouldProcessQueue = function () {
var should_process = true;
if (this._queue.peek() === null) { // There's nothing to process
should_process = false;
} else if (this._requests_in_progress_count >= this._max_requests) { // Max requests are in progress
should_process = false;
}
return should_process;
};
restque.prototype._processQueue = function (kicked) {
while (this._shouldProcessQueue()) {
var next_request = this._queue.next();
if (!next_request.is_cancelled) {
this._doRequest(next_request);
}
}
if (!kicked) {
this._setQueueTimer();
}
};
restque.prototype._kickQueue = function () {
this._processQueue(true);
};
restque.prototype._requestCompleted = function (err, request, response) {
this._requests_in_progress_count--;
if (this._requests_in_progress[request.id]) {
delete(this._requests_in_progress[request.id]);
}
if (!request.is_cancelled && response.status_code === 401) {
this.trigger('authentication_required', [request, response]);
} else if (!request.is_cancelled && _.isFunction(request.done)) {
if (!request.quiet && (err || (response.status_code !== 200 && response.status_code !== 201))) {
this.trigger('request_failed', [request, response]);
}
if (request.context) {
request.done.apply(request.context, [err, request, response]);
} else {
request.done(err, request, response);
}
}
};
restque.prototype._doRequest = function (request) {
request.handle = this._http_client.request(request, this, this._requestCompleted);
this._requests_in_progress[request.id] = request;
this._requests_in_progress_count++;
};
restque.prototype._queueRequest = function (method, url, data, options, done) {
if (_.isFunction(options)) {
done = options;
options = null;
}
options = options || {};
var request = {
id: _generateGuid(),
url: url,
method: method,
data: data,
priority: options.priority || 1,
done: done,
context: options.context,
timeout: options.timeout,
restque_id: this._id,
is_cancelled: false,
quiet: options.quiet || false
};
this._queue.add(request);
this._kickQueue();
return request.id;
};
/**
* Gets a new restque instance that shares the same underlying queue as this instance.
* Requests sent via the new instance can be cancelled as a set without affecting requests
* sent through other restque instances.
*/
restque.prototype.taggedRestque = function () {
// Create a new restque instance which will have its own unique id.
// Set the queue and http client to the same as this instance so the underlying queue is shared.
var tagged_restque = new restque();
tagged_restque._queue = this._queue;
tagged_restque._http_cleint = this._http_client;
return tagged_restque;
};
restque.prototype._cancelRequest = function (request) {
request.is_cancelled = true;
if (request.handle) {
request.handle.abort();
}
};
restque.prototype.cancel = function () {
var key,
request;
for (key in this._requests_in_progress) {
if (this._requests_in_progress.hasOwnProperty(key)) {
request = this._requests_in_progress[key];
if (request.restque_id === this._id) {
this._cancelRequest(request);
delete this._requests_in_progress[key];
this._requests_in_progress_count--;
}
}
}
var i,
found = false;
for (i = 0; i < this._queue.count(); i++) {
request = this._queue.peekAtIndex(i);
if (request.restque_id === this._id) {
this._cancelRequest(request);
this._queue.removeAtIndex(i);
found = true;
break;
}
}
if (found) {
this.cancel();
}
};
restque.prototype.get = function (url, options, done) {
this._queueRequest('GET', url, null, options, done);
};
restque.prototype.post = function (url, data, options, done) {
this._queueRequest('POST', url, data, options, done);
};
restque.prototype.put = function (url, data, options, done) {
this._queueRequest('PUT', url, data, options, done);
};
restque.prototype.delete_ = function (url, options, done) {
this._queueRequest('DELETE', url, null, options, done);
};
if (!window.restque) {
window.restque = new restque();
}
return window.restque;
}
); | {
"content_hash": "44bed70f1e0e0b992318a08c288db9fe",
"timestamp": "",
"source": "github",
"line_count": 227,
"max_line_length": 112,
"avg_line_length": 34.418502202643175,
"alnum_prop": 0.49635223345705876,
"repo_name": "Diggs/restque",
"id": "e2b836ddfaae2e6b70ab0405f4800b08e0cecf0f",
"size": "7813",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/restque.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "17296"
}
],
"symlink_target": ""
} |
using System.Data.Entity;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
namespace MVC5Skeleton.Models
{
// You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
} | {
"content_hash": "378d46de2efe6bdbb4b9f1357e709559",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 175,
"avg_line_length": 36.63636363636363,
"alnum_prop": 0.707196029776675,
"repo_name": "gvaduha/homebrew",
"id": "c18a9ea7cd8369fb87fa152715dcd151b1b0c6c8",
"size": "1211",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "csharp/MVC5Skeleton/Models/IdentityModels.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "103"
},
{
"name": "Batchfile",
"bytes": "627"
},
{
"name": "C#",
"bytes": "79073"
},
{
"name": "C++",
"bytes": "23472"
},
{
"name": "CSS",
"bytes": "513"
},
{
"name": "HTML",
"bytes": "102270"
},
{
"name": "JavaScript",
"bytes": "14708"
},
{
"name": "PowerShell",
"bytes": "215"
},
{
"name": "Python",
"bytes": "17241"
},
{
"name": "Shell",
"bytes": "10004"
},
{
"name": "Visual Basic",
"bytes": "5191"
}
],
"symlink_target": ""
} |
package com.example.android.sunshine.app.model;
import android.graphics.Bitmap;
import java.util.Date;
/**
* Created by cristhian on 4/07/16.
*/
public class TodayWeather {
private int weatherId;
private String todayDate;
private String todayMaxTemp;
private String todayMinTemp;
private Bitmap todayWeatherIcon;
public TodayWeather(int weatherId, String todayDate, String todayMaxTemp, String todayMinTemp, Bitmap todayWeatherIcon) {
this.weatherId = weatherId;
this.todayDate = todayDate;
this.todayMaxTemp = todayMaxTemp;
this.todayMinTemp = todayMinTemp;
this.todayWeatherIcon = todayWeatherIcon;
}
public int getWeatherId() {
return weatherId;
}
public void setWeatherId(int weatherId) {
this.weatherId = weatherId;
}
public String getTodayDate() {
return todayDate;
}
public void setTodayDate(String todayDate) {
this.todayDate = todayDate;
}
public String getTodayMaxTemp() {
return todayMaxTemp;
}
public void setTodayMaxTemp(String todayMaxTemp) {
this.todayMaxTemp = todayMaxTemp;
}
public String getTodayMinTemp() {
return todayMinTemp;
}
public void setTodayMinTemp(String todayMinTemp) {
this.todayMinTemp = todayMinTemp;
}
public Bitmap getTodayWeatherIcon() {
return todayWeatherIcon;
}
public void setTodayWeatherIcon(Bitmap todayWeatherIcon) {
this.todayWeatherIcon = todayWeatherIcon;
}
}
| {
"content_hash": "c39575f7c1858ff155f7b435982f9c7d",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 125,
"avg_line_length": 23.876923076923077,
"alnum_prop": 0.6791237113402062,
"repo_name": "cristh18/Sunshine",
"id": "217386fb50785a2321b01eafd077c8c7a2571b69",
"size": "1552",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/java/com/example/android/sunshine/app/model/TodayWeather.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "290857"
}
],
"symlink_target": ""
} |
Krylov Documentation
====================
This page contains the Krylov Package documentation.
The :mod:`_bicgstab` Module
---------------------------
.. automodule:: pyamg.krylov._bicgstab
:members:
:undoc-members:
:show-inheritance:
The :mod:`_cg` Module
---------------------
.. automodule:: pyamg.krylov._cg
:members:
:undoc-members:
:show-inheritance:
The :mod:`_cgne` Module
-----------------------
.. automodule:: pyamg.krylov._cgne
:members:
:undoc-members:
:show-inheritance:
The :mod:`_cgnr` Module
-----------------------
.. automodule:: pyamg.krylov._cgnr
:members:
:undoc-members:
:show-inheritance:
The :mod:`_fgmres` Module
-------------------------
.. automodule:: pyamg.krylov._fgmres
:members:
:undoc-members:
:show-inheritance:
The :mod:`_gmres` Module
------------------------
.. automodule:: pyamg.krylov._gmres
:members:
:undoc-members:
:show-inheritance:
The :mod:`_gmres_householder` Module
------------------------------------
.. automodule:: pyamg.krylov._gmres_householder
:members:
:undoc-members:
:show-inheritance:
The :mod:`_gmres_mgs` Module
----------------------------
.. automodule:: pyamg.krylov._gmres_mgs
:members:
:undoc-members:
:show-inheritance:
The :mod:`setup` Module
-----------------------
.. automodule:: pyamg.krylov.setup
:members:
:undoc-members:
:show-inheritance:
| {
"content_hash": "b71017fd3a9a06e0573eb300e5b9b55b",
"timestamp": "",
"source": "github",
"line_count": 77,
"max_line_length": 52,
"avg_line_length": 18.753246753246753,
"alnum_prop": 0.5422437673130194,
"repo_name": "pombreda/pyamg",
"id": "c72e25eb819657998ef837c8d45a4412f524f505",
"size": "1444",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Docs/source/pyamg.krylov.rst",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C++",
"bytes": "1112880"
},
{
"name": "CSS",
"bytes": "9832"
},
{
"name": "Makefile",
"bytes": "3249"
},
{
"name": "Matlab",
"bytes": "2742"
},
{
"name": "Python",
"bytes": "1215339"
},
{
"name": "Shell",
"bytes": "558"
},
{
"name": "TeX",
"bytes": "232"
}
],
"symlink_target": ""
} |
<?php
namespace Pulpy\CoreBundle\Services\Post;
use Pulpy\CoreBundle\Entity\AbstractPost,
Pulpy\CoreBundle\Services\ResourceResolverService;
class PostResourceResolverService extends ResourceResolverService {
public function fileForPostAndResourceName(AbstractPost $post, $name) {
return $this->fileForResourceName($name);
}
public function urlForPostAndResourceName(AbstractPost $post, $name) {
$file = $this->fileForPostAndResourceName($post, $name);
if(is_null($file)) {
return null;
}
return $this->fs->getUrl($file);
}
} | {
"content_hash": "7b09d7b98b1b78345fc5f6e75ac45fe9",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 75,
"avg_line_length": 26.608695652173914,
"alnum_prop": 0.6879084967320261,
"repo_name": "netgusto/PPSymfony",
"id": "a0d090b14c7b5812a17b66f92dbd80aedf9e165b",
"size": "612",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Pulpy/CoreBundle/Services/Post/PostResourceResolverService.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "40828"
},
{
"name": "CoffeeScript",
"bytes": "31"
},
{
"name": "JavaScript",
"bytes": "900"
},
{
"name": "PHP",
"bytes": "185241"
}
],
"symlink_target": ""
} |
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschraenkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Orleans;
using Squidex.Infrastructure.Orleans;
namespace Squidex.Domain.Apps.Entities.Backup
{
public interface IBackupGrain : IGrainWithGuidKey
{
Task RunAsync();
Task DeleteAsync(Guid id);
Task<J<List<IBackupJob>>> GetStateAsync();
}
}
| {
"content_hash": "d34000e711ada4e0deab826228b2ad0f",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 78,
"avg_line_length": 30.416666666666668,
"alnum_prop": 0.4904109589041096,
"repo_name": "pushrbx/squidex",
"id": "21f66e2ffd26df440431aaa0695abddc9b98d1fb",
"size": "732",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Squidex.Domain.Apps.Entities/Backup/IBackupGrain.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "3242273"
},
{
"name": "CSS",
"bytes": "115407"
},
{
"name": "Dockerfile",
"bytes": "1459"
},
{
"name": "HTML",
"bytes": "428105"
},
{
"name": "JavaScript",
"bytes": "21146"
},
{
"name": "PowerShell",
"bytes": "2918"
},
{
"name": "Shell",
"bytes": "295"
},
{
"name": "TypeScript",
"bytes": "1072715"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_101) on Mon Sep 19 15:00:38 UTC 2016 -->
<title>org.springframework.jca.cci.connection (Spring Framework 4.3.3.RELEASE API)</title><script>var _hmt = _hmt || [];(function() {var hm = document.createElement("script");hm.src = "//hm.baidu.com/hm.js?dd1361ca20a10cc161e72d4bc4fef6df";var s = document.getElementsByTagName("script")[0];s.parentNode.insertBefore(hm, s);})();</script>
<meta name="date" content="2016-09-19">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script>
</head>
<body>
<h1 class="bar"><a href="../../../../../org/springframework/jca/cci/connection/package-summary.html" target="classFrame">org.springframework.jca.cci.connection</a></h1>
<div class="indexContainer">
<h2 title="Classes">Classes</h2>
<ul title="Classes">
<li><a href="CciLocalTransactionManager.html" title="class in org.springframework.jca.cci.connection" target="classFrame">CciLocalTransactionManager</a></li>
<li><a href="ConnectionFactoryUtils.html" title="class in org.springframework.jca.cci.connection" target="classFrame">ConnectionFactoryUtils</a></li>
<li><a href="ConnectionHolder.html" title="class in org.springframework.jca.cci.connection" target="classFrame">ConnectionHolder</a></li>
<li><a href="ConnectionSpecConnectionFactoryAdapter.html" title="class in org.springframework.jca.cci.connection" target="classFrame">ConnectionSpecConnectionFactoryAdapter</a></li>
<li><a href="DelegatingConnectionFactory.html" title="class in org.springframework.jca.cci.connection" target="classFrame">DelegatingConnectionFactory</a></li>
<li><a href="NotSupportedRecordFactory.html" title="class in org.springframework.jca.cci.connection" target="classFrame">NotSupportedRecordFactory</a></li>
<li><a href="SingleConnectionFactory.html" title="class in org.springframework.jca.cci.connection" target="classFrame">SingleConnectionFactory</a></li>
<li><a href="TransactionAwareConnectionFactoryProxy.html" title="class in org.springframework.jca.cci.connection" target="classFrame">TransactionAwareConnectionFactoryProxy</a></li>
</ul>
</div>
</body>
</html>
| {
"content_hash": "6da586763ce97bb93fccaa40b1e635e8",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 338,
"avg_line_length": 86.44444444444444,
"alnum_prop": 0.7493573264781491,
"repo_name": "piterlin/piterlin.github.io",
"id": "9eb3b32e8a5d50d9cda9fcfaafae2ce0dfa635a2",
"size": "2334",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "doc/spring4.3.3-docs/javadoc-api/org/springframework/jca/cci/connection/package-frame.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "479"
},
{
"name": "HTML",
"bytes": "9480869"
},
{
"name": "JavaScript",
"bytes": "246"
}
],
"symlink_target": ""
} |
require 'puppet_x/bsd/hostname_if/trunk'
describe 'Trunk' do
subject(:trunkif) { HostnameIf::Trunk }
describe 'content' do
it 'supports a full example' do
c = {
proto: 'lacp',
interface: ['em0']
}
expect(trunkif.new(c).content).to match(%r{trunkproto lacp trunkport em0})
end
it 'supports a partial example' do
c = {
proto: 'lacp',
interface: %w[
em0
em1
em2
em3
]
}
expect(trunkif.new(c).content).to match(%r{trunkproto lacp trunkport em0 trunkport em1 trunkport em2 trunkport em3})
end
end
end
| {
"content_hash": "821a88b6efdf3ace05da2425736ea006",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 122,
"avg_line_length": 22.75,
"alnum_prop": 0.5682888540031397,
"repo_name": "buzzdeee/puppet-bsd",
"id": "5d8e1faf29e62e18a8053eaaef6cd40872e22f58",
"size": "637",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "spec/unit/bsd/hostname_if/trunk_spec.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Puppet",
"bytes": "17202"
},
{
"name": "Ruby",
"bytes": "120959"
},
{
"name": "Shell",
"bytes": "133"
}
],
"symlink_target": ""
} |
<!doctype html>
<!--
Copyright 2017 The Chromium Authors
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->
<html>
<body>
<webview></webview>
<script src="main.js"></script>
</body>
</html>
| {
"content_hash": "da9b7a6c98cdde2ae904ff55e7ac663c",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 70,
"avg_line_length": 20.416666666666668,
"alnum_prop": 0.6938775510204082,
"repo_name": "nwjs/chromium.src",
"id": "eba2601e0a1622b29fc9235251e9d3c9a192fae4",
"size": "245",
"binary": false,
"copies": "6",
"ref": "refs/heads/nw70",
"path": "chrome/test/data/extensions/platform_apps/web_view/audio_state_api/main.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
// This file is automatically generated.
package adila.db;
/*
* LG Spectrum
*
* DEVICE: i_vzw
* MODEL: VS920 4G
*/
final class i5fvzw {
public static final String DATA = "LG|Spectrum|";
}
| {
"content_hash": "7d293b6777c6c02b68a378d0a0ca15e1",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 53,
"avg_line_length": 15.307692307692308,
"alnum_prop": 0.6582914572864321,
"repo_name": "karim/adila",
"id": "7f83cb6b52c82f17113e1cc167c6a3498e0dc146",
"size": "199",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "database/src/main/java/adila/db/i5fvzw.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "2903103"
},
{
"name": "Prolog",
"bytes": "489"
},
{
"name": "Python",
"bytes": "3280"
}
],
"symlink_target": ""
} |
package worker
import (
"context"
"fmt"
"github.com/ohsu-comp-bio/funnel/cmd/version"
"github.com/ohsu-comp-bio/funnel/config"
"github.com/ohsu-comp-bio/funnel/events"
"github.com/ohsu-comp-bio/funnel/proto/tes"
"github.com/ohsu-comp-bio/funnel/storage"
"github.com/ohsu-comp-bio/funnel/util"
"os"
"path/filepath"
"time"
)
// DefaultWorker is the default task worker, which follows a basic,
// sequential process of task initialization, execution, finalization,
// and logging.
type DefaultWorker struct {
Conf config.Worker
Mapper *FileMapper
Store storage.Storage
TaskReader TaskReader
Event *events.TaskWriter
}
// Close cleans up worker resources, e.g. closing the event writers.
func (r *DefaultWorker) Close() error {
return r.Event.Close()
}
// Run runs the Worker.
// TODO document behavior of slow consumer of task log updates
func (r *DefaultWorker) Run(pctx context.Context) {
// The code here is verbose, but simple; mainly loops and simple error checking.
//
// The steps are:
// - prepare the working directory
// - map the task files to the working directory
// - log the IP address
// - set up the storage configuration
// - validate input and output files
// - download inputs
// - run the steps (docker)
// - upload the outputs
var run helper
var task *tes.Task
r.Event.Info("Version", version.LogFields()...)
task, run.syserr = r.TaskReader.Task()
r.Event.State(tes.State_INITIALIZING)
r.Event.StartTime(time.Now())
// Run the final logging/state steps in a deferred function
// to ensure they always run, even if there's a missed error.
defer func() {
r.Event.EndTime(time.Now())
switch {
case run.taskCanceled:
// The task was canceled.
r.Event.Info("Canceled")
r.Event.State(tes.State_CANCELED)
case run.execerr != nil:
// One of the executors failed
r.Event.Error("Exec error", "error", run.execerr)
r.Event.State(tes.State_EXECUTOR_ERROR)
case run.syserr != nil:
// Something else failed
// TODO should we do something special for run.err == context.Canceled?
r.Event.Error("System error", "error", run.syserr)
r.Event.State(tes.State_SYSTEM_ERROR)
default:
r.Event.State(tes.State_COMPLETE)
}
}()
// Recover from panics
defer handlePanic(func(e error) {
run.syserr = e
})
ctx := r.pollForCancel(pctx, func() {
run.taskCanceled = true
})
run.ctx = ctx
// Create working dir
var dir string
if run.ok() {
dir, run.syserr = filepath.Abs(r.Conf.WorkDir)
}
if run.ok() {
run.syserr = util.EnsureDir(dir)
}
// Prepare file mapper, which maps task file URLs to host filesystem paths
if run.ok() {
run.syserr = r.Mapper.MapTask(task)
}
// Configure a task-specific storage backend.
// This provides download/upload for inputs/outputs.
if run.ok() {
r.Store, run.syserr = r.Store.WithConfig(r.Conf.Storage)
}
if run.ok() {
run.syserr = r.validateInputs()
}
if run.ok() {
run.syserr = r.validateOutputs()
}
// Download inputs
for _, input := range r.Mapper.Inputs {
if run.ok() {
r.Event.Info("Starting download", "url", input.Url)
err := r.Store.Get(ctx, input.Url, input.Path, input.Type)
if err != nil {
run.syserr = err
r.Event.Error("Download failed", "url", input.Url, "error", err)
} else {
r.Event.Info("Download finished", "url", input.Url)
}
}
}
if run.ok() {
r.Event.State(tes.State_RUNNING)
}
// Run steps
for i, d := range task.Executors {
s := &stepWorker{
Conf: r.Conf,
Event: r.Event.NewExecutorWriter(uint32(i)),
Command: &DockerCommand{
Image: d.Image,
Command: d.Command,
Env: d.Env,
Volumes: r.Mapper.Volumes,
Workdir: d.Workdir,
ContainerName: fmt.Sprintf("%s-%d", task.Id, i),
// TODO make RemoveContainer configurable
RemoveContainer: true,
Event: r.Event.NewExecutorWriter(uint32(i)),
},
}
// Opens stdin/out/err files and updates those fields on "cmd".
if run.ok() {
run.syserr = r.openStepLogs(s, d)
}
if run.ok() {
run.execerr = s.Run(ctx)
}
}
// Upload outputs
var outputs []*tes.OutputFileLog
for _, output := range r.Mapper.Outputs {
if run.ok() {
r.Event.Info("Starting upload", "url", output.Url)
r.fixLinks(output.Path)
out, err := r.Store.Put(ctx, output.Url, output.Path, output.Type)
if err != nil {
run.syserr = err
r.Event.Error("Upload failed", "url", output.Url, "error", err)
} else {
r.Event.Info("Upload finished", "url", output.Url)
}
outputs = append(outputs, out...)
}
}
// unmap paths for OutputFileLog
for _, o := range outputs {
o.Path = r.Mapper.ContainerPath(o.Path)
}
if run.ok() {
r.Event.Outputs(outputs)
}
}
// fixLinks walks the output paths, fixing cases where a symlink is
// broken because it's pointing to a path inside a container volume.
func (r *DefaultWorker) fixLinks(basepath string) {
filepath.Walk(basepath, func(p string, f os.FileInfo, err error) error {
if err != nil {
// There's an error, so be safe and give up on this file
return nil
}
// Only bother to check symlinks
if f.Mode()&os.ModeSymlink != 0 {
// Test if the file can be opened because it doesn't exist
fh, rerr := os.Open(p)
fh.Close()
if rerr != nil && os.IsNotExist(rerr) {
// Get symlink source path
src, err := os.Readlink(p)
if err != nil {
return nil
}
// Map symlink source (possible container path) to host path
mapped, err := r.Mapper.HostPath(src)
if err != nil {
return nil
}
// Check whether the mapped path exists
fh, err := os.Open(mapped)
fh.Close()
// If the mapped path exists, fix the symlink
if err == nil {
err := os.Remove(p)
if err != nil {
return nil
}
os.Symlink(mapped, p)
}
}
}
return nil
})
}
// openLogs opens/creates the logs files for a step and updates those fields.
func (r *DefaultWorker) openStepLogs(s *stepWorker, d *tes.Executor) error {
// Find the path for task stdin
var err error
if d.Stdin != "" {
s.Command.Stdin, err = r.Mapper.OpenHostFile(d.Stdin)
if err != nil {
s.Event.Error("Couldn't prepare log files", err)
return err
}
}
// Create file for task stdout
if d.Stdout != "" {
s.Command.Stdout, err = r.Mapper.CreateHostFile(d.Stdout)
if err != nil {
s.Event.Error("Couldn't prepare log files", err)
return err
}
}
// Create file for task stderr
if d.Stderr != "" {
s.Command.Stderr, err = r.Mapper.CreateHostFile(d.Stderr)
if err != nil {
s.Event.Error("Couldn't prepare log files", err)
return err
}
}
return nil
}
// Validate the input downloads
func (r *DefaultWorker) validateInputs() error {
for _, input := range r.Mapper.Inputs {
if !r.Store.Supports(input.Url, input.Path, input.Type) {
return fmt.Errorf("Input download not supported by storage: %v", input)
}
}
return nil
}
// Validate the output uploads
func (r *DefaultWorker) validateOutputs() error {
for _, output := range r.Mapper.Outputs {
if !r.Store.Supports(output.Url, output.Path, output.Type) {
return fmt.Errorf("Output upload not supported by storage: %v", output)
}
}
return nil
}
func (r *DefaultWorker) pollForCancel(ctx context.Context, f func()) context.Context {
taskctx, cancel := context.WithCancel(ctx)
// Start a goroutine that polls the server to watch for a canceled state.
// If a cancel state is found, "taskctx" is canceled.
go func() {
ticker := time.NewTicker(r.Conf.UpdateRate)
defer ticker.Stop()
for {
select {
case <-taskctx.Done():
return
case <-ticker.C:
state, _ := r.TaskReader.State()
if tes.TerminalState(state) {
cancel()
f()
}
}
}
}()
return taskctx
}
| {
"content_hash": "5894ad22df6288229734dc086482ae64",
"timestamp": "",
"source": "github",
"line_count": 316,
"max_line_length": 86,
"avg_line_length": 24.65506329113924,
"alnum_prop": 0.653831343858298,
"repo_name": "buchanae/funnel",
"id": "3dd9788c967573f6509367a948f60bf661a75b9a",
"size": "7791",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "worker/worker.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "39229"
},
{
"name": "Go",
"bytes": "517203"
},
{
"name": "HTML",
"bytes": "20381"
},
{
"name": "JavaScript",
"bytes": "6083"
},
{
"name": "Makefile",
"bytes": "8602"
},
{
"name": "Shell",
"bytes": "19953"
}
],
"symlink_target": ""
} |
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>com.alibaba.rocketmq</groupId>
<artifactId>rocketmq-all</artifactId>
<version>3.0.8-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<packaging>jar</packaging>
<artifactId>rocketmq-client</artifactId>
<name>rocketmq-client ${project.version}</name>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>rocketmq-common</artifactId>
</dependency>
</dependencies>
</project>
| {
"content_hash": "92227130a6af87f0ee0cc9b0caae0190",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 204,
"avg_line_length": 32.375,
"alnum_prop": 0.7194337194337195,
"repo_name": "ans76/RocketMQ",
"id": "7a236b73034e8eab1082b613cd8304792af99cf4",
"size": "777",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "rocketmq-client/pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
dotnet ef migrations add Initial -c GuardContext -o Migrations/Guard
dotnet ef migrations add Grant -c PersistedGrantDbContext -o Migrations/Grant
dotnet ef migrations add Config -c ConfigurationDbContext -o Migrations/Config
dotnet ef database update -c GuardContext
dotnet ef database update -c PersistedGrantDbContext
dotnet ef database update -c ConfigurationDbContext | {
"content_hash": "0c0f3618c4597b5c291c3b2b53a42b08",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 78,
"avg_line_length": 53.285714285714285,
"alnum_prop": 0.8471849865951743,
"repo_name": "zahasoft/guard",
"id": "361154f45e2a03dd56af5a200ecc11ab0d314e10",
"size": "373",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "source/Zahasoft.Guard.Data/migrate.ps1",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "189044"
},
{
"name": "CSS",
"bytes": "131"
},
{
"name": "F#",
"bytes": "168131"
},
{
"name": "HTML",
"bytes": "12643"
},
{
"name": "PowerShell",
"bytes": "373"
}
],
"symlink_target": ""
} |
layout: page
title: About
---
<p class="message">
About
</p>
| {
"content_hash": "55818ea46ad29d908e438f70c5ae7221",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 19,
"avg_line_length": 8.125,
"alnum_prop": 0.6,
"repo_name": "kangfoo2/kangfoo2.github.io",
"id": "591c32f763a7e98c689bd1f2d884a928d2d4cf1d",
"size": "69",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "about.md",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "21971"
},
{
"name": "HTML",
"bytes": "5644"
}
],
"symlink_target": ""
} |
using System;
namespace Esp.Net.Examples.ReactiveModel.ClientApp.Model.Events
{
public class RejectQuoteEvent
{
public RejectQuoteEvent(Guid quoteId)
{
QuoteId = quoteId;
}
public Guid QuoteId { get; private set; }
}
} | {
"content_hash": "58a825bba3d899d1f68ba65a956ab2f3",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 63,
"avg_line_length": 19.785714285714285,
"alnum_prop": 0.6173285198555957,
"repo_name": "esp/esp-net",
"id": "4a00053a5979f217242c27f838e5865b8d6195aa",
"size": "279",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "examples/ReactiveModel/Esp.Net.Examples.ReactiveModel/ClientApp/Model/Events/RejectQuoteEvent.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "266654"
}
],
"symlink_target": ""
} |
using System;
using SDRSharp.Radio;
namespace SDRSharp.DNR
{
public unsafe class NoiseFilter : FftProcessor
{
private const int WindowSize = 32;
private const int FftSize = 1024 * 4;
private const float OverlapRatio = 0.2f;
private float _noiseThreshold;
private readonly UnsafeBuffer _gainBuffer;
private readonly float* _gainPtr;
private readonly UnsafeBuffer _smoothedGainBuffer;
private readonly float* _smoothedGainPtr;
private readonly UnsafeBuffer _powerBuffer;
private readonly float* _powerPtr;
public NoiseFilter(int fftSize = FftSize)
: base(fftSize, OverlapRatio)
{
_gainBuffer = UnsafeBuffer.Create(fftSize, sizeof(float));
_gainPtr = (float*) _gainBuffer;
_smoothedGainBuffer = UnsafeBuffer.Create(fftSize, sizeof(float));
_smoothedGainPtr = (float*) _smoothedGainBuffer;
_powerBuffer = UnsafeBuffer.Create(fftSize, sizeof(float));
_powerPtr = (float*) _powerBuffer;
}
public float NoiseThreshold
{
get { return _noiseThreshold; }
set { _noiseThreshold = value; }
}
protected override void ProcessFft(Complex* buffer, int length)
{
Fourier.SpectrumPower(buffer, _powerPtr, length);
for (var i = 0; i < length; i++)
{
_gainPtr[i] = _powerPtr[i] > _noiseThreshold ? 1.0f : 0.0f;
}
for (var i = 0; i < length; i++)
{
var sum = 0.0f;
for (var j = -WindowSize / 2; j < WindowSize / 2; j++)
{
var index = i + j;
if (index >= length)
{
index -= length;
}
if (index < 0)
{
index += length;
}
sum += _gainPtr[index];
}
var gain = sum / WindowSize;
_smoothedGainPtr[i] = gain;
}
for (var i = 0; i < length; i++)
{
buffer[i] *= _smoothedGainPtr[i];
}
}
}
} | {
"content_hash": "36e1ecc3274c43705a4e0cd4fad49148",
"timestamp": "",
"source": "github",
"line_count": 80,
"max_line_length": 78,
"avg_line_length": 28.8,
"alnum_prop": 0.4852430555555556,
"repo_name": "murphy666/sdrsharp_experimental",
"id": "128ec8fabbfcf606a2476e1b7f8e2b1808a6e643",
"size": "2306",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "DNR/NoiseFilter.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "2220321"
}
],
"symlink_target": ""
} |
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
public class ChangeScene : MonoBehaviour {
public string sceneName;
void OnControllerColliderHit(ControllerColliderHit other)
{
if (other.gameObject.tag == "LoadScene") {
SceneManager.LoadScene (sceneName);
}
}
}
| {
"content_hash": "d98d63b0fe4d58612684845c5bdcb466",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 58,
"avg_line_length": 23.53846153846154,
"alnum_prop": 0.7745098039215687,
"repo_name": "spandananitdgp/Egyptian-Mummification-VR-Experience",
"id": "ff566cb9079a0a4595ac332366a07db839abd4b8",
"size": "308",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Assets/Scripts/ChangeScene.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "704570"
},
{
"name": "GLSL",
"bytes": "312461"
},
{
"name": "Objective-C",
"bytes": "1433"
},
{
"name": "Objective-C++",
"bytes": "2960"
}
],
"symlink_target": ""
} |
package org.camunda.community.process_test_coverage.examples.junit5.platform8;
import io.camunda.zeebe.client.ZeebeClient;
import io.camunda.zeebe.client.api.response.ActivatedJob;
import io.camunda.zeebe.client.api.response.ProcessInstanceEvent;
import io.camunda.zeebe.process.test.api.ZeebeTestEngine;
import io.camunda.zeebe.process.test.extension.testcontainer.ZeebeProcessTest;
import org.camunda.community.process_test_coverage.junit5.platform8.ProcessEngineCoverageExtension;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeoutException;
import static io.camunda.zeebe.process.test.assertions.BpmnAssert.assertThat;
import static io.camunda.zeebe.protocol.Protocol.USER_TASK_JOB_TYPE;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
@ZeebeProcessTest
@ExtendWith(ProcessEngineCoverageExtension.class)
public class OrderProcessTest {
// @RegisterExtension
// public static ProcessEngineCoverageExtension extension = ProcessEngineCoverageExtension.builder().build();
private ZeebeClient zeebe;
private ZeebeTestEngine engine;
@BeforeEach
public void setup() {
zeebe.newDeployResourceCommand()
.addResourceFromClasspath("order-process.bpmn")
.send()
.join();
}
@Test
public void shouldExecuteHappyPath() throws InterruptedException, TimeoutException {
final ProcessInstanceEvent instance = this.startProcess();
waitForUserTaskAndComplete("Task_ProcessOrder", Collections.singletonMap("orderOk", true));
assertThat(instance).isWaitingAtElements("Task_DeliverOrder");
waitForUserTaskAndComplete("Task_DeliverOrder", Collections.emptyMap());
assertThat(instance)
.hasPassedElement("Event_OrderProcessed")
.isCompleted();
}
@Test
public void shouldCancelOrder() throws Exception {
final ProcessInstanceEvent instance = this.startProcess();
waitForUserTaskAndComplete("Task_ProcessOrder", Collections.singletonMap("orderOk", false));
assertThat(instance)
.hasPassedElement("Event_OrderCancelled")
.isCompleted();
}
private void waitForUserTaskAndComplete(String userTaskId, Map<String, Object> variables) throws InterruptedException, TimeoutException {
// Let the workflow engine do whatever it needs to do
engine.waitForIdleState(Duration.ofSeconds(10));
// Now get all user tasks
List<ActivatedJob> jobs = zeebe.newActivateJobsCommand().jobType(USER_TASK_JOB_TYPE).maxJobsToActivate(1).workerName("waitForUserTaskAndComplete").send().join().getJobs();
// Should be only one
assertTrue(jobs.size()>0, "Job for user task '" + userTaskId + "' does not exist");
ActivatedJob userTaskJob = jobs.get(0);
// Make sure it is the right one
if (userTaskId!=null) {
assertEquals(userTaskId, userTaskJob.getElementId());
}
// And complete it passing the variables
if (variables!=null && variables.size()>0) {
zeebe.newCompleteCommand(userTaskJob.getKey()).variables(variables).send().join();
} else {
zeebe.newCompleteCommand(userTaskJob.getKey()).send().join();
}
// Let the workflow engine do whatever it needs to do
engine.waitForIdleState(Duration.ofSeconds(10));
}
private ProcessInstanceEvent startProcess() {
return zeebe.newCreateInstanceCommand() //
.bpmnProcessId("order-process")
.latestVersion() //
.send().join();
}
}
| {
"content_hash": "76a8f8ce08786cffe38e1ee2ef9b31cf",
"timestamp": "",
"source": "github",
"line_count": 99,
"max_line_length": 179,
"avg_line_length": 39.35353535353536,
"alnum_prop": 0.7089322381930184,
"repo_name": "camunda/camunda-process-test-coverage",
"id": "bb99d9248fb88431f72c3abf9556f29ab7f31bc0",
"size": "3896",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "examples/junit5-platform-8/src/test/java/org/camunda/community/process_test_coverage/examples/junit5/platform8/OrderProcessTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "6482"
},
{
"name": "Java",
"bytes": "114946"
}
],
"symlink_target": ""
} |
package de.tuberlin.uebb.sl2.modules
import java.io.File
import java.net.URL
import scalax.file.FileSystem
import scalax.file.Path
import scala.io.Source
trait AbstractFile {
/**
* Used to abstract from the differences between files from a .jar file ({@link BottledFile})
* and files from the file system ({@link PathedFile}).
*/
abstract class AbstractFile {
def filename():String
def parent():File
def path():String
def canRead():Boolean
def lastModified():Long
def contents():String
}
class PathedFile(path: Path) extends AbstractFile {
def filename() = {
path.name
}
def parent() = {
if(path.parent != null)
new File(path.parent.toString)
else
new File(".")
}
def path() = {
path.path
}
def canRead() = {
path.canRead
}
def lastModified() = {
path.lastModified
}
def contents() = {
path.lines(includeTerminator = true).mkString("")
}
}
class ErrorFile(url: URL) extends AbstractFile {
def filename = { "Error" }
def parent = { new File(".") }
def path = { throw new UnsupportedOperationException() }
def canRead() = { false }
def lastModified() = { 0 }
def contents() = { throw new UnsupportedOperationException() }
}
/**
* A file inside a .jar file
*/
class BottledFile(url: URL) extends AbstractFile {
def filename() = {
val f = url.getFile
f.substring(f.lastIndexOf("!")+1)
}
def parent() = {
new File(".")
}
def path() = {
url.toString
}
def jarFile() = {
val f = url.getFile
f.substring(5, f.lastIndexOf("!"))
}
def canRead() = {
/*
* A bottled file can always be read. Otherwise, its location wouldn't have been found.
*/
true
}
def lastModified() = {
/*
* The modification date for a bottled does not matter, because all files
* (source, js and signature) in a JAR file have the same date and cannot
* be modified.
*/
0
}
def contents() = {
Source.fromURL(url).getLines.mkString("\n")
}
}
def createFile(url: URL, path: String):AbstractFile = {
createFile(new URL(url, path))
}
def createFile(file: File, path: String):AbstractFile = {
if(file != null)
createFile(new URL(file.toURI.toURL, path))
else
new ErrorFile(new File(path).toURI.toURL)
}
def createFile(url: URL):AbstractFile = {
if(url.toString.startsWith("jar:")) {
new BottledFile(url)
} else {
val option = Path(url.toURI)
if(option.isEmpty)
new ErrorFile(url)
else
new PathedFile(option.get)
}
}
} | {
"content_hash": "5da4fd5b7c601e32dd86c5f6c32ce6ed",
"timestamp": "",
"source": "github",
"line_count": 127,
"max_line_length": 95,
"avg_line_length": 21.96062992125984,
"alnum_prop": 0.57475797776981,
"repo_name": "choeger/sl2",
"id": "d4211bbc5b8bc63f09d48e817f6621ebe6648f9d",
"size": "2789",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/main/scala/de/tuberlin/uebb/sl2/modules/AbstractFile.scala",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "JavaScript",
"bytes": "631508"
},
{
"name": "Scala",
"bytes": "426372"
},
{
"name": "Slash",
"bytes": "27846"
}
],
"symlink_target": ""
} |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE590_Free_Memory_Not_on_Heap__delete_array_int64_t_alloca_82_bad.cpp
Label Definition File: CWE590_Free_Memory_Not_on_Heap__delete_array.label.xml
Template File: sources-sink-82_bad.tmpl.cpp
*/
/*
* @description
* CWE: 590 Free Memory Not on Heap
* BadSource: alloca Data buffer is allocated on the stack with alloca()
* GoodSource: Allocate memory on the heap
* Sinks:
* BadSink : Print then free data
* Flow Variant: 82 Data flow: data passed in a parameter to a virtual method called via a pointer
*
* */
#ifndef OMITBAD
#include "std_testcase.h"
#include "CWE590_Free_Memory_Not_on_Heap__delete_array_int64_t_alloca_82.h"
namespace CWE590_Free_Memory_Not_on_Heap__delete_array_int64_t_alloca_82
{
void CWE590_Free_Memory_Not_on_Heap__delete_array_int64_t_alloca_82_bad::action(int64_t * data)
{
printLongLongLine(data[0]);
/* POTENTIAL FLAW: Possibly deallocating memory allocated on the stack */
delete [] data;
}
}
#endif /* OMITBAD */
| {
"content_hash": "6cd7901201da5534c15cb3a9f7f437f8",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 98,
"avg_line_length": 32.8125,
"alnum_prop": 0.7095238095238096,
"repo_name": "maurer/tiamat",
"id": "449b9df449e6d9f06c418874fa83fb3f44f0cc60",
"size": "1050",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "samples/Juliet/testcases/CWE590_Free_Memory_Not_on_Heap/s01/CWE590_Free_Memory_Not_on_Heap__delete_array_int64_t_alloca_82_bad.cpp",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
namespace blink {
class CSSStyleValue;
// This class is designed for CSS Paint such that its instance can be safely
// passed cross threads.
class CORE_EXPORT CrossThreadStyleValue {
public:
enum class StyleValueType {
kUnknownType,
kUnparsedType,
kKeywordType,
kUnitType,
kColorType,
};
virtual ~CrossThreadStyleValue() = default;
virtual StyleValueType GetType() const = 0;
virtual CSSStyleValue* ToCSSStyleValue() = 0;
virtual std::unique_ptr<CrossThreadStyleValue> IsolatedCopy() const = 0;
virtual bool operator==(const CrossThreadStyleValue&) const = 0;
protected:
CrossThreadStyleValue() = default;
private:
DISALLOW_COPY_AND_ASSIGN(CrossThreadStyleValue);
};
} // namespace blink
#endif
| {
"content_hash": "b6ac451f09e282d055932e9e15fa74cb",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 76,
"avg_line_length": 21.941176470588236,
"alnum_prop": 0.7372654155495979,
"repo_name": "endlessm/chromium-browser",
"id": "4b213fc00d2b3229a05dd52c3ad982b9b5ad0b26",
"size": "1171",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "third_party/blink/renderer/core/css/cssom/cross_thread_style_value.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
package com.planet_ink.coffee_mud.Abilities.Spells;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
@SuppressWarnings("unchecked")
public class Spell_ContinualLight extends Spell
{
public String ID() { return "Spell_ContinualLight"; }
public String name(){return "Continual Light";}
public String displayText(){return "(Continual Light)";}
public int abstractQuality(){ return Ability.QUALITY_OK_SELF;}
protected int canTargetCode(){return CAN_MOBS|CAN_ITEMS;}
protected int canAffectCode(){return CAN_MOBS|CAN_ITEMS;}
public int classificationCode(){return Ability.ACODE_SPELL|Ability.DOMAIN_EVOCATION;}
public void affectEnvStats(Environmental affected, EnvStats affectableStats)
{
if(!(affected instanceof Room))
affectableStats.setDisposition(affectableStats.disposition()|EnvStats.IS_LIGHTSOURCE);
if(CMLib.flags().isInDark(affected))
affectableStats.setDisposition(affectableStats.disposition()-EnvStats.IS_DARK);
}
public void unInvoke()
{
// undo the affects of this spell
if((affected==null)||(!(affected instanceof MOB)))
return;
MOB mob=(MOB)affected;
Room room=((MOB)affected).location();
if(canBeUninvoked())
room.show(mob,null,CMMsg.MSG_OK_VISUAL,"The light above <S-NAME> dims.");
super.unInvoke();
if(canBeUninvoked())
room.recoverRoomStats();
}
public int castingQuality(MOB mob, Environmental target)
{
if(mob!=null)
{
if((mob==target)&&(!CMLib.flags().canBeSeenBy(mob.location(),mob)))
return super.castingQuality(mob, target,Ability.QUALITY_BENEFICIAL_SELF);
}
return super.castingQuality(mob,target);
}
public boolean invoke(MOB mob, Vector commands, Environmental givenTarget, boolean auto, int asLevel)
{
Environmental target=null;
if(commands.size()==0) target=mob;
else
target=getAnyTarget(mob,commands,givenTarget,Item.WORNREQ_UNWORNONLY);
if(target==null) return false;
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
boolean success=proficiencyCheck(mob,0,auto);
String str="^S<S-NAME> invoke(s) a continual light toward(s) <T-NAMESELF>!^?";
if(!(target instanceof MOB))
str="^S<S-NAME> invoke(s) a continual light into <T-NAME>!^?";
CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),str);
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
beneficialAffect(mob,target,asLevel,Integer.MAX_VALUE-100);
mob.location().recoverRoomStats(); // attempt to handle followers
}
else
beneficialWordsFizzle(mob,target,"<S-NAME> attempt(s) to invoke light, but fail(s).");
return success;
}
}
| {
"content_hash": "2dd38776c0e58f1edfab0132757aae52",
"timestamp": "",
"source": "github",
"line_count": 91,
"max_line_length": 102,
"avg_line_length": 37.53846153846154,
"alnum_prop": 0.7148711943793911,
"repo_name": "robjcaskey/Unofficial-Coffee-Mud-Upstream",
"id": "1b830eae8145cc0dd70518b40fc6854cdddc8554",
"size": "4024",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "com/planet_ink/coffee_mud/Abilities/Spells/Spell_ContinualLight.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "21082141"
},
{
"name": "JavaScript",
"bytes": "16596"
},
{
"name": "Shell",
"bytes": "7865"
}
],
"symlink_target": ""
} |
/* Google Map Service */
(function(){
'use strict';
angular.module('myApp')
.factory('mapService', function(){
var service = {
setMap: setMap,
getMap: initialize
}
var lat = 0,
lng = 0,
url = "",
tags = []
function setMap(lat, lng, url, location){
this.lat = lat;
this.lng = lng;
this.url = decodeURI(url);
this.location = location;
}
function initialize() {
var myLatlng = new google.maps.LatLng(this.lat, this.lng);
var mapOptions = {
center: myLatlng,
zoom: 14
};
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
var icon = {
url: this.url, // url
scaledSize: new google.maps.Size(60, 60), // scaled size
origin: new google.maps.Point(0,0), // origin
anchor: new google.maps.Point(0, 0) // anchor
};
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
animation: google.maps.Animation.DROP,
icon: icon
});
var infowindow = new google.maps.InfoWindow({
content: this.location
});
infowindow.open(map,marker);
google.maps.event.addListener(marker, 'click', toggleBounce);
}
function toggleBounce() {
if (marker.getAnimation() != null) {
marker.setAnimation(null);
} else {
marker.setAnimation(google.maps.Animation.BOUNCE);
}
}
return service;
});
}()); | {
"content_hash": "71384af331e63933e71b277ec10b5cf1",
"timestamp": "",
"source": "github",
"line_count": 97,
"max_line_length": 92,
"avg_line_length": 16.628865979381445,
"alnum_prop": 0.5257284562926224,
"repo_name": "kpingul/foodWidget",
"id": "59185e770c6c1b935448e47d88b071066011ecdf",
"size": "1613",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "public/src/js/app/shared/MapService.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "8048"
},
{
"name": "HTML",
"bytes": "5336"
},
{
"name": "JavaScript",
"bytes": "20782"
}
],
"symlink_target": ""
} |
package com.klarna.hiverunner.sql.cli.beeline;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import com.klarna.hiverunner.sql.split.Consumer;
import com.klarna.hiverunner.sql.split.Context;
@ExtendWith(MockitoExtension.class)
public class SqlLineCommandRuleTest {
@Mock
private Context context;
@Test
public void handleStart() {
when(context.statement()).thenReturn(" ");
SqlLineCommandRule.INSTANCE.handle("token", context);
verify(context).append("token");
verify(context).appendWith(Consumer.UNTIL_EOL);
verify(context).flush();
}
@Test
public void handleOther() {
when(context.statement()).thenReturn("statement");
SqlLineCommandRule.INSTANCE.handle("token", context);
verify(context).append("token");
verify(context, never()).appendWith(any(Consumer.class));
verify(context, never()).flush();
}
}
| {
"content_hash": "3488a3651bc3eaa1caa7b1fd31d4fd9c",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 65,
"avg_line_length": 29.609756097560975,
"alnum_prop": 0.7067545304777595,
"repo_name": "klarna/HiveRunner",
"id": "8b1b20953fc9733606b0b5dde94585e57d8d556e",
"size": "1865",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "src/test/java/com/klarna/hiverunner/sql/cli/beeline/SqlLineCommandRuleTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "400217"
},
{
"name": "TSQL",
"bytes": "41"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PhotographyApi.SelfHost
{
class Program
{
static void Main(string[] args)
{
}
}
}
| {
"content_hash": "1b8e3aa6b77bff2d336e272427574dc9",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 39,
"avg_line_length": 16.4,
"alnum_prop": 0.6585365853658537,
"repo_name": "QuinntyneBrown/PhotographyApi",
"id": "2a14fdde75c81dd71f9504eab3a567f353ce3318",
"size": "248",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "PhotographyApi.SelfHost/Program.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "19904"
},
{
"name": "JavaScript",
"bytes": "122396"
}
],
"symlink_target": ""
} |
Subsets and Splits