code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-present Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "OgreVulkanQueue.h" #include "OgreVulkanDevice.h" #include "OgreVulkanMappings.h" #include "OgreVulkanRenderSystem.h" #include "OgreVulkanTextureGpu.h" #include "OgreVulkanWindow.h" #include "OgreException.h" #include "OgrePixelFormat.h" #include "OgreStringConverter.h" #include "OgreVulkanUtils.h" #include "OgreVulkanDescriptorPool.h" #define TODO_findRealPresentQueue #define TODO_we_assume_has_stencil namespace Ogre { // Mask away read flags from srcAccessMask static const uint32 c_srcValidAccessFlags = 0xFFFFFFFF ^ ( VK_ACCESS_INDIRECT_COMMAND_READ_BIT | VK_ACCESS_INDEX_READ_BIT | VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT | VK_ACCESS_UNIFORM_READ_BIT | VK_ACCESS_INPUT_ATTACHMENT_READ_BIT | VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_HOST_READ_BIT | VK_ACCESS_MEMORY_READ_BIT ); VulkanQueue::VulkanQueue() : mDevice( 0 ), mFamily( NumQueueFamilies ), mFamilyIdx( 0u ), mQueueIdx( 0u ), mQueue( 0 ), mCurrentCmdBuffer( 0 ), mOwnerDevice( 0 ), mNumFramesInFlight( 3 ), mCurrentFrameIdx( 0 ), mRenderSystem( 0 ), mCurrentFence( 0 ), mEncoderState( EncoderClosed ), mCopyEndReadSrcBufferFlags( 0 ), mCopyEndReadDstBufferFlags( 0 ), mCopyEndReadDstTextureFlags( 0 ), mCopyStartWriteSrcBufferFlags( 0 ) { } //------------------------------------------------------------------------- VulkanQueue::~VulkanQueue() { destroy(); } //------------------------------------------------------------------------- void VulkanQueue::setQueueData( VulkanDevice *owner, QueueFamily family, uint32 familyIdx, uint32 queueIdx ) { mOwnerDevice = owner; mFamily = family; mFamilyIdx = familyIdx; mQueueIdx = queueIdx; } //------------------------------------------------------------------------- void VulkanQueue::init( VkDevice device, VkQueue queue, VulkanRenderSystem *renderSystem ) { mDevice = device; mQueue = queue; mRenderSystem = renderSystem; mPerFrameData.resize( mNumFramesInFlight ); VkCommandPoolCreateInfo cmdPoolCreateInfo = {VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; cmdPoolCreateInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT; cmdPoolCreateInfo.queueFamilyIndex = mFamilyIdx; VkCommandBufferAllocateInfo allocateInfo = {VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; allocateInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; allocateInfo.commandBufferCount = 1u; VkFenceCreateInfo fenceCi = {VK_STRUCTURE_TYPE_FENCE_CREATE_INFO}; fenceCi.flags = VK_FENCE_CREATE_SIGNALED_BIT; for (auto& fd : mPerFrameData) { OGRE_VK_CHECK(vkCreateCommandPool(mDevice, &cmdPoolCreateInfo, 0, &fd.mCommandPool)); allocateInfo.commandPool = fd.mCommandPool; OGRE_VK_CHECK(vkAllocateCommandBuffers( mDevice, &allocateInfo, &fd.mCommandBuffer )); OGRE_VK_CHECK(vkCreateFence(mDevice, &fenceCi, 0, &fd.mProtectingFence)); } newCommandBuffer(); } void VulkanQueue::destroy() { if( mDevice ) { vkDeviceWaitIdle( mDevice ); for(size_t i = 0; i < mPerFrameData.size(); ++i) { _waitOnFrame(i); } for(auto& fd : mPerFrameData) { vkDestroyFence( mDevice, fd.mProtectingFence, 0 ); vkDestroyCommandPool( mDevice, fd.mCommandPool, 0 ); } mDevice = 0; } } //------------------------------------------------------------------------- void VulkanQueue::newCommandBuffer( void ) { _waitOnFrame(mCurrentFrameIdx); vkResetCommandPool(mDevice, mPerFrameData[mCurrentFrameIdx].mCommandPool, 0); mCurrentCmdBuffer = mPerFrameData[mCurrentFrameIdx].mCommandBuffer; mCurrentFence = mPerFrameData[mCurrentFrameIdx].mProtectingFence; VkCommandBufferBeginInfo beginInfo = {VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; vkBeginCommandBuffer( mCurrentCmdBuffer, &beginInfo ); } //------------------------------------------------------------------------- void VulkanQueue::endCommandBuffer( void ) { if( mCurrentCmdBuffer ) { endAllEncoders(); OGRE_VK_CHECK(vkEndCommandBuffer( mCurrentCmdBuffer )); } } //------------------------------------------------------------------------- void VulkanQueue::getGraphicsEncoder( void ) { if( mEncoderState != EncoderGraphicsOpen ) { endCopyEncoder(); endComputeEncoder(); mEncoderState = EncoderGraphicsOpen; } } //------------------------------------------------------------------------- void VulkanQueue::getComputeEncoder( void ) { if( mEncoderState != EncoderComputeOpen ) { endRenderEncoder(); endCopyEncoder(); mEncoderState = EncoderComputeOpen; } } //------------------------------------------------------------------------- VkPipelineStageFlags VulkanQueue::deriveStageFromBufferAccessFlags( VkAccessFlags accessFlags ) { VkPipelineStageFlags stage = 0; if( accessFlags & VK_ACCESS_INDIRECT_COMMAND_READ_BIT ) stage |= VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT; if( accessFlags & ( VK_ACCESS_INDEX_READ_BIT | VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT ) ) { stage |= VK_PIPELINE_STAGE_VERTEX_INPUT_BIT; } if( accessFlags & ( VK_ACCESS_UNIFORM_READ_BIT | VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT ) ) { stage |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT | VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT | VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; } if( accessFlags & ( VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT ) ) { stage |= VK_PIPELINE_STAGE_TRANSFER_BIT; } return stage; } //------------------------------------------------------------------------- VkPipelineStageFlags VulkanQueue::deriveStageFromTextureAccessFlags( VkAccessFlags accessFlags ) { VkPipelineStageFlags stage = 0; if( accessFlags & ( VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT ) ) { stage |= VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT; } if( accessFlags & ( VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT ) ) { stage |= VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; } if( accessFlags & ( VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT ) ) { stage |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT | VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT | VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; } if( accessFlags & ( VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT ) ) { stage |= VK_PIPELINE_STAGE_TRANSFER_BIT; } if( accessFlags & VK_ACCESS_INPUT_ATTACHMENT_READ_BIT ) stage |= VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT; return stage; } //------------------------------------------------------------------------- void VulkanQueue::insertRestoreBarrier( VulkanTextureGpu *vkTexture, const VkImageLayout newTransferLayout ) { const VkImageLayout oldLayout = vkTexture->mCurrLayout; const VkImageLayout otherTransferLayout = newTransferLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL ? VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL : VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; const VkAccessFlags accessFlags = newTransferLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL ? VK_ACCESS_TRANSFER_READ_BIT : VK_ACCESS_TRANSFER_WRITE_BIT; if( oldLayout == newTransferLayout ) { // Nothing to do. A restore barrier has already been inserted // If the assert fails, then the texture transitioned // to this layout without us knowing OGRE_ASSERT_HIGH( std::find( mImageMemBarrierPtrs.begin(), mImageMemBarrierPtrs.end(), vkTexture ) != mImageMemBarrierPtrs.end() && "Only this class should set VK_IMAGE_LAYOUT_TRANSFER_*_OPTIMAL" ); } else if( oldLayout == otherTransferLayout ) { // A restore barrier has already been inserted, but it needs modification FastArray<TextureGpu *>::iterator itor = std::find( mImageMemBarrierPtrs.begin(), mImageMemBarrierPtrs.end(), vkTexture ); // If the assert fails, then the texture transitioned // to this layout without us knowing OGRE_ASSERT_LOW( itor != mImageMemBarrierPtrs.end() && "Only this class should set VK_IMAGE_LAYOUT_TRANSFER_*_OPTIMAL" ); const size_t idx = ( size_t )( itor - mImageMemBarrierPtrs.begin() ); VkImageMemoryBarrier &imageMemBarrier = *( mImageMemBarriers.begin() + idx ); imageMemBarrier.srcAccessMask = accessFlags & c_srcValidAccessFlags; imageMemBarrier.oldLayout = newTransferLayout; } else { // First time we see this texture VkImageMemoryBarrier imageMemBarrier = vkTexture->getImageMemoryBarrier(); imageMemBarrier.srcAccessMask = accessFlags & c_srcValidAccessFlags; imageMemBarrier.dstAccessMask = VulkanMappings::get( vkTexture ); if( newTransferLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL ) { // We need to block subsequent stages from writing to this texture // until we're done copying from it (but they can read) imageMemBarrier.dstAccessMask &= (VkAccessFlags)~VK_ACCESS_SHADER_READ_BIT; mCopyEndReadDstTextureFlags |= imageMemBarrier.dstAccessMask; } imageMemBarrier.oldLayout = newTransferLayout; imageMemBarrier.newLayout = vkTexture->mNextLayout; mImageMemBarriers.push_back( imageMemBarrier ); mImageMemBarrierPtrs.push_back( vkTexture ); } } //------------------------------------------------------------------------- void VulkanQueue::prepareForUpload( const BufferPacked *buffer, TextureGpu *texture ) { VkAccessFlags bufferAccessFlags = 0; if( buffer ) { BufferPackedDownloadMap::iterator it = mCopyDownloadBuffers.find( buffer ); if( it == mCopyDownloadBuffers.end() ) ;//bufferAccessFlags = VulkanMappings::get( buffer->getBufferPackedType() ); else { if( !it->second ) { // bufferAccessFlags = VK_ACCESS_TRANSFER_WRITE_BIT; // We assume consecutive writes means we're writing to non-overlapping areas // Do not wait for previous transfers. bufferAccessFlags = 0; } else bufferAccessFlags = VK_ACCESS_TRANSFER_READ_BIT; } mCopyDownloadBuffers[buffer] = false; mCopyEndReadSrcBufferFlags |= VK_ACCESS_TRANSFER_WRITE_BIT; } OGRE_ASSERT_HIGH( !texture || dynamic_cast<VulkanTextureGpu *>( texture ) ); VulkanTextureGpu *vkTexture = static_cast<VulkanTextureGpu *>( texture ); VkAccessFlags texAccessFlags = 0; if( texture ) { TextureGpuDownloadMap::iterator it = mCopyDownloadTextures.find( vkTexture ); if( vkTexture->mCurrLayout == VK_IMAGE_LAYOUT_UNDEFINED ) { // This texture must just have been created texAccessFlags = 0; } else if( it == mCopyDownloadTextures.end() ) { if( vkTexture->mCurrLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL || vkTexture->mCurrLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL ) { OGRE_EXCEPT( Exception::ERR_INVALID_STATE, "Texture " + vkTexture->getName() + " is already in CopySrc or CopyDst layout, externally set. Perhaps " "you need to call RenderSystem::flushTextureCopyOperations", "VulkanQueue::prepareForUpload" ); } texAccessFlags = VulkanMappings::get( texture ); } else { if( !it->second ) { OGRE_ASSERT_MEDIUM( vkTexture->mCurrLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL ); // texAccessFlags = VK_ACCESS_TRANSFER_WRITE_BIT; // We assume consecutive writes means we're writing to non-overlapping areas // Do not wait for previous transfers. texAccessFlags = 0; } else { OGRE_ASSERT_MEDIUM( vkTexture->mCurrLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL ); texAccessFlags = VK_ACCESS_TRANSFER_READ_BIT; } } // We need to block subsequent stages from accessing this texture at all // until we're done copying into it mCopyEndReadDstTextureFlags |= VulkanMappings::get( texture ); mCopyDownloadTextures[vkTexture] = false; } // One buffer barrier is enough for all buffers. // Unless we already issued a transfer to this same buffer const bool bNeedsBufferBarrier = ( bufferAccessFlags && ( mCopyEndReadDstBufferFlags & bufferAccessFlags ) != bufferAccessFlags ) || ( bufferAccessFlags & ( VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT ) ); const bool bNeedsTexTransition = vkTexture && vkTexture->mCurrLayout != VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; mCopyEndReadDstBufferFlags |= bufferAccessFlags; // Trigger the barrier if we actually have to wait. // And only if we haven't issued this barrier already if( bNeedsBufferBarrier || bNeedsTexTransition ) { VkPipelineStageFlags srcStage = 0; uint32 numMemBarriers = 0u; VkMemoryBarrier memBarrier = {VK_STRUCTURE_TYPE_MEMORY_BARRIER}; if( bNeedsBufferBarrier ) { // GPU must stop using this buffer before we can write into it memBarrier.srcAccessMask = bufferAccessFlags & c_srcValidAccessFlags; memBarrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; srcStage |= deriveStageFromBufferAccessFlags( bufferAccessFlags ); numMemBarriers = 1u; } uint32 numImageMemBarriers = 0u; VkImageMemoryBarrier imageMemBarrier; if( bNeedsTexTransition ) { // GPU must stop using this texture before we can write into it // Also we need to do a transition imageMemBarrier = vkTexture->getImageMemoryBarrier(); imageMemBarrier.srcAccessMask = texAccessFlags & c_srcValidAccessFlags; imageMemBarrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; imageMemBarrier.oldLayout = vkTexture->mCurrLayout; imageMemBarrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; if( texAccessFlags == 0u ) { if( bufferAccessFlags == 0u ) { // Wait for nothing. We're only issuing a barrier // because of the texture transition srcStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; } } else { srcStage |= deriveStageFromTextureAccessFlags( texAccessFlags ); } insertRestoreBarrier( vkTexture, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL ); vkTexture->mCurrLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; numImageMemBarriers = 1u; } // Wait until earlier render, compute and transfers are done so we can copy what // they wrote (unless we're only here for a texture transition) vkCmdPipelineBarrier( mCurrentCmdBuffer, srcStage & mOwnerDevice->mSupportedStages, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, numMemBarriers, &memBarrier, 0u, 0, numImageMemBarriers, &imageMemBarrier ); } } //------------------------------------------------------------------------- void VulkanQueue::prepareForDownload( const BufferPacked *buffer, VulkanTextureGpu *texture ) { VkAccessFlags bufferAccessFlags = 0; VkPipelineStageFlags srcStage = 0; // Evaluate the stages which blocks us before we can begin our transfer if( buffer ) { BufferPackedDownloadMap::iterator it = mCopyDownloadBuffers.find( buffer ); if( it == mCopyDownloadBuffers.end() ) { if( /*buffer->getBufferPackedType() == BP_TYPE_UAV*/ 0 ) { bufferAccessFlags = VK_ACCESS_SHADER_WRITE_BIT; srcStage |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT | VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT | VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; } // else //{ // If the buffer is not BT_TYPE_UAV, the GPU won't modify these buffers, // we can start downloading right away without waiting //} } else { if( !it->second ) { bufferAccessFlags = VK_ACCESS_TRANSFER_WRITE_BIT; srcStage |= VK_PIPELINE_STAGE_TRANSFER_BIT; } else bufferAccessFlags = 0; // Consecutive reads don't require waiting } mCopyDownloadBuffers[buffer] = true; mCopyEndReadSrcBufferFlags |= VK_ACCESS_TRANSFER_READ_BIT; } OGRE_ASSERT_HIGH( !texture || dynamic_cast<VulkanTextureGpu *>( texture ) ); VulkanTextureGpu *vkTexture = static_cast<VulkanTextureGpu *>( texture ); VkAccessFlags texAccessFlags = 0; if( texture ) { TextureGpuDownloadMap::iterator it = mCopyDownloadTextures.find( vkTexture ); if( it == mCopyDownloadTextures.end() ) { if( vkTexture->mCurrLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL || vkTexture->mCurrLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL ) { OGRE_EXCEPT( Exception::ERR_INVALID_STATE, "Texture " + vkTexture->getName() + " is already in CopySrc or CopyDst layout, externally set. Perhaps " "you need to call RenderSystem::flushTextureCopyOperations", "VulkanQueue::prepareForDownload" ); } if( texture->isUav() ) { texAccessFlags |= VK_ACCESS_SHADER_WRITE_BIT; srcStage |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT | VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT | VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; } if( texture->getUsage() & TU_RENDERTARGET ) { texAccessFlags |= VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; if( !PixelUtil::isDepth( texture->getFormat() ) ) { texAccessFlags |= VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; srcStage |= VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; } else { texAccessFlags |= VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; srcStage |= VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT; } } } else { if( !it->second ) { OGRE_ASSERT_MEDIUM( vkTexture->mCurrLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL ); texAccessFlags = VK_ACCESS_TRANSFER_WRITE_BIT; srcStage |= VK_PIPELINE_STAGE_TRANSFER_BIT; } else { OGRE_ASSERT_MEDIUM( vkTexture->mCurrLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL ); texAccessFlags = 0; // Consecutive reads don't require waiting } } mCopyDownloadTextures[vkTexture] = true; } // One buffer barrier is enough for all buffers. // Unless we already issued a transfer to this same buffer const bool bNeedsBufferBarrier = ( bufferAccessFlags && ( mCopyStartWriteSrcBufferFlags & bufferAccessFlags ) != bufferAccessFlags ) || ( bufferAccessFlags & ( VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT ) ); mCopyStartWriteSrcBufferFlags |= bufferAccessFlags; const bool bNeedsTexTransition = vkTexture && vkTexture->mCurrLayout != VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; // Trigger the barrier if we actually have to wait. // And only if we haven't issued this barrier already if( bNeedsBufferBarrier || bNeedsTexTransition ) { uint32 numMemBarriers = 0u; VkMemoryBarrier memBarrier = {VK_STRUCTURE_TYPE_MEMORY_BARRIER}; if( bNeedsBufferBarrier ) { memBarrier.srcAccessMask = bufferAccessFlags & c_srcValidAccessFlags; memBarrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; numMemBarriers = 1u; } uint32 numImageMemBarriers = 0u; VkImageMemoryBarrier imageMemBarrier; if( bNeedsTexTransition ) { imageMemBarrier = vkTexture->getImageMemoryBarrier(); imageMemBarrier.srcAccessMask = texAccessFlags & c_srcValidAccessFlags; imageMemBarrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; imageMemBarrier.oldLayout = vkTexture->mCurrLayout; imageMemBarrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; insertRestoreBarrier( vkTexture, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL ); vkTexture->mCurrLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; numImageMemBarriers = 1u; if( !srcStage ) { // If we're here the texture is read-only and we only // need the barrier to perform a layout transition srcStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; } } // Wait until earlier render, compute and transfers are done so we can copy what // they wrote (unless we're only here for a texture transition) vkCmdPipelineBarrier( mCurrentCmdBuffer, srcStage & mOwnerDevice->mSupportedStages, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, numMemBarriers, &memBarrier, 0u, 0, numImageMemBarriers, &imageMemBarrier ); } } //------------------------------------------------------------------------- void VulkanQueue::getCopyEncoder( const BufferPacked *buffer, VulkanTextureGpu *texture, const bool bDownload ) { OgreAssert(mEncoderState != EncoderGraphicsOpen, "interrupting RenderPass not supported"); if( mEncoderState != EncoderCopyOpen ) { endRenderEncoder(); endComputeEncoder(); mEncoderState = EncoderCopyOpen; // Submission guarantees the host write being complete, as per // khronos.org/registry/vulkan/specs/1.0/html/vkspec.html#synchronization-submission-host-writes // So no need for a barrier before the transfer // // The only exception is when writing from CPU to GPU when a command that uses that region // has already been submitted via vkQueueSubmit (and you're using vkCmdWaitEvents to wait // for the CPU to write the data and give ok to the GPU). // Which Ogre does not do (too complex to get right). } if( bDownload ) prepareForDownload( buffer, texture ); else prepareForUpload( buffer, texture ); } //------------------------------------------------------------------------- void VulkanQueue::getCopyEncoderV1Buffer( const bool bDownload ) { OgreAssert(mEncoderState != EncoderGraphicsOpen, "interrupting RenderPass not supported"); if( mEncoderState != EncoderCopyOpen ) { endRenderEncoder(); endComputeEncoder(); mEncoderState = EncoderCopyOpen; } if( !bDownload ) { // V1 buffers are only used for vertex and index buffers // We assume v1 buffers don't try to write then read (or read then write) in a row const VkAccessFlags bufferAccessFlags = VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT | VK_ACCESS_INDEX_READ_BIT; if( ( mCopyEndReadDstBufferFlags & bufferAccessFlags ) != bufferAccessFlags ) { uint32 numMemBarriers = 0u; VkMemoryBarrier memBarrier = {VK_STRUCTURE_TYPE_MEMORY_BARRIER}; memBarrier.srcAccessMask = bufferAccessFlags & c_srcValidAccessFlags; memBarrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; numMemBarriers = 1u; // GPU must stop using this buffer before we can write into it vkCmdPipelineBarrier( mCurrentCmdBuffer, VK_PIPELINE_STAGE_VERTEX_INPUT_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, numMemBarriers, &memBarrier, 0u, 0, 0u, 0 ); } mCopyEndReadDstBufferFlags |= bufferAccessFlags; mCopyEndReadSrcBufferFlags |= VK_ACCESS_TRANSFER_WRITE_BIT; } else { mCopyEndReadSrcBufferFlags |= VK_ACCESS_TRANSFER_READ_BIT; } } //------------------------------------------------------------------------- void VulkanQueue::endCopyEncoder( void ) { if( mEncoderState != EncoderCopyOpen ) return; if( mCopyEndReadDstBufferFlags || !mImageMemBarrierPtrs.empty() ) { VkPipelineStageFlags dstStage = 0; uint32 numMemBarriers = 0u; VkMemoryBarrier memBarrier = {VK_STRUCTURE_TYPE_MEMORY_BARRIER}; if( mCopyEndReadDstBufferFlags ) { memBarrier.srcAccessMask = mCopyEndReadSrcBufferFlags & c_srcValidAccessFlags; memBarrier.dstAccessMask = mCopyEndReadDstBufferFlags; // Evaluate the stages we can unblock when our transfers are done dstStage |= deriveStageFromBufferAccessFlags( memBarrier.dstAccessMask ); numMemBarriers = 1u; } dstStage |= deriveStageFromTextureAccessFlags( mCopyEndReadDstTextureFlags ); if( dstStage == 0u ) { // Nothing needs to wait for us. Can happen if all we're // doing is copying from read-only textures (rare) dstStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; #if OGRE_DEBUG_MODE FastArray<TextureGpu *>::const_iterator itor = mImageMemBarrierPtrs.begin(); FastArray<TextureGpu *>::const_iterator endt = mImageMemBarrierPtrs.end(); while( itor != endt ) { OgreAssert( (( *itor )->getUsage() & TU_RENDERTARGET) == 0/*&& !( *itor )->isUav()*/, "endCopyEncoder says nothing will wait on this texture(s) but " "we don't know if a subsequent stage will write to it" ); ++itor; } #endif } // Wait until earlier render, compute and transfers are done // Block render, compute and transfers until we're done vkCmdPipelineBarrier( mCurrentCmdBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, dstStage & mOwnerDevice->mSupportedStages, 0, numMemBarriers, &memBarrier, 0u, 0, static_cast<uint32_t>( mImageMemBarriers.size() ), mImageMemBarriers.data() ); mImageMemBarriers.clear(); mImageMemBarrierPtrs.clear(); TextureGpuDownloadMap::const_iterator itor = mCopyDownloadTextures.begin(); TextureGpuDownloadMap::const_iterator endt = mCopyDownloadTextures.end(); while( itor != endt ) { itor->first->mCurrLayout = itor->first->mNextLayout; ++itor; } } mCopyEndReadSrcBufferFlags = 0; mCopyEndReadDstBufferFlags = 0; mCopyEndReadDstTextureFlags = 0; mCopyStartWriteSrcBufferFlags = 0; mCopyDownloadTextures.clear(); mCopyDownloadBuffers.clear(); mEncoderState = EncoderClosed; } //------------------------------------------------------------------------- void VulkanQueue::endRenderEncoder( const bool endRenderPassDesc ) { if( mEncoderState != EncoderGraphicsOpen ) return; mRenderSystem->_notifyActiveEncoderEnded(); if( endRenderPassDesc ) mRenderSystem->endRenderPassDescriptor(); mEncoderState = EncoderClosed; } //------------------------------------------------------------------------- void VulkanQueue::endComputeEncoder( void ) { if( mEncoderState != EncoderComputeOpen ) return; mEncoderState = EncoderClosed; mRenderSystem->_notifyActiveComputeEnded(); } //------------------------------------------------------------------------- void VulkanQueue::endAllEncoders( const bool endRenderPassDesc ) { endCopyEncoder(); endRenderEncoder( endRenderPassDesc ); endComputeEncoder(); } //------------------------------------------------------------------------- void VulkanQueue::notifyTextureDestroyed( VulkanTextureGpu *texture ) { if( mEncoderState == EncoderCopyOpen ) { bool needsToFlush = false; TextureGpuDownloadMap::const_iterator itor = mCopyDownloadTextures.find( texture ); if( itor != mCopyDownloadTextures.end() ) needsToFlush = true; else { FastArray<TextureGpu *>::const_iterator it2 = std::find( mImageMemBarrierPtrs.begin(), mImageMemBarrierPtrs.end(), texture ); if( it2 != mImageMemBarrierPtrs.end() ) needsToFlush = true; } if( needsToFlush ) { // If this asserts triggers, then the texture is probably being referenced // by something else doing anything on the texture and was interrupted // midway (since Ogre must ensure the texture ends in TRANSFER_SRC/DST_OPTIMAL // if the copy encoder is holding a reference. OGRE_ASSERT_LOW( texture->mCurrLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL || texture->mCurrLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL ); endCopyEncoder(); } } } //------------------------------------------------------------------------- void VulkanQueue::addWindowToWaitFor( VkSemaphore imageAcquisitionSemaph ) { OGRE_ASSERT_MEDIUM( mFamily == Graphics ); mGpuWaitFlags.push_back( VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT ); mGpuWaitSemaphForCurrCmdBuff.push_back( imageAcquisitionSemaph ); } //------------------------------------------------------------------------- void VulkanQueue::queueForDeletion(VkBuffer buffer, VkDeviceMemory memory) { mPerFrameData[mCurrentFrameIdx].mBufferGraveyard.push_back({buffer, memory}); } void VulkanQueue::queueForDeletion(const std::shared_ptr<VulkanDescriptorPool>& descriptorPool) { mPerFrameData[mCurrentFrameIdx].mDescriptorPoolGraveyard.push_back(descriptorPool); } void VulkanQueue::_waitOnFrame( uint8 frameIdx ) { VkFence fence = mPerFrameData[frameIdx].mProtectingFence; vkWaitForFences( mDevice, 1, &fence, VK_TRUE, UINT64_MAX ); // it is safe to free staging buffers now for(auto bm : mPerFrameData[frameIdx].mBufferGraveyard) { vkDestroyBuffer(mDevice, bm.first, nullptr); vkFreeMemory(mDevice, bm.second, nullptr); } mPerFrameData[frameIdx].mBufferGraveyard.clear(); mPerFrameData[frameIdx].mDescriptorPoolGraveyard.clear(); } //------------------------------------------------------------------------- bool VulkanQueue::_isFrameFinished( uint8 frameIdx ) { VkFence fence = mPerFrameData[frameIdx].mProtectingFence; VkResult ret = vkWaitForFences( mDevice, 1, &fence, VK_TRUE, 0u ); if( ret != VK_TIMEOUT ) { OGRE_VK_CHECK(ret); //recycleFences( fences ); return true; } return false; } //------------------------------------------------------------------------- void VulkanQueue::commitAndNextCommandBuffer( SubmissionType::SubmissionType submissionType ) { endCommandBuffer(); VkSubmitInfo submitInfo = {VK_STRUCTURE_TYPE_SUBMIT_INFO}; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &mCurrentCmdBuffer; if( !mGpuWaitSemaphForCurrCmdBuff.empty() ) { // We need to wait on these semaphores so that rendering can // only happen start the swapchain is done presenting submitInfo.waitSemaphoreCount = mGpuWaitSemaphForCurrCmdBuff.size(); submitInfo.pWaitSemaphores = mGpuWaitSemaphForCurrCmdBuff.data(); submitInfo.pWaitDstStageMask = mGpuWaitFlags.data(); } if( submissionType >= SubmissionType::NewFrameIdx ) { if( submissionType >= SubmissionType::EndFrameAndSwap ) { // Get semaphores so that presentation can wait for this job to finish rendering // (one for each window that will be swapped) for (auto w : mWindowsPendingSwap) { mGpuSignalSemaphForCurrCmdBuff.push_back(w->getRenderFinishedSemaphore()); w->setImageFence(mCurrentFence); } } if( !mGpuSignalSemaphForCurrCmdBuff.empty() ) { // We need to signal these semaphores so that presentation // can only happen after we're done rendering (presentation may not be the // only thing waiting for us though; thus we must set this with NewFrameIdx // and not just with EndFrameAndSwap) submitInfo.signalSemaphoreCount = mGpuSignalSemaphForCurrCmdBuff.size(); submitInfo.pSignalSemaphores = mGpuSignalSemaphForCurrCmdBuff.data(); } } OGRE_VK_CHECK(vkResetFences(mDevice, 1, &mCurrentFence) ); vkQueueSubmit( mQueue, 1u, &submitInfo, mCurrentFence ); mGpuWaitSemaphForCurrCmdBuff.clear(); mCurrentCmdBuffer = VK_NULL_HANDLE; if( submissionType >= SubmissionType::EndFrameAndSwap ) { for (auto w : mWindowsPendingSwap) w->_swapBuffers(); } if( submissionType >= SubmissionType::NewFrameIdx ) { mCurrentFrameIdx = (mCurrentFrameIdx + 1) % mPerFrameData.size(); } newCommandBuffer(); if( submissionType >= SubmissionType::EndFrameAndSwap ) { // acquireNextImage must be called after newCommandBuffer() for (auto w : mWindowsPendingSwap) w->acquireNextImage(); mWindowsPendingSwap.clear(); mGpuSignalSemaphForCurrCmdBuff.clear(); } } } // namespace Ogre
OGRECave/ogre
RenderSystems/Vulkan/src/OgreVulkanQueue.cpp
C++
mit
40,249
function foo() { var bar = ''; };
michaelghinrichs/hello-world
scope-chains-closures/scopes.js
JavaScript
mit
37
/*-- 简单测试node.js端使用的air-js -note 所有的模块以模块简称为属性名挂载在air上 */ var air = require('air-js'); var byteLength = air.byteLength; console.log(byteLength('中国人')); // => 6 console.log(byteLength('air')); // => 3 console.log(air.byteLength('air')); // => 3 console.log(air.clip('我是中国人', 8)); // => 我是中国… console.log(air.thousandFloat(78934.25)); // => 78,934.25
erniu/air
test-air.js
JavaScript
mit
442
import forIn from '../core/forIn' import forElements from '../core/forElements' export default function _parseAndApply (parse, apply, elements, options) { forIn(options, parse.bind(null, options)) return forElements(elements, apply.bind(null, options)) }
chirashijs/chirashi
lib/_internals/_parseAndApply.js
JavaScript
mit
261
<?php /* * This file is part of the PHPExifTool package. * * (c) Alchemy <support@alchemy.fr> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPExiftool\Driver\Tag\DICOM; use JMS\Serializer\Annotation\ExclusionPolicy; use PHPExiftool\Driver\AbstractTag; /** * @ExclusionPolicy("all") */ class SelectorSequencePointer extends AbstractTag { protected $Id = '0072,0052'; protected $Name = 'SelectorSequencePointer'; protected $FullName = 'DICOM::Main'; protected $GroupName = 'DICOM'; protected $g0 = 'DICOM'; protected $g1 = 'DICOM'; protected $g2 = 'Image'; protected $Type = '?'; protected $Writable = false; protected $Description = 'Selector Sequence Pointer'; }
bburnichon/PHPExiftool
lib/PHPExiftool/Driver/Tag/DICOM/SelectorSequencePointer.php
PHP
mit
822
<?php namespace kiwi\Http\Middleware; use kiwi\Http\Request; trait AuthorizesRequests { /** * Dont access without authorizing. * * @return void */ public function middleware() { if (!auth()->check()) { Request::redirect('/login'); } } }
jakobjohansson/Verbalizer
framework/Http/Middleware/AuthorizesRequests.php
PHP
mit
304
<?php namespace NilPortugues\ForbiddenFunctions\Console; use NilPortugues\ForbiddenFunctions\Command\CheckCommand; class Application extends \Symfony\Component\Console\Application { /** * Construct method */ public function __construct() { $name = <<<NAME ------------------------------------------------- PHP Forbidden Functions Checker ------------------------------------------------- NAME; parent::__construct($name); } /** * Initializes all the composer commands * * @return \Symfony\Component\Console\Command\Command[] */ protected function getDefaultCommands() { $commands = parent::getDefaultCommands(); $commands[] = new CheckCommand(); return $commands; } }
nilportugues/php_forbidden_functions
src/ForbiddenFunctions/Console/Application.php
PHP
mit
778
/** * This class is generated by jOOQ */ package de.piratenpartei.berlin.ldadmin.dbaccess.generated.routines; /** * This class is generated by jOOQ. */ @javax.annotation.Generated(value = { "http://www.jooq.org", "3.4.4" }, comments = "This class is generated by jOOQ") @java.lang.SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class DelegationChainForClosedIssue extends org.jooq.impl.AbstractRoutine<de.piratenpartei.berlin.ldadmin.dbaccess.generated.udt.records.DelegationChainRowRecord> { private static final long serialVersionUID = -1265014680; /** * The parameter <code>delegation_chain_for_closed_issue.RETURN_VALUE</code>. */ public static final org.jooq.Parameter<de.piratenpartei.berlin.ldadmin.dbaccess.generated.udt.records.DelegationChainRowRecord> RETURN_VALUE = createParameter("RETURN_VALUE", de.piratenpartei.berlin.ldadmin.dbaccess.generated.udt.DelegationChainRow.DELEGATION_CHAIN_ROW.getDataType()); /** * The parameter <code>delegation_chain_for_closed_issue.member_id_p</code>. */ public static final org.jooq.Parameter<java.lang.Integer> MEMBER_ID_P = createParameter("member_id_p", org.jooq.impl.SQLDataType.INTEGER); /** * The parameter <code>delegation_chain_for_closed_issue.issue_id_p</code>. */ public static final org.jooq.Parameter<java.lang.Integer> ISSUE_ID_P = createParameter("issue_id_p", org.jooq.impl.SQLDataType.INTEGER); /** * Create a new routine call instance */ public DelegationChainForClosedIssue() { super("delegation_chain_for_closed_issue", de.piratenpartei.berlin.ldadmin.dbaccess.generated.DefaultSchema.DEFAULT_SCHEMA, de.piratenpartei.berlin.ldadmin.dbaccess.generated.udt.DelegationChainRow.DELEGATION_CHAIN_ROW.getDataType()); setReturnParameter(RETURN_VALUE); addInParameter(MEMBER_ID_P); addInParameter(ISSUE_ID_P); } /** * Set the <code>member_id_p</code> parameter IN value to the routine */ public void setMemberIdP(java.lang.Integer value) { setValue(de.piratenpartei.berlin.ldadmin.dbaccess.generated.routines.DelegationChainForClosedIssue.MEMBER_ID_P, value); } /** * Set the <code>member_id_p</code> parameter to the function to be used with a {@link org.jooq.Select} statement */ public void setMemberIdP(org.jooq.Field<java.lang.Integer> field) { setField(MEMBER_ID_P, field); } /** * Set the <code>issue_id_p</code> parameter IN value to the routine */ public void setIssueIdP(java.lang.Integer value) { setValue(de.piratenpartei.berlin.ldadmin.dbaccess.generated.routines.DelegationChainForClosedIssue.ISSUE_ID_P, value); } /** * Set the <code>issue_id_p</code> parameter to the function to be used with a {@link org.jooq.Select} statement */ public void setIssueIdP(org.jooq.Field<java.lang.Integer> field) { setField(ISSUE_ID_P, field); } }
plattformbrandenburg/ldadmin
src/main/java/de/piratenpartei/berlin/ldadmin/dbaccess/generated/routines/DelegationChainForClosedIssue.java
Java
mit
2,840
using Microsoft.Azure.ServiceBus; using Microsoft.Extensions.Logging; using System; using System.IO; namespace Microsoft.eShopOnContainers.BuildingBlocks.EventBusServiceBus { public class DefaultServiceBusPersisterConnection :IServiceBusPersisterConnection { private readonly ILogger<DefaultServiceBusPersisterConnection> _logger; private readonly ServiceBusConnectionStringBuilder _serviceBusConnectionStringBuilder; private ITopicClient _topicClient; bool _disposed; public DefaultServiceBusPersisterConnection(ServiceBusConnectionStringBuilder serviceBusConnectionStringBuilder, ILogger<DefaultServiceBusPersisterConnection> logger) { _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _serviceBusConnectionStringBuilder = serviceBusConnectionStringBuilder ?? throw new ArgumentNullException(nameof(serviceBusConnectionStringBuilder)); _topicClient = new TopicClient(_serviceBusConnectionStringBuilder, RetryPolicy.Default); } public ServiceBusConnectionStringBuilder ServiceBusConnectionStringBuilder => _serviceBusConnectionStringBuilder; public ITopicClient CreateModel() { if(_topicClient.IsClosedOrClosing) { _topicClient = new TopicClient(_serviceBusConnectionStringBuilder, RetryPolicy.Default); } return _topicClient; } public void Dispose() { if (_disposed) return; _disposed = true; } } }
TypeW/eShopOnContainers
src/BuildingBlocks/EventBus/EventBusServiceBus/DefaultServiceBusPersisterConnection.cs
C#
mit
1,621
/// <reference path="./event.ts" /> module Fusion { /** * Represents a component of discrete functionality in a Fusion application */ export interface Widget extends EventEmittable { } /** * Represents a component of discrete functionality in a Fusion application */ export class WidgetBase extends EventEmitter implements Widget { constructor() { super(); } } }
jumpinjackie/mapguide-ajax-viewer
shared/src/fusion/widget.ts
TypeScript
mit
448
'use strict'; app.controller('DeleteTripModalCtrl', function($scope, $uibModalInstance, TripFactory, $routeParams, $window, ActivityFactory, MemberFactory){ let tripId = $routeParams.tripId; $scope.close = () => { $uibModalInstance.close(); }; //Not only do we want to delete the trip object connected to that user from Firebase but we also want to delete anything associated with the trip - notes, packing list, and trails that have been added. $scope.deleteTrip = ()=>{ TripFactory.deleteTrip(tripId) .then(()=>{ console.log("trip was deleted"); $scope.close(); $window.location.href='#/parks/explore'; return ActivityFactory.getActivities(tripId) }) .then((activityData)=>{ console.log("activities in trip", activityData); Object.keys(activityData).forEach((activityId)=>{ ActivityFactory.deleteActivityFromTrip(activityId); }); return TripFactory.getUserPackingList(tripId) }) .then((packingData)=>{ console.log("user packing list", packingData); Object.keys(packingData).forEach((listId)=>{ TripFactory.deleteItemFromList(listId); }); return MemberFactory.getMembersOfTrip(tripId) }) .then((members)=>{ console.log("members", members); Object.keys(members).forEach((memberId)=>{ MemberFactory.deleteMember(memberId); }); return TripFactory.getInvitationsInTrip(tripId) }) .then((invitations)=>{ console.log("invitations", invitations); Object.keys(invitations).forEach((invitationId)=>{ TripFactory.deleteInvitation(invitationId); }); }) }; });
delainewendling/NP_trip_planner
deploy/app/controllers/DeleteTripModalCtrl.js
JavaScript
mit
1,660
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace XmlGuy { public class XmlElement : AbstractXmlElement { public XmlElement(XmlElement parent = null) : base(parent) { Children = new List<IXmlElement>(); Attributes = new Dictionary<string, string>(); } public IList<IXmlElement> Children { get; set; } public IDictionary<string, string> Attributes { get; set; } public XmlElement Up() { return Parent; } public XmlElement Add(string name, params object[] args) { string value = null; Dictionary<string, string> attributes = new Dictionary<string, string>(); if (args != null) { foreach (var arg in args) { if (arg is string) value = arg as string; else foreach (var prop in arg.GetType().GetProperties()) attributes.Add(prop.Name, prop.GetValue(arg, null) as string); } } return Add(name, value, attributes); } private XmlElement Add(string name, string value, IDictionary<string, string> attributes) { if (Value != null) throw new InvalidOperationException("XML Element " + Name + " has a text value: it cannot contain child elements"); var child = new XmlElement(this) { Name = name, Value = value, Attributes = attributes }; Children.Add(child); return child; } public XmlElement CData(string data) { Children.Add(new CDataElement(this) { Value = data }); return this; } } public class CDataElement : AbstractXmlElement { public CDataElement(XmlElement parent = null) : base(parent) { } } }
windracer/xmlguy
src/XmlElement.cs
C#
mit
1,589
import isArray from '../../util/isArray' import forEach from '../../util/forEach' import TreeIndex from '../../util/TreeIndex' import NodeIndex from './NodeIndex' class PropertyIndex extends NodeIndex { constructor(property) { super() this._property = property || 'id' this.index = new TreeIndex() } /** Get all indexed nodes for a given path. @param {Array<String>} path @returns A node or an object with ids and nodes as values. */ get(path) { return this.index.get(path) || {} } /** Collects nodes recursively. @returns An object with ids as keys and nodes as values. */ getAll(path) { return this.index.getAll(path) } /** Check if a node should be indexed. Used internally only. Override this in subclasses to achieve a custom behavior. @private @param {Node} @returns {Boolean} true if the given node should be added to the index. */ select(node) { // eslint-disable-line return true } /** Called when a node has been created. Override this in subclasses for customization. @private @param {Node} node */ create(node) { var values = node[this._property] if (!isArray(values)) { values = [values] } forEach(values, function(value) { this.index.set([value, node.id], node) }.bind(this)) } /** * Called when a node has been deleted. * * Override this in subclasses for customization. * * @private * @param {model/data/Node} node */ delete(node) { var values = node[this._property] if (!isArray(values)) { values = [values] } forEach(values, function(value) { this.index.delete([value, node.id]) }.bind(this)) } /** Called when a property has been updated. Override this in subclasses for customization. @private @param {Node} node */ update(node, path, newValue, oldValue) { if (!this.select(node) || path[1] !== this._property) return var values = oldValue if (!isArray(values)) { values = [values] } forEach(values, function(value) { this.index.delete([value, node.id]) }.bind(this)) values = newValue if (!isArray(values)) { values = [values] } forEach(values, function(value) { this.index.set([value, node.id], node) }.bind(this)) } set(node, path, newValue, oldValue) { this.update(node, path, newValue, oldValue) } _clear() { this.index.clear() } _initialize(data) { forEach(data.getNodes(), function(node) { if (this.select(node)) { this.create(node) } }.bind(this)) } } export default PropertyIndex
andene/substance
model/data/PropertyIndex.js
JavaScript
mit
2,682
/* * Smush In - jQuery plugin * * Copyright (c) 2013 Shane Donnelly * * Licensed under the MIT license: * http://www.opensource.org/licenses/mit-license.php * * Project home: * http://shanejdonnelly.github.io/smush-in * Version: 1.0 * */ ;(function ($) { "use strict"; /* CLASS DEFINITION * ====================== */ var SmushIn = function ($element, options) { this.settings = options; this.$el = $element; this.setup(); } SmushIn.prototype = { constructor: SmushIn, setup: function(){ this.height = this.$el.height(); this.width = this.$el.width(); this.left = parseInt(this.$el.css('left')); this.top = parseInt(this.$el.css('top')); this.font_size = parseInt(this.$el.css('font-size')); this.window_width = $(window).width(); this.window_height = $(window).height(); this.max_anim_speed = (this.settings.speed === 'slow') ? 130 : 75; if(this.settings.overshot === 0){ this.settings.overshot = this.rand(10,70) } //decide direction if(this.settings.from_direction === 'random') { var random_direction = (this.rand(0,20) < 10) ? 'left' : 'right'; this.horzAnim(random_direction); } else{ this.horzAnim(this.settings.from_direction); } }, horzAnim: function(from_direction){ var base = this, start_position = (from_direction === 'right') ? ( base.rand((base.window_width * 1.1), (base.window_width * 2)) ) : ( start_position = -1 * base.rand((base.window_width * 1.1), (base.window_width * 2)) ), fly_to = (from_direction === 'right') ? (base.left - base.settings.overshot) : (base.left + base.settings.overshot); //set start position base.$el.css('left', start_position ); setTimeout(function(){ //fly in base.$el.show().animate({'left': fly_to}, base.rand(200,500 ), function(){ //hit the 'wall' base.$el.animate( { 'height': (base.height * base.rand(1,2)), 'width': base.width * base.rand(.3, .7), 'margin-top': -(base.height * base.rand(.2,.4)) }, base.max_anim_speed, function(){ //bounce back base.$el.animate( { 'height': base.height, 'width': base.width, 'margin-top':0, 'left':base.left }, ( base.max_anim_speed * 1.75)); }); }); }, base.rand(500,1500)); }, //returns float rand: function(min, max){ return Math.random() * (max - min) + min; } } /* PLUGIN DEFINITION * ======================= */ $.fn.smushIn = function (custom_options) { return this.each(function () { var $el = $(this), options = $.extend({}, $.fn.smushIn.defaults, custom_options); new SmushIn($el, options) }) } $.fn.smushIn.defaults = { 'overshot' : 0, 'speed' : 'slow', 'from_direction' : 'left' } $.fn.smushIn.Constructor = SmushIn })(window.jQuery);
shanejdonnelly/smush-in
smushIn.js
JavaScript
mit
3,613
<?php // SonataMediaBundle:Form:media_widgets.html.twig return array ( );
DevKhater/YallaWebSite
app/cache/prod/assetic/config/4/423e5d4324992a3bd20ae71d066b011d.php
PHP
mit
75
<?php defined('_JEXEC') or die('Restricted access'); /** * Mercado Pago plugin * * @author Developers Mercado Pago <modulos@mercadopago.com> * @version 2.0.5 * @package VirtueMart * @subpackage payment * @link https://www.mercadopago.com * @copyright Copyright © 2016 MercadoPago.com * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php */ ?> <br/> <img src="<?php echo MercadoPagoHelper::getBanner($viewData['site_id']);?>" id="mercadopago-banner-basic">
yaelduckwen/lo_imaginario
web2/plugins/vmpayment/mercadopago/mercadopago/tmpl/mercadopago_checkout_standard.php
PHP
mit
491
#!/usr/bin/env node "use strict"; // XXX currently this project is written to support node 0.10.* // when Meteor 1.4 is ready, we can rewrite in es6 var Vorpal = require("vorpal")(), Path = require("path"), Fs = require("fs"), Exec = require("child_process").exec, Spawn = require("child_process").spawn, Rimraf = require("rimraf").sync, Promise = require("es6-promise").Promise, GitHub = require("github-download"), Mkdirp = require("mkdirp") ; var root = Path.resolve(__dirname, "../"); var built = [ ".remote", "node_modules", "packages", ".meteor/local" ]; function installDep(src, dep){ return new Promise(function(resolve, reject){ Mkdirp(src, function(err) { if (err) return reject(err); GitHub(dep, src) .on("error", function(err){}) // XXX handle error .on("end", resolve); }); }); } Vorpal .command("setup") .description("Bootstrap an application. This may take some time...") .option("-c, --clean", "Force rebuild of application(s)") .option("-l, --log [level]", "Sets verbosity level.") .action(function(args, cb) { var app = root; var options = args.options; if (options.clean) { console.log("Cleaning all dependencies..."); for (var i = 0; i < built.length; i++) { var localPath = built[i]; Rimraf(Path.join(app, localPath)); } } var packageFile = require(Path.join(app, "package.json")); var depPromises = []; if (packageFile.apollos && packageFile.apollos.resource) { for (var subDir in packageFile.apollos.resource) { if (!packageFile.apollos.resource.hasOwnProperty(subDir)) continue; var localPath = Path.join(app, subDir); var deps = packageFile.apollos.resource[subDir]; for (var dep in deps) { if (!deps.hasOwnProperty(dep)) continue; console.log("installing resource: " + dep) depPromises.push(installDep(Path.join(localPath, dep), deps[dep])); } } } // var npmPromises = []; // npmPromises.push( // new Promise(function(p, f){ // console.log("installing npm deps"); // var child = Spawn("npm", ["install"], { // cwd: app, stdio: "inherit" // }); // child.on("error", f); // }) // ); return Promise.all(depPromises) .then(function(){ console.log("Holtzmann should be ready to go!"); // console.log("you will need to clone it down manually"); // console.log("\n"); // console.log(" cd " + app + "/.remote/ && git clone https://github.com/NewSpring/ops-settings.git settings"); // console.log("\n"); cb(); }) .catch(function(err) { console.error(err); cb(); }) }); Vorpal .command("run") .description("Start a local server to serve the site and print its address in your console") .option("-p, --port", "Choose a port to run the application") .option("-v, --verbosity [level]", "Sets verbosity level.") .option("-q, --quick", "Only runs the app, not apollos watcher as well") .option("-n, --native", "Runs the native version of the application") .option("--ios", "Run the native app of a given site in the iOS simulator") .option("--android", "Run the native app of a given site in the Android simulator") .option("--device", "Run the native app of a given site on the device of the platform") .option("--production", "Run the application in production mode") .option("--debug", "Run the application in debug mode") .action(function(args, cb) { var app = root; var options = args.options; var packageFile = require(Path.join(app, "package.json")); var env = process.env; env.METEOR_DISABLE_FS_FIBERS = 1; // https://github.com/meteor/meteor/pull/7668#issuecomment-256230102 if (options.debug) env.METEOR_PROFILE = 200; if (options.production) env.NODE_ENV = "production"; if (!options.ios && !options.android && !options.native) env.WEB = true; if (options.native || options.ios || options.android) env.NATIVE = true; var configFile = Path.join(__dirname, "apollos-runtime.json"); if (!Fs.existsSync(configFile)) { Fs.writeFileSync(configFile, JSON.stringify({ WEB: !!env.WEB }, null, 2), "utf8"); } var apolloRuntime = require(configFile); // removes the built files for a rebuild if (!options.quick && !!apolloRuntime.WEB != !!env.WEB) { Rimraf(Path.join(app, ".meteor/local")); } var meteorArgs = [ "--settings" ]; if (options.ios && !options.device) meteorArgs.unshift("run", "ios"); if (options.android && !options.device) meteorArgs.unshift("run", "android"); if (options.ios && options.device) meteorArgs.unshift("run", "ios-device"); if (options.android && options.device) meteorArgs.unshift("run", "android-device"); if ( packageFile.apollos && packageFile.apollos.settings && Fs.existsSync(Path.join(app, packageFile.apollos.settings)) ) { meteorArgs.push(packageFile.apollos.settings) } else { meteorArgs.push(Path.join(app, ".meteor/sample.settings.json")); } function run() { var meteor = Spawn("meteor", meteorArgs, { stdio: "inherit", cwd: app, env: env }); } Fs.writeFileSync(configFile, JSON.stringify({ WEB: !!env.WEB }, null, 2), "utf8"); if (options.production) { console.log("Building apollos in production mode"); meteorArgs.push("--production"); } run(); }); Vorpal .parse(process.argv);
NewSpring/apollos-core
.bin/index.js
JavaScript
mit
5,565
function calculaIMC(altura, peso) { return peso / (altura * altura); } console.log("O seu imc é: " + calculaIMC(prompt("Sua altura? "), prompt("Seu peso? "))); //https://pt.stackoverflow.com/q/327751/101
maniero/SOpt
JavaScript/Algorithm/Bmi2.js
JavaScript
mit
207
/* * Sample Adjuster * */ #include "LimitAdjuster.h" // Sample Simple Adjuster class Sample1 : public SimpleAdjuster { public: const char* GetLimitName() { return GetGVM().IsSA()? "FoodLimit" : nullptr; } void ChangeLimit(int, const std::string& value) { injector::WriteMemory(0xF00D, std::stof(value)); } // Instantiate the adjuster on the global scope } simple_adjuster_sample; // Sample "Complex" Adjuster class Sample2 : public Adjuster { public: // ID enum, those ids are local between each Adjuster, you shouldn't worry about conflicts with other adjusters enum { CoffeeLimit, FoodLimit, IceLimit }; // Get the limit table that we're going to handle const Limit* GetLimits() { static Limit limits[] = { // You could use DEFINE_LIMIT(CoffeeLimit) instead of {...} { "CoffeeLimit", CoffeeLimit }, { "FoodLimit", FoodLimit }, { "IceLimit", IceLimit }, // You could also use FINISH_LIMITS() { nullptr, 0 } }; // This Sample Adjuster can handle only San Andreas game if(GetGVM().IsSA()) return limits; return nullptr; } // Change an specific limit void ChangeLimit(int id, const std::string& value) { switch(id) { case CoffeeLimit: // Changes the cofee limit injector::WriteMemory(0xC0FFEE, std::stoi(value, 0, 0)); break; case FoodLimit: // Changes the food limit injector::WriteMemory(0xF00D, std::stof(value)); break; case IceLimit: // Changes the ice limit injector::WriteMemory<short>(0x1CED, std::stoi(value) % 1337); break; } } // Instantiate the adjuster on the global scope } complex_adjuster_sample;
ThirteenAG/limit_adjuster_gta3vcsa
src/sample/sample.cpp
C++
mit
2,162
<?php if ( ! defined( 'ABSPATH' ) ) { die( '-1' ); } /** * Class Vc_Vendor_Woocommerce * * @since 4.4 * @todo move to separate file and dir. */ class Vc_Vendor_Woocommerce { protected static $product_fields_list = false; protected static $order_fields_list = false; /** * @since 4.4 */ public function load() { if ( class_exists( 'WooCommerce' ) ) { add_action( 'vc_after_mapping', array( $this, 'mapShortcodes', ) ); add_action( 'vc_backend_editor_render', array( $this, 'enqueueJsBackend', ) ); add_action( 'vc_frontend_editor_render', array( $this, 'enqueueJsFrontend', ) ); add_filter( 'vc_grid_item_shortcodes', array( $this, 'mapGridItemShortcodes', ) ); add_action( 'vc_vendor_yoastseo_filter_results', array( $this, 'yoastSeoCompatibility', ) ); add_filter( 'woocommerce_product_tabs', array( $this, 'addContentTabPageEditable', ) ); add_filter( 'woocommerce_shop_manager_editable_roles', array( $this, 'addShopManagerRoleToEditable', ) ); } } /** * @param $rules * @return array */ public function addShopManagerRoleToEditable( $rules ) { $rules[] = 'shop_manager'; return array_unique( $rules ); } /** * @param $tabs * @return mixed */ public function addContentTabPageEditable( $tabs ) { if ( vc_is_page_editable() ) { // Description tab - shows product content $tabs['description'] = array( 'title' => esc_html__( 'Description', 'woocommerce' ), 'priority' => 10, 'callback' => 'woocommerce_product_description_tab', ); } return $tabs; } /** * @since 4.4 */ public function enqueueJsBackend() { wp_enqueue_script( 'vc_vendor_woocommerce_backend', vc_asset_url( 'js/vendors/woocommerce.js' ), array( 'vc-backend-min-js' ), '1.0', true ); } /** * @since 4.4 */ public function enqueueJsFrontend() { wp_enqueue_script( 'vc_vendor_woocommerce_frontend', vc_asset_url( 'js/vendors/woocommerce.js' ), array( 'vc-frontend-editor-min-js' ), '1.0', true ); } /** * Add settings for shortcodes * * @param $tag * * @return array * @since 4.9 * */ public function addShortcodeSettings( $tag ) { $args = array( 'type' => 'post', 'child_of' => 0, 'parent' => '', 'orderby' => 'name', 'order' => 'ASC', 'hide_empty' => false, 'hierarchical' => 1, 'exclude' => '', 'include' => '', 'number' => '', 'taxonomy' => 'product_cat', 'pad_counts' => false, ); $order_by_values = array( '', esc_html__( 'Date', 'js_composer' ) => 'date', esc_html__( 'ID', 'js_composer' ) => 'ID', esc_html__( 'Author', 'js_composer' ) => 'author', esc_html__( 'Title', 'js_composer' ) => 'title', esc_html__( 'Modified', 'js_composer' ) => 'modified', esc_html__( 'Random', 'js_composer' ) => 'rand', esc_html__( 'Comment count', 'js_composer' ) => 'comment_count', esc_html__( 'Menu order', 'js_composer' ) => 'menu_order', esc_html__( 'Menu order & title', 'js_composer' ) => 'menu_order title', esc_html__( 'Include', 'js_composer' ) => 'include', ); $order_way_values = array( '', esc_html__( 'Descending', 'js_composer' ) => 'DESC', esc_html__( 'Ascending', 'js_composer' ) => 'ASC', ); $settings = array(); switch ( $tag ) { case 'woocommerce_cart': $settings = array( 'name' => esc_html__( 'Cart', 'js_composer' ), 'base' => 'woocommerce_cart', 'icon' => 'icon-wpb-woocommerce', 'category' => esc_html__( 'WooCommerce', 'js_composer' ), 'description' => esc_html__( 'Displays the cart contents', 'js_composer' ), 'show_settings_on_create' => false, 'php_class_name' => 'Vc_WooCommerce_NotEditable', ); break; case 'woocommerce_checkout': /** * @shortcode woocommerce_checkout * @description Used on the checkout page, the checkout shortcode displays the checkout process. * @no_params * @not_editable */ $settings = array( 'name' => esc_html__( 'Checkout', 'js_composer' ), 'base' => 'woocommerce_checkout', 'icon' => 'icon-wpb-woocommerce', 'category' => esc_html__( 'WooCommerce', 'js_composer' ), 'description' => esc_html__( 'Displays the checkout', 'js_composer' ), 'show_settings_on_create' => false, 'php_class_name' => 'Vc_WooCommerce_NotEditable', ); break; case 'woocommerce_order_tracking': /** * @shortcode woocommerce_order_tracking * @description Lets a user see the status of an order by entering their order details. * @no_params * @not_editable */ $settings = array( 'name' => esc_html__( 'Order Tracking Form', 'js_composer' ), 'base' => 'woocommerce_order_tracking', 'icon' => 'icon-wpb-woocommerce', 'category' => esc_html__( 'WooCommerce', 'js_composer' ), 'description' => esc_html__( 'Lets a user see the status of an order', 'js_composer' ), 'show_settings_on_create' => false, 'php_class_name' => 'Vc_WooCommerce_NotEditable', ); break; case 'woocommerce_my_account': /** * @shortcode woocommerce_my_account * @description Shows the ‘my account’ section where the customer can view past orders and update their information. * You can specify the number or order to show, it’s set by default to 15 (use -1 to display all orders.) * * @param order_count integer * Current user argument is automatically set using get_user_by( ‘id’, get_current_user_id() ). */ $settings = array( 'name' => esc_html__( 'My Account', 'js_composer' ), 'base' => 'woocommerce_my_account', 'icon' => 'icon-wpb-woocommerce', 'category' => esc_html__( 'WooCommerce', 'js_composer' ), 'description' => esc_html__( 'Shows the "my account" section', 'js_composer' ), 'params' => array( array( 'type' => 'textfield', 'heading' => esc_html__( 'Order count', 'js_composer' ), 'value' => 15, 'save_always' => true, 'param_name' => 'order_count', 'description' => esc_html__( 'You can specify the number or order to show, it\'s set by default to 15 (use -1 to display all orders.)', 'js_composer' ), ), ), ); break; case 'recent_products': /** * @shortcode recent_products * @description Lists recent products – useful on the homepage. The ‘per_page’ shortcode determines how many products * to show on the page and the columns attribute controls how many columns wide the products should be before wrapping. * To learn more about the default ‘orderby’ parameters please reference the WordPress Codex: http://codex.wordpress.org/Class_Reference/WP_Query * * @param per_page integer * @param columns integer * @param orderby array * @param order array */ $settings = array( 'name' => esc_html__( 'Recent products', 'js_composer' ), 'base' => 'recent_products', 'icon' => 'icon-wpb-woocommerce', 'category' => esc_html__( 'WooCommerce', 'js_composer' ), 'description' => esc_html__( 'Lists recent products', 'js_composer' ), 'params' => array( array( 'type' => 'textfield', 'heading' => esc_html__( 'Per page', 'js_composer' ), 'value' => 12, 'save_always' => true, 'param_name' => 'per_page', 'description' => esc_html__( 'The "per_page" shortcode determines how many products to show on the page', 'js_composer' ), ), array( 'type' => 'textfield', 'heading' => esc_html__( 'Columns', 'js_composer' ), 'value' => 4, 'param_name' => 'columns', 'save_always' => true, 'description' => esc_html__( 'The columns attribute controls how many columns wide the products should be before wrapping.', 'js_composer' ), ), array( 'type' => 'dropdown', 'heading' => esc_html__( 'Order by', 'js_composer' ), 'param_name' => 'orderby', 'value' => $order_by_values, 'std' => 'date', // default WC value for recent_products 'save_always' => true, 'description' => sprintf( esc_html__( 'Select how to sort retrieved products. More at %s.', 'js_composer' ), '<a href="https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>' ), ), array( 'type' => 'dropdown', 'heading' => esc_html__( 'Sort order', 'js_composer' ), 'param_name' => 'order', 'value' => $order_way_values, 'std' => 'DESC', // default WC value 'save_always' => true, 'description' => sprintf( esc_html__( 'Designates the ascending or descending order. More at %s.', 'js_composer' ), '<a href="https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>' ), ), ), ); break; case 'featured_products': /** * @shortcode featured_products * @description Works exactly the same as recent products but displays products which have been set as “featured”. * * @param per_page integer * @param columns integer * @param orderby array * @param order array */ $settings = array( 'name' => esc_html__( 'Featured products', 'js_composer' ), 'base' => 'featured_products', 'icon' => 'icon-wpb-woocommerce', 'category' => esc_html__( 'WooCommerce', 'js_composer' ), 'description' => esc_html__( 'Display products set as "featured"', 'js_composer' ), 'params' => array( array( 'type' => 'textfield', 'heading' => esc_html__( 'Per page', 'js_composer' ), 'value' => 12, 'param_name' => 'per_page', 'save_always' => true, 'description' => esc_html__( 'The "per_page" shortcode determines how many products to show on the page', 'js_composer' ), ), array( 'type' => 'textfield', 'heading' => esc_html__( 'Columns', 'js_composer' ), 'value' => 4, 'param_name' => 'columns', 'save_always' => true, 'description' => esc_html__( 'The columns attribute controls how many columns wide the products should be before wrapping.', 'js_composer' ), ), array( 'type' => 'dropdown', 'heading' => esc_html__( 'Order by', 'js_composer' ), 'param_name' => 'orderby', 'value' => $order_by_values, 'std' => 'date', // default WC value 'save_always' => true, 'description' => sprintf( esc_html__( 'Select how to sort retrieved products. More at %s.', 'js_composer' ), '<a href="https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>' ), ), array( 'type' => 'dropdown', 'heading' => esc_html__( 'Sort order', 'js_composer' ), 'param_name' => 'order', 'value' => $order_way_values, 'std' => 'DESC', // default WC value 'save_always' => true, 'description' => sprintf( esc_html__( 'Designates the ascending or descending order. More at %s.', 'js_composer' ), '<a href="s://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>' ), ), ), ); break; case 'product': /** * @shortcode product * @description Show a single product by ID or SKU. * * @param id integer * @param sku string * If the product isn’t showing, make sure it isn’t set to Hidden in the Catalog Visibility. * To find the Product ID, go to the Product > Edit screen and look in the URL for the postid= . */ $settings = array( 'name' => esc_html__( 'Product', 'js_composer' ), 'base' => 'product', 'icon' => 'icon-wpb-woocommerce', 'category' => esc_html__( 'WooCommerce', 'js_composer' ), 'description' => esc_html__( 'Show a single product by ID or SKU', 'js_composer' ), 'params' => array( array( 'type' => 'autocomplete', 'heading' => esc_html__( 'Select identificator', 'js_composer' ), 'param_name' => 'id', 'description' => esc_html__( 'Input product ID or product SKU or product title to see suggestions', 'js_composer' ), ), array( 'type' => 'hidden', // This will not show on render, but will be used when defining value for autocomplete 'param_name' => 'sku', ), ), ); break; case 'products': $settings = array( 'name' => esc_html__( 'Products', 'js_composer' ), 'base' => 'products', 'icon' => 'icon-wpb-woocommerce', 'category' => esc_html__( 'WooCommerce', 'js_composer' ), 'description' => esc_html__( 'Show multiple products by ID or SKU.', 'js_composer' ), 'params' => array( array( 'type' => 'textfield', 'heading' => esc_html__( 'Columns', 'js_composer' ), 'value' => 4, 'param_name' => 'columns', 'save_always' => true, ), array( 'type' => 'dropdown', 'heading' => esc_html__( 'Order by', 'js_composer' ), 'param_name' => 'orderby', 'value' => $order_by_values, 'std' => 'title', // Default WC value 'save_always' => true, 'description' => sprintf( esc_html__( 'Select how to sort retrieved products. More at %s. Default by Title', 'js_composer' ), '<a href="https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>' ), ), array( 'type' => 'dropdown', 'heading' => esc_html__( 'Sort order', 'js_composer' ), 'param_name' => 'order', 'value' => $order_way_values, 'std' => 'ASC', // default WC value 'save_always' => true, 'description' => sprintf( esc_html__( 'Designates the ascending or descending order. More at %s. Default by ASC', 'js_composer' ), '<a href="https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>' ), ), array( 'type' => 'autocomplete', 'heading' => esc_html__( 'Products', 'js_composer' ), 'param_name' => 'ids', 'settings' => array( 'multiple' => true, 'sortable' => true, 'unique_values' => true, // In UI show results except selected. NB! You should manually check values in backend ), 'save_always' => true, 'description' => esc_html__( 'Enter List of Products', 'js_composer' ), ), array( 'type' => 'hidden', 'param_name' => 'skus', ), ), ); break; case 'add_to_cart': /** * @shortcode add_to_cart * @description Show the price and add to cart button of a single product by ID (or SKU). * * @param id integer * @param sku string * @param style string * If the product isn’t showing, make sure it isn’t set to Hidden in the Catalog Visibility. */ $settings = array( 'name' => esc_html__( 'Add to cart', 'js_composer' ), 'base' => 'add_to_cart', 'icon' => 'icon-wpb-woocommerce', 'category' => esc_html__( 'WooCommerce', 'js_composer' ), 'description' => esc_html__( 'Show multiple products by ID or SKU', 'js_composer' ), 'params' => array( array( 'type' => 'autocomplete', 'heading' => esc_html__( 'Select identificator', 'js_composer' ), 'param_name' => 'id', 'description' => esc_html__( 'Input product ID or product SKU or product title to see suggestions', 'js_composer' ), ), array( 'type' => 'hidden', 'param_name' => 'sku', ), array( 'type' => 'textfield', 'heading' => esc_html__( 'Wrapper inline style', 'js_composer' ), 'param_name' => 'style', ), ), ); break; case 'add_to_cart_url': /** * @shortcode add_to_cart_url * @description Print the URL on the add to cart button of a single product by ID. * * @param id integer * @param sku string */ $settings = array( 'name' => esc_html__( 'Add to cart URL', 'js_composer' ), 'base' => 'add_to_cart_url', 'icon' => 'icon-wpb-woocommerce', 'category' => esc_html__( 'WooCommerce', 'js_composer' ), 'description' => esc_html__( 'Show URL on the add to cart button', 'js_composer' ), 'params' => array( array( 'type' => 'autocomplete', 'heading' => esc_html__( 'Select identificator', 'js_composer' ), 'param_name' => 'id', 'description' => esc_html__( 'Input product ID or product SKU or product title to see suggestions', 'js_composer' ), ), array( 'type' => 'hidden', 'param_name' => 'sku', ), ), ); break; case 'product_page': /** * @shortcode product_page * @description Show a full single product page by ID or SKU. * * @param id integer * @param sku string */ $settings = array( 'name' => esc_html__( 'Product page', 'js_composer' ), 'base' => 'product_page', 'icon' => 'icon-wpb-woocommerce', 'category' => esc_html__( 'WooCommerce', 'js_composer' ), 'description' => esc_html__( 'Show single product by ID or SKU', 'js_composer' ), 'params' => array( array( 'type' => 'autocomplete', 'heading' => esc_html__( 'Select identificator', 'js_composer' ), 'param_name' => 'id', 'description' => esc_html__( 'Input product ID or product SKU or product title to see suggestions', 'js_composer' ), ), array( 'type' => 'hidden', 'param_name' => 'sku', ), ), ); break; case 'product_category': /** * @shortcode product_category * @description Show multiple products in a category by slug. * * @param per_page integer * @param columns integer * @param orderby array * @param order array * @param category string * Go to: WooCommerce > Products > Categories to find the slug column. */ // All this move to product $categories = get_categories( $args ); $product_categories_dropdown = array(); $this->getCategoryChildsFull( 0, $categories, 0, $product_categories_dropdown ); $settings = array( 'name' => esc_html__( 'Product category', 'js_composer' ), 'base' => 'product_category', 'icon' => 'icon-wpb-woocommerce', 'category' => esc_html__( 'WooCommerce', 'js_composer' ), 'description' => esc_html__( 'Show multiple products in a category', 'js_composer' ), 'params' => array( array( 'type' => 'textfield', 'heading' => esc_html__( 'Per page', 'js_composer' ), 'value' => 12, 'save_always' => true, 'param_name' => 'per_page', 'description' => esc_html__( 'How much items per page to show', 'js_composer' ), ), array( 'type' => 'textfield', 'heading' => esc_html__( 'Columns', 'js_composer' ), 'value' => 4, 'save_always' => true, 'param_name' => 'columns', 'description' => esc_html__( 'How much columns grid', 'js_composer' ), ), array( 'type' => 'dropdown', 'heading' => esc_html__( 'Order by', 'js_composer' ), 'param_name' => 'orderby', 'value' => $order_by_values, 'std' => 'menu_order title', // Default WC value 'save_always' => true, 'description' => sprintf( esc_html__( 'Select how to sort retrieved products. More at %s.', 'js_composer' ), '<a href="s://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>' ), ), array( 'type' => 'dropdown', 'heading' => esc_html__( 'Sort order', 'js_composer' ), 'param_name' => 'order', 'value' => $order_way_values, 'std' => 'ASC', // default WC value 'save_always' => true, 'description' => sprintf( esc_html__( 'Designates the ascending or descending order. More at %s.', 'js_composer' ), '<a href="https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>' ), ), array( 'type' => 'dropdown', 'heading' => esc_html__( 'Category', 'js_composer' ), 'value' => $product_categories_dropdown, 'param_name' => 'category', 'save_always' => true, 'description' => esc_html__( 'Product category list', 'js_composer' ), ), ), ); break; case 'product_categories': $settings = array( 'name' => esc_html__( 'Product categories', 'js_composer' ), 'base' => 'product_categories', 'icon' => 'icon-wpb-woocommerce', 'category' => esc_html__( 'WooCommerce', 'js_composer' ), 'description' => esc_html__( 'Display product categories loop', 'js_composer' ), 'params' => array( array( 'type' => 'textfield', 'heading' => esc_html__( 'Number', 'js_composer' ), 'param_name' => 'number', 'description' => esc_html__( 'The `number` field is used to display the number of products.', 'js_composer' ), ), array( 'type' => 'dropdown', 'heading' => esc_html__( 'Order by', 'js_composer' ), 'param_name' => 'orderby', 'value' => $order_by_values, 'std' => 'name', // default WC value 'save_always' => true, 'description' => sprintf( esc_html__( 'Select how to sort retrieved products. More at %s.', 'js_composer' ), '<a href="https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>' ), ), array( 'type' => 'dropdown', 'heading' => esc_html__( 'Sort order', 'js_composer' ), 'param_name' => 'order', 'value' => $order_way_values, 'std' => 'ASC', // default WC value 'save_always' => true, 'description' => sprintf( esc_html__( 'Designates the ascending or descending order. More at %s.', 'js_composer' ), '<a href="https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>' ), ), array( 'type' => 'textfield', 'heading' => esc_html__( 'Columns', 'js_composer' ), 'value' => 4, 'param_name' => 'columns', 'save_always' => true, 'description' => esc_html__( 'How much columns grid', 'js_composer' ), ), array( 'type' => 'textfield', 'heading' => esc_html__( 'Number', 'js_composer' ), 'param_name' => 'hide_empty', 'description' => esc_html__( 'Hide empty', 'js_composer' ), ), array( 'type' => 'autocomplete', 'heading' => esc_html__( 'Categories', 'js_composer' ), 'param_name' => 'ids', 'settings' => array( 'multiple' => true, 'sortable' => true, ), 'save_always' => true, 'description' => esc_html__( 'List of product categories', 'js_composer' ), ), ), ); break; case 'sale_products': /** * @shortcode sale_products * @description List all products on sale. * * @param per_page integer * @param columns integer * @param orderby array * @param order array */ $settings = array( 'name' => esc_html__( 'Sale products', 'js_composer' ), 'base' => 'sale_products', 'icon' => 'icon-wpb-woocommerce', 'category' => esc_html__( 'WooCommerce', 'js_composer' ), 'description' => esc_html__( 'List all products on sale', 'js_composer' ), 'params' => array( array( 'type' => 'textfield', 'heading' => esc_html__( 'Per page', 'js_composer' ), 'value' => 12, 'save_always' => true, 'param_name' => 'per_page', 'description' => esc_html__( 'How much items per page to show', 'js_composer' ), ), array( 'type' => 'textfield', 'heading' => esc_html__( 'Columns', 'js_composer' ), 'value' => 4, 'save_always' => true, 'param_name' => 'columns', 'description' => esc_html__( 'How much columns grid', 'js_composer' ), ), array( 'type' => 'dropdown', 'heading' => esc_html__( 'Order by', 'js_composer' ), 'param_name' => 'orderby', 'value' => $order_by_values, 'std' => 'title', // default WC value 'save_always' => true, 'description' => sprintf( esc_html__( 'Select how to sort retrieved products. More at %s.', 'js_composer' ), '<a href="https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>' ), ), array( 'type' => 'dropdown', 'heading' => esc_html__( 'Sort order', 'js_composer' ), 'param_name' => 'order', 'value' => $order_way_values, 'std' => 'ASC', // default WC value 'save_always' => true, 'description' => sprintf( esc_html__( 'Designates the ascending or descending order. More at %s.', 'js_composer' ), '<a href="https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>' ), ), ), ); break; case 'best_selling_products': /** * @shortcode best_selling_products * @description List best selling products on sale. * * @param per_page integer * @param columns integer */ $settings = array( 'name' => esc_html__( 'Best Selling Products', 'js_composer' ), 'base' => 'best_selling_products', 'icon' => 'icon-wpb-woocommerce', 'category' => esc_html__( 'WooCommerce', 'js_composer' ), 'description' => esc_html__( 'List best selling products on sale', 'js_composer' ), 'params' => array( array( 'type' => 'textfield', 'heading' => esc_html__( 'Per page', 'js_composer' ), 'value' => 12, 'param_name' => 'per_page', 'save_always' => true, 'description' => esc_html__( 'How much items per page to show', 'js_composer' ), ), array( 'type' => 'textfield', 'heading' => esc_html__( 'Columns', 'js_composer' ), 'value' => 4, 'param_name' => 'columns', 'save_always' => true, 'description' => esc_html__( 'How much columns grid', 'js_composer' ), ), ), ); break; case 'top_rated_products': /** * @shortcode top_rated_products * @description List top rated products on sale. * * @param per_page integer * @param columns integer * @param orderby array * @param order array */ $settings = array( 'name' => esc_html__( 'Top Rated Products', 'js_composer' ), 'base' => 'top_rated_products', 'icon' => 'icon-wpb-woocommerce', 'category' => esc_html__( 'WooCommerce', 'js_composer' ), 'description' => esc_html__( 'List all products on sale', 'js_composer' ), 'params' => array( array( 'type' => 'textfield', 'heading' => esc_html__( 'Per page', 'js_composer' ), 'value' => 12, 'param_name' => 'per_page', 'save_always' => true, 'description' => esc_html__( 'How much items per page to show', 'js_composer' ), ), array( 'type' => 'textfield', 'heading' => esc_html__( 'Columns', 'js_composer' ), 'value' => 4, 'param_name' => 'columns', 'save_always' => true, 'description' => esc_html__( 'How much columns grid', 'js_composer' ), ), array( 'type' => 'dropdown', 'heading' => esc_html__( 'Order by', 'js_composer' ), 'param_name' => 'orderby', 'value' => $order_by_values, 'std' => 'title', // default WC value 'save_always' => true, 'description' => sprintf( esc_html__( 'Select how to sort retrieved products. More at %s.', 'js_composer' ), '<a href="https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>' ), ), array( 'type' => 'dropdown', 'heading' => esc_html__( 'Sort order', 'js_composer' ), 'param_name' => 'order', 'value' => $order_way_values, 'std' => 'ASC', // Default WP Value 'save_always' => true, 'description' => sprintf( esc_html__( 'Designates the ascending or descending order. More at %s.', 'js_composer' ), '<a href="https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>' ), ), ), ); break; case 'product_attribute': /** * @shortcode product_attribute * @description List products with an attribute shortcode. * * @param per_page integer * @param columns integer * @param orderby array * @param order array * @param attribute string * @param filter string */ $attributes_tax = wc_get_attribute_taxonomies(); $attributes = array(); foreach ( $attributes_tax as $attribute ) { $attributes[ $attribute->attribute_label ] = $attribute->attribute_name; } $settings = array( 'name' => esc_html__( 'Product Attribute', 'js_composer' ), 'base' => 'product_attribute', 'icon' => 'icon-wpb-woocommerce', 'category' => esc_html__( 'WooCommerce', 'js_composer' ), 'description' => esc_html__( 'List products with an attribute shortcode', 'js_composer' ), 'params' => array( array( 'type' => 'textfield', 'heading' => esc_html__( 'Per page', 'js_composer' ), 'value' => 12, 'param_name' => 'per_page', 'save_always' => true, 'description' => esc_html__( 'How much items per page to show', 'js_composer' ), ), array( 'type' => 'textfield', 'heading' => esc_html__( 'Columns', 'js_composer' ), 'value' => 4, 'param_name' => 'columns', 'save_always' => true, 'description' => esc_html__( 'How much columns grid', 'js_composer' ), ), array( 'type' => 'dropdown', 'heading' => esc_html__( 'Order by', 'js_composer' ), 'param_name' => 'orderby', 'value' => $order_by_values, 'std' => 'title', // default WC value 'save_always' => true, 'description' => sprintf( esc_html__( 'Select how to sort retrieved products. More at %s.', 'js_composer' ), '<a href="https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>' ), ), array( 'type' => 'dropdown', 'heading' => esc_html__( 'Sort order', 'js_composer' ), 'param_name' => 'order', 'value' => $order_way_values, 'std' => 'ASC', // Default WC value 'save_always' => true, 'description' => sprintf( esc_html__( 'Designates the ascending or descending order. More at %s.', 'js_composer' ), '<a href="https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>' ), ), array( 'type' => 'dropdown', 'heading' => esc_html__( 'Attribute', 'js_composer' ), 'param_name' => 'attribute', 'value' => $attributes, 'save_always' => true, 'description' => esc_html__( 'List of product taxonomy attribute', 'js_composer' ), ), array( 'type' => 'checkbox', 'heading' => esc_html__( 'Filter', 'js_composer' ), 'param_name' => 'filter', 'value' => array( 'empty' => 'empty' ), 'save_always' => true, 'description' => esc_html__( 'Taxonomy values', 'js_composer' ), 'dependency' => array( 'callback' => 'vcWoocommerceProductAttributeFilterDependencyCallback', ), ), ), ); break; case 'related_products': /** * @shortcode related_products * @description List related products. * * @param per_page integer * @param columns integer * @param orderby array * @param order array */ /* we need to detect post type to show this shortcode */ global $post, $typenow, $current_screen; $post_type = ''; if ( $post && $post->post_type ) { //we have a post so we can just get the post type from that $post_type = $post->post_type; } elseif ( $typenow ) { //check the global $typenow - set in admin.php $post_type = $typenow; } elseif ( $current_screen && $current_screen->post_type ) { //check the global $current_screen object - set in sceen.php $post_type = $current_screen->post_type; } elseif ( isset( $_REQUEST['post_type'] ) ) { //lastly check the post_type querystring $post_type = sanitize_key( $_REQUEST['post_type'] ); //we do not know the post type! } $settings = array( 'name' => esc_html__( 'Related Products', 'js_composer' ), 'base' => 'related_products', 'icon' => 'icon-wpb-woocommerce', 'content_element' => 'product' === $post_type, // disable showing if not product type 'category' => esc_html__( 'WooCommerce', 'js_composer' ), 'description' => esc_html__( 'List related products', 'js_composer' ), 'params' => array( array( 'type' => 'textfield', 'heading' => esc_html__( 'Per page', 'js_composer' ), 'value' => 12, 'save_always' => true, 'param_name' => 'per_page', 'description' => esc_html__( 'Please note: the "per_page" shortcode argument will determine how many products are shown on a page. This will not add pagination to the shortcode. ', 'js_composer' ), ), array( 'type' => 'textfield', 'heading' => esc_html__( 'Columns', 'js_composer' ), 'value' => 4, 'save_always' => true, 'param_name' => 'columns', 'description' => esc_html__( 'How much columns grid', 'js_composer' ), ), array( 'type' => 'dropdown', 'heading' => esc_html__( 'Order by', 'js_composer' ), 'param_name' => 'orderby', 'value' => $order_by_values, 'std' => 'rand', // default WC value 'save_always' => true, 'description' => sprintf( esc_html__( 'Select how to sort retrieved products. More at %s.', 'js_composer' ), '<a href="https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>' ), ), array( 'type' => 'dropdown', 'heading' => esc_html__( 'Sort order', 'js_composer' ), 'param_name' => 'order', 'value' => $order_way_values, 'std' => 'DESC', // Default WC value 'save_always' => true, 'description' => sprintf( esc_html__( 'Designates the ascending or descending order. More at %s.', 'js_composer' ), '<a href="https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>' ), ), ), ); break; } return $settings; } /** * Add woocommerce shortcodes and hooks/filters for it. * @since 4.4 */ public function mapShortcodes() { add_action( 'wp_ajax_vc_woocommerce_get_attribute_terms', array( $this, 'getAttributeTermsAjax', ) ); $tags = array( 'woocommerce_cart', 'woocommerce_checkout', 'woocommerce_order_tracking', 'woocommerce_my_account', 'recent_products', 'featured_products', 'product', 'products', 'add_to_cart', 'add_to_cart_url', 'product_page', 'product_category', 'product_categories', 'sale_products', 'best_selling_products', 'top_rated_products', 'product_attribute', 'related_products', ); while ( $tag = current( $tags ) ) { vc_lean_map( $tag, array( $this, 'addShortcodeSettings', ) ); next( $tags ); } //Filters For autocomplete param: //For suggestion: vc_autocomplete_[shortcode_name]_[param_name]_callback add_filter( 'vc_autocomplete_product_id_callback', array( $this, 'productIdAutocompleteSuggester', ), 10, 1 ); // Get suggestion(find). Must return an array add_filter( 'vc_autocomplete_product_id_render', array( $this, 'productIdAutocompleteRender', ), 10, 1 ); // Render exact product. Must return an array (label,value) //For param: ID default value filter add_filter( 'vc_form_fields_render_field_product_id_param_value', array( $this, 'productIdDefaultValue', ), 10, 4 ); // Defines default value for param if not provided. Takes from other param value. //Filters For autocomplete param: //For suggestion: vc_autocomplete_[shortcode_name]_[param_name]_callback add_filter( 'vc_autocomplete_products_ids_callback', array( $this, 'productIdAutocompleteSuggester', ), 10, 1 ); // Get suggestion(find). Must return an array add_filter( 'vc_autocomplete_products_ids_render', array( $this, 'productIdAutocompleteRender', ), 10, 1 ); // Render exact product. Must return an array (label,value) //For param: ID default value filter add_filter( 'vc_form_fields_render_field_products_ids_param_value', array( $this, 'productsIdsDefaultValue', ), 10, 4 ); // Defines default value for param if not provided. Takes from other param value. //Filters For autocomplete param: Exactly Same as "product" shortcode //For suggestion: vc_autocomplete_[shortcode_name]_[param_name]_callback add_filter( 'vc_autocomplete_add_to_cart_id_callback', array( $this, 'productIdAutocompleteSuggester', ), 10, 1 ); // Get suggestion(find). Must return an array add_filter( 'vc_autocomplete_add_to_cart_id_render', array( $this, 'productIdAutocompleteRender', ), 10, 1 ); // Render exact product. Must return an array (label,value) //For param: ID default value filter add_filter( 'vc_form_fields_render_field_add_to_cart_id_param_value', array( $this, 'productIdDefaultValue', ), 10, 4 ); // Defines default value for param if not provided. Takes from other param value. //Filters For autocomplete param: Exactly Same as "product" shortcode //For suggestion: vc_autocomplete_[shortcode_name]_[param_name]_callback add_filter( 'vc_autocomplete_add_to_cart_url_id_callback', array( $this, 'productIdAutocompleteSuggester', ), 10, 1 ); // Get suggestion(find). Must return an array add_filter( 'vc_autocomplete_add_to_cart_url_id_render', array( $this, 'productIdAutocompleteRender', ), 10, 1 ); // Render exact product. Must return an array (label,value) //For param: ID default value filter add_filter( 'vc_form_fields_render_field_add_to_cart_url_id_param_value', array( $this, 'productIdDefaultValue', ), 10, 4 ); // Defines default value for param if not provided. Takes from other param value. //Filters For autocomplete param: Exactly Same as "product" shortcode //For suggestion: vc_autocomplete_[shortcode_name]_[param_name]_callback add_filter( 'vc_autocomplete_product_page_id_callback', array( $this, 'productIdAutocompleteSuggester', ), 10, 1 ); // Get suggestion(find). Must return an array add_filter( 'vc_autocomplete_product_page_id_render', array( $this, 'productIdAutocompleteRender', ), 10, 1 ); // Render exact product. Must return an array (label,value) //For param: ID default value filter add_filter( 'vc_form_fields_render_field_product_page_id_param_value', array( $this, 'productIdDefaultValue', ), 10, 4 ); // Defines default value for param if not provided. Takes from other param value. //Filters For autocomplete param: //For suggestion: vc_autocomplete_[shortcode_name]_[param_name]_callback add_filter( 'vc_autocomplete_product_category_category_callback', array( $this, 'productCategoryCategoryAutocompleteSuggesterBySlug', ), 10, 1 ); // Get suggestion(find). Must return an array add_filter( 'vc_autocomplete_product_category_category_render', array( $this, 'productCategoryCategoryRenderBySlugExact', ), 10, 1 ); // Render exact category by Slug. Must return an array (label,value) //Filters For autocomplete param: //For suggestion: vc_autocomplete_[shortcode_name]_[param_name]_callback add_filter( 'vc_autocomplete_product_categories_ids_callback', array( $this, 'productCategoryCategoryAutocompleteSuggester', ), 10, 1 ); // Get suggestion(find). Must return an array add_filter( 'vc_autocomplete_product_categories_ids_render', array( $this, 'productCategoryCategoryRenderByIdExact', ), 10, 1 ); // Render exact category by id. Must return an array (label,value) //For param: "filter" param value //vc_form_fields_render_field_{shortcode_name}_{param_name}_param add_filter( 'vc_form_fields_render_field_product_attribute_filter_param', array( $this, 'productAttributeFilterParamValue', ), 10, 4 ); // Defines default value for param if not provided. Takes from other param value. } /** * @param array $shortcodes * @return array|mixed */ /** * @param array $shortcodes * @return array|mixed */ public function mapGridItemShortcodes( array $shortcodes ) { require_once vc_path_dir( 'VENDORS_DIR', 'plugins/woocommerce/class-vc-gitem-woocommerce-shortcode.php' ); require_once vc_path_dir( 'VENDORS_DIR', 'plugins/woocommerce/grid-item-attributes.php' ); $wc_shortcodes = include vc_path_dir( 'VENDORS_DIR', 'plugins/woocommerce/grid-item-shortcodes.php' ); return $shortcodes + $wc_shortcodes; } /** * Defines default value for param if not provided. Takes from other param value. * @param array $param_settings * @param $current_value * @param $map_settings * @param $atts * * @return array * @since 4.4 * */ public function productAttributeFilterParamValue( $param_settings, $current_value, $map_settings, $atts ) { if ( isset( $atts['attribute'] ) ) { $value = $this->getAttributeTerms( $atts['attribute'] ); if ( is_array( $value ) && ! empty( $value ) ) { $param_settings['value'] = $value; } } return $param_settings; } /** * Get attribute terms hooks from ajax request * @since 4.4 */ public function getAttributeTermsAjax() { vc_user_access()->checkAdminNonce()->validateDie()->wpAny( 'edit_posts', 'edit_pages' )->validateDie(); $attribute = vc_post_param( 'attribute' ); $values = $this->getAttributeTerms( $attribute ); $param = array( 'param_name' => 'filter', 'type' => 'checkbox', ); $param_line = ''; foreach ( $values as $label => $v ) { $param_line .= ' <label class="vc_checkbox-label"><input id="' . $param['param_name'] . '-' . $v . '" value="' . $v . '" class="wpb_vc_param_value ' . $param['param_name'] . ' ' . $param['type'] . '" type="checkbox" name="' . $param['param_name'] . '"' . '> ' . $label . '</label>'; } die( wp_json_encode( $param_line ) ); } /** * Get attribute terms suggester * @param $attribute * * @return array * @since 4.4 * */ public function getAttributeTerms( $attribute ) { $terms = get_terms( 'pa_' . $attribute ); // return array. take slug $data = array(); if ( ! empty( $terms ) && empty( $terms->errors ) ) { foreach ( $terms as $term ) { $data[ $term->name ] = $term->slug; } } return $data; } /** * Get lists of categories. * @param $parent_id * @param array $array * @param $level * @param array $dropdown - passed by reference * @return array * @since 4.5.3 * */ protected function getCategoryChildsFull( $parent_id, $array, $level, &$dropdown ) { $keys = array_keys( $array ); $i = 0; while ( $i < count( $array ) ) { $key = $keys[ $i ]; $item = $array[ $key ]; $i ++; if ( $item->category_parent == $parent_id ) { $name = str_repeat( '- ', $level ) . $item->name; $value = $item->slug; $dropdown[] = array( 'label' => $name . '(' . $item->term_id . ')', 'value' => $value, ); unset( $array[ $key ] ); $array = $this->getCategoryChildsFull( $item->term_id, $array, $level + 1, $dropdown ); $keys = array_keys( $array ); $i = 0; } } return $array; } /** * Replace single product sku to id. * @param $current_value * @param $param_settings * @param $map_settings * @param $atts * * @return bool|string * @since 4.4 * */ public function productIdDefaultValue( $current_value, $param_settings, $map_settings, $atts ) { $value = trim( $current_value ); if ( strlen( trim( $current_value ) ) === 0 && isset( $atts['sku'] ) && strlen( $atts['sku'] ) > 0 ) { $value = $this->productIdDefaultValueFromSkuToId( $atts['sku'] ); } return $value; } /** * Replaces product skus to id's. * @param $current_value * @param $param_settings * @param $map_settings * @param $atts * * @return string * @since 4.4 * */ public function productsIdsDefaultValue( $current_value, $param_settings, $map_settings, $atts ) { $value = trim( $current_value ); if ( strlen( trim( $value ) ) === 0 && isset( $atts['skus'] ) && strlen( $atts['skus'] ) > 0 ) { $data = array(); $skus = $atts['skus']; $skus_array = explode( ',', $skus ); foreach ( $skus_array as $sku ) { $id = $this->productIdDefaultValueFromSkuToId( trim( $sku ) ); if ( is_numeric( $id ) ) { $data[] = $id; } } if ( ! empty( $data ) ) { $values = explode( ',', $value ); $values = array_merge( $values, $data ); $value = implode( ',', $values ); } } return $value; } /** * Suggester for autocomplete by id/name/title/sku * @param $query * * @return array - id's from products with title/sku. * @since 4.4 * */ public function productIdAutocompleteSuggester( $query ) { global $wpdb; $product_id = (int) $query; $post_meta_infos = $wpdb->get_results( $wpdb->prepare( "SELECT a.ID AS id, a.post_title AS title, b.meta_value AS sku FROM {$wpdb->posts} AS a LEFT JOIN ( SELECT meta_value, post_id FROM {$wpdb->postmeta} WHERE `meta_key` = '_sku' ) AS b ON b.post_id = a.ID WHERE a.post_type = 'product' AND ( a.ID = '%d' OR b.meta_value LIKE '%%%s%%' OR a.post_title LIKE '%%%s%%' )", $product_id > 0 ? $product_id : - 1, stripslashes( $query ), stripslashes( $query ) ), ARRAY_A ); $results = array(); if ( is_array( $post_meta_infos ) && ! empty( $post_meta_infos ) ) { foreach ( $post_meta_infos as $value ) { $data = array(); $data['value'] = $value['id']; $data['label'] = esc_html__( 'Id', 'js_composer' ) . ': ' . $value['id'] . ( ( strlen( $value['title'] ) > 0 ) ? ' - ' . esc_html__( 'Title', 'js_composer' ) . ': ' . $value['title'] : '' ) . ( ( strlen( $value['sku'] ) > 0 ) ? ' - ' . esc_html__( 'Sku', 'js_composer' ) . ': ' . $value['sku'] : '' ); $results[] = $data; } } return $results; } /** * Find product by id * @param $query * * @return bool|array * @since 4.4 * */ public function productIdAutocompleteRender( $query ) { $query = trim( $query['value'] ); // get value from requested if ( ! empty( $query ) ) { // get product $product_object = wc_get_product( (int) $query ); if ( is_object( $product_object ) ) { $product_sku = $product_object->get_sku(); $product_title = $product_object->get_title(); $product_id = $product_object->get_id(); $product_sku_display = ''; if ( ! empty( $product_sku ) ) { $product_sku_display = ' - ' . esc_html__( 'Sku', 'js_composer' ) . ': ' . $product_sku; } $product_title_display = ''; if ( ! empty( $product_title ) ) { $product_title_display = ' - ' . esc_html__( 'Title', 'js_composer' ) . ': ' . $product_title; } $product_id_display = esc_html__( 'Id', 'js_composer' ) . ': ' . $product_id; $data = array(); $data['value'] = $product_id; $data['label'] = $product_id_display . $product_title_display . $product_sku_display; return ! empty( $data ) ? $data : false; } return false; } return false; } /** * Return ID of product by provided SKU of product. * @param $query * * @return bool * @since 4.4 * */ public function productIdDefaultValueFromSkuToId( $query ) { $result = $this->productIdAutocompleteSuggesterExactSku( $query ); return isset( $result['value'] ) ? $result['value'] : false; } /** * Find product by SKU * @param $query * * @return bool|array * @since 4.4 * */ public function productIdAutocompleteSuggesterExactSku( $query ) { global $wpdb; $query = trim( $query ); $product_id = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key='_sku' AND meta_value='%s' LIMIT 1", stripslashes( $query ) ) ); $product_data = get_post( $product_id ); if ( 'product' !== $product_data->post_type ) { return ''; } $product_object = wc_get_product( $product_data ); if ( is_object( $product_object ) ) { $product_sku = $product_object->get_sku(); $product_title = $product_object->get_title(); $product_id = $product_object->get_id(); $product_sku_display = ''; if ( ! empty( $product_sku ) ) { $product_sku_display = ' - ' . esc_html__( 'Sku', 'js_composer' ) . ': ' . $product_sku; } $product_title_display = ''; if ( ! empty( $product_title ) ) { $product_title_display = ' - ' . esc_html__( 'Title', 'js_composer' ) . ': ' . $product_title; } $product_id_display = esc_html__( 'Id', 'js_composer' ) . ': ' . $product_id; $data = array(); $data['value'] = $product_id; $data['label'] = $product_id_display . $product_title_display . $product_sku_display; return ! empty( $data ) ? $data : false; } return false; } /** * Autocomplete suggester to search product category by name/slug or id. * @param $query * @param bool $slug - determines what output is needed * default false - return id of product category * true - return slug of product category * * @return array * @since 4.4 * */ public function productCategoryCategoryAutocompleteSuggester( $query, $slug = false ) { global $wpdb; $cat_id = (int) $query; $query = trim( $query ); $post_meta_infos = $wpdb->get_results( $wpdb->prepare( "SELECT a.term_id AS id, b.name as name, b.slug AS slug FROM {$wpdb->term_taxonomy} AS a INNER JOIN {$wpdb->terms} AS b ON b.term_id = a.term_id WHERE a.taxonomy = 'product_cat' AND (a.term_id = '%d' OR b.slug LIKE '%%%s%%' OR b.name LIKE '%%%s%%' )", $cat_id > 0 ? $cat_id : - 1, stripslashes( $query ), stripslashes( $query ) ), ARRAY_A ); $result = array(); if ( is_array( $post_meta_infos ) && ! empty( $post_meta_infos ) ) { foreach ( $post_meta_infos as $value ) { $data = array(); $data['value'] = $slug ? $value['slug'] : $value['id']; $data['label'] = esc_html__( 'Id', 'js_composer' ) . ': ' . $value['id'] . ( ( strlen( $value['name'] ) > 0 ) ? ' - ' . esc_html__( 'Name', 'js_composer' ) . ': ' . $value['name'] : '' ) . ( ( strlen( $value['slug'] ) > 0 ) ? ' - ' . esc_html__( 'Slug', 'js_composer' ) . ': ' . $value['slug'] : '' ); $result[] = $data; } } return $result; } /** * Search product category by id * @param $query * * @return bool|array * @since 4.4 * */ public function productCategoryCategoryRenderByIdExact( $query ) { $query = $query['value']; $cat_id = (int) $query; $term = get_term( $cat_id, 'product_cat' ); return $this->productCategoryTermOutput( $term ); } /** * Suggester for autocomplete to find product category by id/name/slug but return found product category SLUG * @param $query * * @return array - slug of products categories. * @since 4.4 * */ public function productCategoryCategoryAutocompleteSuggesterBySlug( $query ) { $result = $this->productCategoryCategoryAutocompleteSuggester( $query, true ); return $result; } /** * Search product category by slug. * @param $query * * @return bool|array * @since 4.4 * */ public function productCategoryCategoryRenderBySlugExact( $query ) { $query = $query['value']; $query = trim( $query ); $term = get_term_by( 'slug', $query, 'product_cat' ); return $this->productCategoryTermOutput( $term ); } /** * Return product category value|label array * * @param $term * * @return array|bool * @since 4.4 */ protected function productCategoryTermOutput( $term ) { $term_slug = $term->slug; $term_title = $term->name; $term_id = $term->term_id; $term_slug_display = ''; if ( ! empty( $term_slug ) ) { $term_slug_display = ' - ' . esc_html__( 'Sku', 'js_composer' ) . ': ' . $term_slug; } $term_title_display = ''; if ( ! empty( $term_title ) ) { $term_title_display = ' - ' . esc_html__( 'Title', 'js_composer' ) . ': ' . $term_title; } $term_id_display = esc_html__( 'Id', 'js_composer' ) . ': ' . $term_id; $data = array(); $data['value'] = $term_id; $data['label'] = $term_id_display . $term_title_display . $term_slug_display; return ! empty( $data ) ? $data : false; } /** * @return array */ /** * @return array */ public static function getProductsFieldsList() { return array( esc_html__( 'SKU', 'js_composer' ) => 'sku', esc_html__( 'ID', 'js_composer' ) => 'id', esc_html__( 'Price', 'js_composer' ) => 'price', esc_html__( 'Regular Price', 'js_composer' ) => 'regular_price', esc_html__( 'Sale Price', 'js_composer' ) => 'sale_price', esc_html__( 'Price html', 'js_composer' ) => 'price_html', esc_html__( 'Reviews count', 'js_composer' ) => 'reviews_count', esc_html__( 'Short description', 'js_composer' ) => 'short_description', esc_html__( 'Dimensions', 'js_composer' ) => 'dimensions', esc_html__( 'Rating count', 'js_composer' ) => 'rating_count', esc_html__( 'Weight', 'js_composer' ) => 'weight', esc_html__( 'Is on sale', 'js_composer' ) => 'on_sale', esc_html__( 'Custom field', 'js_composer' ) => '_custom_', ); } /** * @param $key * @return string */ /** * @param $key * @return string */ public static function getProductFieldLabel( $key ) { if ( false === self::$product_fields_list ) { self::$product_fields_list = array_flip( self::getProductsFieldsList() ); } return isset( self::$product_fields_list[ $key ] ) ? self::$product_fields_list[ $key ] : ''; } /** * @return array */ /** * @return array */ public static function getOrderFieldsList() { return array( esc_html__( 'ID', 'js_composer' ) => 'id', esc_html__( 'Order number', 'js_composer' ) => 'order_number', esc_html__( 'Currency', 'js_composer' ) => 'order_currency', esc_html__( 'Total', 'js_composer' ) => 'total', esc_html__( 'Status', 'js_composer' ) => 'status', esc_html__( 'Payment method', 'js_composer' ) => 'payment_method', esc_html__( 'Billing address city', 'js_composer' ) => 'billing_address_city', esc_html__( 'Billing address country', 'js_composer' ) => 'billing_address_country', esc_html__( 'Shipping address city', 'js_composer' ) => 'shipping_address_city', esc_html__( 'Shipping address country', 'js_composer' ) => 'shipping_address_country', esc_html__( 'Customer Note', 'js_composer' ) => 'customer_note', esc_html__( 'Customer API', 'js_composer' ) => 'customer_api', esc_html__( 'Custom field', 'js_composer' ) => '_custom_', ); } /** * @param $key * @return string */ /** * @param $key * @return string */ public static function getOrderFieldLabel( $key ) { if ( false === self::$order_fields_list ) { self::$order_fields_list = array_flip( self::getOrderFieldsList() ); } return isset( self::$order_fields_list[ $key ] ) ? self::$order_fields_list[ $key ] : ''; } public function yoastSeoCompatibility() { if ( function_exists( 'WC' ) ) { // WC()->frontend_includes(); include_once( WC()->plugin_path() . '/includes/wc-template-functions.php' ); // include_once WC()->plugin_path() . ''; } } } /** * Removes EDIT button in backend and frontend editor * Class Vc_WooCommerce_NotEditable * @since 4.4 */ class Vc_WooCommerce_NotEditable extends WPBakeryShortCode { /** * @since 4.4 * @var array */ protected $controls_list = array( 'clone', 'delete', ); }
jujudellago/yc2016
web/app/plugins/js_composer/include/classes/vendors/plugins/class-vc-vendor-woocommerce.php
PHP
mit
55,910
using System; using System.Threading; namespace Remotus.Base.Observables { public sealed class DelegateObserver<T> : IObserver<T>, IDisposable { private readonly Action _onCompleted; private readonly Action<Exception> _onError; private readonly Action<T> _onNext; private int _isStopped; public DelegateObserver(Action<T> onNext, Action<Exception> onError = null, Action onCompleted = null) { _onNext = onNext; _onError = onError; _onCompleted = onCompleted; } public void OnNext(T value) { if (_isStopped == 0) _onNext?.Invoke(value); } public void OnError(Exception error) { if (Interlocked.Exchange(ref _isStopped, 1) == 0) _onError?.Invoke(error); } public void OnCompleted() { if (Interlocked.Exchange(ref _isStopped, 1) == 0) _onCompleted?.Invoke(); } public void Dispose() { Interlocked.Exchange(ref _isStopped, 1); } } }
LazyTarget/ProcHelper
src/Remotus.Base/Observables/DelegateObserver.cs
C#
mit
1,134
from django.conf.urls.defaults import * urlpatterns = patterns('', url(r'^$', 'topics.views.topics', name="topic_list"), url(r'^(?P<topic_id>\d+)/edit/$', 'topics.views.topic', kwargs={"edit": True}, name="topic_edit"), url(r'^(?P<topic_id>\d+)/delete/$', 'topics.views.topic_delete', name="topic_delete"), url(r'^(?P<topic_id>\d+)/$', 'topics.views.topic', name="topic_detail"), )
ericholscher/pinax
pinax/apps/topics/urls.py
Python
mit
399
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.ComponentModel.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Shared.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.SolutionCrawler; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.TaskList { internal sealed class ExternalErrorDiagnosticUpdateSource : IDiagnosticUpdateSource { private readonly Workspace _workspace; private readonly IDiagnosticAnalyzerService _diagnosticService; private readonly IGlobalOperationNotificationService _notificationService; private readonly SimpleTaskQueue _taskQueue; private readonly IAsynchronousOperationListener _listener; private readonly object _gate = new object(); private InProgressState _stateDoNotAccessDirectly = null; private ImmutableArray<DiagnosticData> _lastBuiltResult = ImmutableArray<DiagnosticData>.Empty; public ExternalErrorDiagnosticUpdateSource( VisualStudioWorkspace workspace, IDiagnosticAnalyzerService diagnosticService, IDiagnosticUpdateSourceRegistrationService registrationService, IAsynchronousOperationListenerProvider listenerProvider) : this(workspace, diagnosticService, listenerProvider.GetListener(FeatureAttribute.ErrorList)) { registrationService.Register(this); } /// <summary> /// internal for testing /// </summary> internal ExternalErrorDiagnosticUpdateSource( Workspace workspace, IDiagnosticAnalyzerService diagnosticService, IAsynchronousOperationListener listener) { // use queue to serialize work. no lock needed _taskQueue = new SimpleTaskQueue(TaskScheduler.Default); _listener = listener; _workspace = workspace; _workspace.WorkspaceChanged += OnWorkspaceChanged; _diagnosticService = diagnosticService; _notificationService = _workspace.Services.GetService<IGlobalOperationNotificationService>(); } public event EventHandler<BuildProgress> BuildProgressChanged; public event EventHandler<DiagnosticsUpdatedArgs> DiagnosticsUpdated; public event EventHandler DiagnosticsCleared { add { } remove { } } public bool IsInProgress => BuildInprogressState != null; public ImmutableArray<DiagnosticData> GetBuildErrors() { return _lastBuiltResult; } public bool IsSupportedDiagnosticId(ProjectId projectId, string id) { return BuildInprogressState?.IsSupportedDiagnosticId(projectId, id) ?? false; } public void ClearErrors(ProjectId projectId) { // capture state if it exists var state = BuildInprogressState; var asyncToken = _listener.BeginAsyncOperation("ClearErrors"); _taskQueue.ScheduleTask(() => { // this will get called if the project is actually built by "build" command. // we track what project has been built, so that later we can clear any stale live errors // if build give us no errors for this project state?.Built(projectId); ClearProjectErrors(state?.Solution ?? _workspace.CurrentSolution, projectId); }).CompletesAsyncOperation(asyncToken); } private void OnWorkspaceChanged(object sender, WorkspaceChangeEventArgs e) { switch (e.Kind) { case WorkspaceChangeKind.SolutionAdded: case WorkspaceChangeKind.SolutionRemoved: case WorkspaceChangeKind.SolutionCleared: case WorkspaceChangeKind.SolutionReloaded: { var asyncToken = _listener.BeginAsyncOperation("OnSolutionChanged"); _taskQueue.ScheduleTask(() => e.OldSolution.ProjectIds.Do(p => ClearProjectErrors(e.OldSolution, p))).CompletesAsyncOperation(asyncToken); break; } case WorkspaceChangeKind.ProjectRemoved: case WorkspaceChangeKind.ProjectReloaded: { var asyncToken = _listener.BeginAsyncOperation("OnProjectChanged"); _taskQueue.ScheduleTask(() => ClearProjectErrors(e.OldSolution, e.ProjectId)).CompletesAsyncOperation(asyncToken); break; } case WorkspaceChangeKind.DocumentRemoved: case WorkspaceChangeKind.DocumentReloaded: { var asyncToken = _listener.BeginAsyncOperation("OnDocumentRemoved"); _taskQueue.ScheduleTask(() => ClearDocumentErrors(e.OldSolution, e.ProjectId, e.DocumentId)).CompletesAsyncOperation(asyncToken); break; } case WorkspaceChangeKind.ProjectAdded: case WorkspaceChangeKind.DocumentAdded: case WorkspaceChangeKind.DocumentChanged: case WorkspaceChangeKind.ProjectChanged: case WorkspaceChangeKind.SolutionChanged: case WorkspaceChangeKind.AdditionalDocumentAdded: case WorkspaceChangeKind.AdditionalDocumentRemoved: case WorkspaceChangeKind.AdditionalDocumentReloaded: case WorkspaceChangeKind.AdditionalDocumentChanged: case WorkspaceChangeKind.AnalyzerConfigDocumentAdded: case WorkspaceChangeKind.AnalyzerConfigDocumentRemoved: case WorkspaceChangeKind.AnalyzerConfigDocumentChanged: case WorkspaceChangeKind.AnalyzerConfigDocumentReloaded: break; default: Contract.Fail("Unknown workspace events"); break; } } internal void OnSolutionBuildStarted() { // build just started, create the state and fire build in progress event. // build just started, create the state and fire build in progress event. _ = GetOrCreateInProgressState(); } internal void OnSolutionBuildCompleted() { // building is done. reset the state // and get local copy of in-progress state var inProgressState = ClearInProgressState(); // enqueue build/live sync in the queue. var asyncToken = _listener.BeginAsyncOperation("OnSolutionBuild"); _taskQueue.ScheduleTask(async () => { // nothing to do if (inProgressState == null) { return; } // explicitly start solution crawler if it didn't start yet. since solution crawler is lazy, // user might have built solution before workspace fires its first event yet (which is when solution crawler is initialized) // here we give initializeLazily: false so that solution crawler is fully initialized when we do de-dup live and build errors, // otherwise, we will think none of error we have here belong to live errors since diagnostic service is not initialized yet. var registrationService = (SolutionCrawlerRegistrationService)_workspace.Services.GetService<ISolutionCrawlerRegistrationService>(); registrationService.EnsureRegistration(_workspace, initializeLazily: false); _lastBuiltResult = inProgressState.GetBuildDiagnostics(); // we are about to update live analyzer data using one from build. // pause live analyzer using var operation = _notificationService.Start("BuildDone"); if (_diagnosticService is DiagnosticAnalyzerService diagnosticService) { await CleanupAllLiveErrorsAsync(diagnosticService, inProgressState.GetProjectsWithoutErrors()).ConfigureAwait(false); await SyncBuildErrorsAndReportAsync(diagnosticService, inProgressState).ConfigureAwait(false); } inProgressState.Done(); }).CompletesAsyncOperation(asyncToken); } private Task CleanupAllLiveErrorsAsync(DiagnosticAnalyzerService diagnosticService, IEnumerable<ProjectId> projects) { var map = projects.ToImmutableDictionary(p => p, _ => ImmutableArray<DiagnosticData>.Empty); return diagnosticService.SynchronizeWithBuildAsync(_workspace, map); } private async Task SyncBuildErrorsAndReportAsync(DiagnosticAnalyzerService diagnosticService, InProgressState inProgressState) { var solution = inProgressState.Solution; var map = await inProgressState.GetLiveDiagnosticsPerProjectAsync().ConfigureAwait(false); // make those errors live errors await diagnosticService.SynchronizeWithBuildAsync(_workspace, map).ConfigureAwait(false); // raise events for ones left-out var buildErrors = GetBuildErrors().Except(map.Values.SelectMany(v => v)).GroupBy(k => k.DocumentId); foreach (var group in buildErrors) { if (group.Key == null) { foreach (var projectGroup in group.GroupBy(g => g.ProjectId)) { Contract.ThrowIfNull(projectGroup.Key); ReportBuildErrors(projectGroup.Key, solution, projectGroup.ToImmutableArray()); } continue; } ReportBuildErrors(group.Key, solution, group.ToImmutableArray()); } } private void ReportBuildErrors<T>(T item, Solution solution, ImmutableArray<DiagnosticData> buildErrors) { if (item is ProjectId projectId) { RaiseDiagnosticsCreated(projectId, solution, projectId, null, buildErrors); return; } // must be not null var documentId = item as DocumentId; RaiseDiagnosticsCreated(documentId, solution, documentId.ProjectId, documentId, buildErrors); } private void ClearProjectErrors(Solution solution, ProjectId projectId) { // remove all project errors RaiseDiagnosticsRemoved(projectId, solution, projectId, documentId: null); var project = solution.GetProject(projectId); if (project == null) { return; } // remove all document errors foreach (var documentId in project.DocumentIds) { ClearDocumentErrors(solution, projectId, documentId); } } private void ClearDocumentErrors(Solution solution, ProjectId projectId, DocumentId documentId) { RaiseDiagnosticsRemoved(documentId, solution, projectId, documentId); } public void AddNewErrors(ProjectId projectId, DiagnosticData diagnostic) { // capture state that will be processed in background thread. var state = GetOrCreateInProgressState(); var asyncToken = _listener.BeginAsyncOperation("Project New Errors"); _taskQueue.ScheduleTask(() => { state.AddError(projectId, diagnostic); }).CompletesAsyncOperation(asyncToken); } public void AddNewErrors(DocumentId documentId, DiagnosticData diagnostic) { // capture state that will be processed in background thread. var state = GetOrCreateInProgressState(); var asyncToken = _listener.BeginAsyncOperation("Document New Errors"); _taskQueue.ScheduleTask(() => { state.AddError(documentId, diagnostic); }).CompletesAsyncOperation(asyncToken); } public void AddNewErrors( ProjectId projectId, HashSet<DiagnosticData> projectErrors, Dictionary<DocumentId, HashSet<DiagnosticData>> documentErrorMap) { // capture state that will be processed in background thread var state = GetOrCreateInProgressState(); var asyncToken = _listener.BeginAsyncOperation("Project New Errors"); _taskQueue.ScheduleTask(() => { foreach (var kv in documentErrorMap) { state.AddErrors(kv.Key, kv.Value); } state.AddErrors(projectId, projectErrors); }).CompletesAsyncOperation(asyncToken); } private InProgressState BuildInprogressState { get { lock (_gate) { return _stateDoNotAccessDirectly; } } } private InProgressState ClearInProgressState() { lock (_gate) { var state = _stateDoNotAccessDirectly; _stateDoNotAccessDirectly = null; return state; } } private InProgressState GetOrCreateInProgressState() { lock (_gate) { if (_stateDoNotAccessDirectly == null) { // here, we take current snapshot of solution when the state is first created. and through out this code, we use this snapshot. // since we have no idea what actual snapshot of solution the out of proc build has picked up, it doesn't remove the race we can have // between build and diagnostic service, but this at least make us to consistent inside of our code. _stateDoNotAccessDirectly = new InProgressState(this, _workspace.CurrentSolution); } return _stateDoNotAccessDirectly; } } private void RaiseDiagnosticsCreated(object id, Solution solution, ProjectId projectId, DocumentId documentId, ImmutableArray<DiagnosticData> items) { DiagnosticsUpdated?.Invoke(this, DiagnosticsUpdatedArgs.DiagnosticsCreated( CreateArgumentKey(id), _workspace, solution, projectId, documentId, items)); } private void RaiseDiagnosticsRemoved(object id, Solution solution, ProjectId projectId, DocumentId documentId) { DiagnosticsUpdated?.Invoke(this, DiagnosticsUpdatedArgs.DiagnosticsRemoved( CreateArgumentKey(id), _workspace, solution, projectId, documentId)); } private static ArgumentKey CreateArgumentKey(object id) => new ArgumentKey(id); private void RaiseBuildProgressChanged(BuildProgress progress) { BuildProgressChanged?.Invoke(this, progress); } #region not supported public bool SupportGetDiagnostics { get { return false; } } public ImmutableArray<DiagnosticData> GetDiagnostics( Workspace workspace, ProjectId projectId, DocumentId documentId, object id, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default) { return ImmutableArray<DiagnosticData>.Empty; } #endregion internal enum BuildProgress { Started, Updated, Done } private sealed class InProgressState { private int _incrementDoNotAccessDirectly = 0; private readonly ExternalErrorDiagnosticUpdateSource _owner; private readonly HashSet<ProjectId> _projectsBuilt = new HashSet<ProjectId>(); private readonly HashSet<ProjectId> _projectsWithErrors = new HashSet<ProjectId>(); private readonly Dictionary<ProjectId, ImmutableHashSet<string>> _allDiagnosticIdMap = new Dictionary<ProjectId, ImmutableHashSet<string>>(); private readonly Dictionary<ProjectId, ImmutableHashSet<string>> _liveDiagnosticIdMap = new Dictionary<ProjectId, ImmutableHashSet<string>>(); private readonly Dictionary<ProjectId, Dictionary<DiagnosticData, int>> _projectMap = new Dictionary<ProjectId, Dictionary<DiagnosticData, int>>(); private readonly Dictionary<DocumentId, Dictionary<DiagnosticData, int>> _documentMap = new Dictionary<DocumentId, Dictionary<DiagnosticData, int>>(); public InProgressState(ExternalErrorDiagnosticUpdateSource owner, Solution solution) { _owner = owner; Solution = solution; // let people know build has started _owner.RaiseBuildProgressChanged(BuildProgress.Started); } public Solution Solution { get; } public void Done() { _owner.RaiseBuildProgressChanged(BuildProgress.Done); } public bool IsSupportedDiagnosticId(ProjectId projectId, string id) { lock (_allDiagnosticIdMap) { if (_allDiagnosticIdMap.TryGetValue(projectId, out var ids)) { return ids.Contains(id); } var project = Solution.GetProject(projectId); if (project == null) { // projectId no longer exist, return false; _allDiagnosticIdMap.Add(projectId, ImmutableHashSet<string>.Empty); return false; } // set ids set var builder = ImmutableHashSet.CreateBuilder<string>(); var descriptorMap = _owner._diagnosticService.AnalyzerInfoCache.GetDiagnosticDescriptorsPerReference(project); builder.UnionWith(descriptorMap.Values.SelectMany(v => v.Select(d => d.Id))); var set = builder.ToImmutable(); _allDiagnosticIdMap.Add(projectId, set); return set.Contains(id); } } public ImmutableArray<DiagnosticData> GetBuildDiagnostics() { // return errors in the order that is reported return ImmutableArray.CreateRange( _projectMap.Values.SelectMany(d => d).Concat(_documentMap.Values.SelectMany(d => d)).OrderBy(kv => kv.Value).Select(kv => kv.Key)); } public void Built(ProjectId projectId) { _projectsBuilt.Add(projectId); } public IEnumerable<ProjectId> GetProjectsWithErrors() { // filter out project that is no longer exist in IDE // this can happen if user started a "build" and then remove a project from IDE // before build finishes return _projectsWithErrors.Where(p => Solution.GetProject(p) != null); } public IEnumerable<ProjectId> GetProjectsWithoutErrors() { return GetProjectsBuilt().Except(GetProjectsWithErrors()); IEnumerable<ProjectId> GetProjectsBuilt() { // filter out project that is no longer exist in IDE // this can happen if user started a "build" and then remove a project from IDE // before build finishes return Solution.ProjectIds.Where(p => _projectsBuilt.Contains(p)); } } public async Task<ImmutableDictionary<ProjectId, ImmutableArray<DiagnosticData>>> GetLiveDiagnosticsPerProjectAsync() { var builder = ImmutableDictionary.CreateBuilder<ProjectId, ImmutableArray<DiagnosticData>>(); foreach (var projectId in GetProjectsWithErrors()) { var project = Solution.GetProject(projectId); var compilation = project.SupportsCompilation ? await project.GetCompilationAsync(CancellationToken.None).ConfigureAwait(false) : null; var diagnostics = ImmutableArray.CreateRange( _projectMap.Where(kv => kv.Key == projectId).SelectMany(kv => kv.Value).Concat( _documentMap.Where(kv => kv.Key.ProjectId == projectId).SelectMany(kv => kv.Value)) .Select(kv => kv.Key).Where(d => IsLive(project, compilation, d))); builder.Add(projectId, diagnostics); } return builder.ToImmutable(); } public void AddErrors(DocumentId key, HashSet<DiagnosticData> diagnostics) { AddErrors(_documentMap, key, diagnostics); } public void AddErrors(ProjectId key, HashSet<DiagnosticData> diagnostics) { AddErrors(_projectMap, key, diagnostics); } public void AddError(DocumentId key, DiagnosticData diagnostic) { AddError(_documentMap, key, diagnostic); } public void AddError(ProjectId key, DiagnosticData diagnostic) { AddError(_projectMap, key, diagnostic); } private bool IsLive(Project project, Compilation compilation, DiagnosticData diagnosticData) { // REVIEW: current design is that we special case compiler analyzer case and we accept only document level // diagnostic as live. otherwise, we let them be build errors. we changed compiler analyzer accordingly as well // so that it doesn't report project level diagnostic as live errors. if (_owner._diagnosticService.AnalyzerInfoCache.IsCompilerDiagnostic(project.Language, diagnosticData) && !IsDocumentLevelDiagnostic(diagnosticData)) { // compiler error but project level error return false; } if (SupportedLiveDiagnosticId(project, compilation, diagnosticData.Id)) { return true; } return false; static bool IsDocumentLevelDiagnostic(DiagnosticData diagnoaticData) { if (diagnoaticData.DocumentId != null) { return true; } // due to mapped file such as // // A.cs having // #line 2 RandomeFile.txt // ErrorHere // #line default // // we can't simply say it is not document level diagnostic since // file path is not part of solution. build output will just tell us // mapped span not original span, so any code like above will not // part of solution. // // but also we can't simply say it is a document level error because it has file path // since project level error can have a file path pointing to a file such as dll // , pdb, embedded files and etc. // // unfortunately, there is no 100% correct way to do this. // so we will use a heuristic that will most likely work for most of common cases. return !string.IsNullOrEmpty(diagnoaticData.DataLocation.OriginalFilePath) && (diagnoaticData.DataLocation.OriginalStartLine > 0 || diagnoaticData.DataLocation.OriginalStartColumn > 0); } } private bool SupportedLiveDiagnosticId(Project project, Compilation compilation, string id) { var projectId = project.Id; lock (_liveDiagnosticIdMap) { if (_liveDiagnosticIdMap.TryGetValue(projectId, out var ids)) { return ids.Contains(id); } var fullSolutionAnalysis = SolutionCrawlerOptions.GetBackgroundAnalysisScope(project) == BackgroundAnalysisScope.FullSolution; if (!project.SupportsCompilation || fullSolutionAnalysis) { return IsSupportedDiagnosticId(project.Id, id); } // set ids set var builder = ImmutableHashSet.CreateBuilder<string>(); var diagnosticService = _owner._diagnosticService; var infoCache = diagnosticService.AnalyzerInfoCache; foreach (var analyzersPerReference in infoCache.CreateDiagnosticAnalyzersPerReference(project)) { foreach (var analyzer in analyzersPerReference.Value) { if (diagnosticService.IsCompilationEndAnalyzer(analyzer, project, compilation)) { continue; } var diagnosticIds = infoCache.GetDiagnosticDescriptors(analyzer).Select(d => d.Id); builder.UnionWith(diagnosticIds); } } var set = builder.ToImmutable(); _liveDiagnosticIdMap.Add(projectId, set); return set.Contains(id); } } private void AddErrors<T>(Dictionary<T, Dictionary<DiagnosticData, int>> map, T key, HashSet<DiagnosticData> diagnostics) { var errors = GetErrorSet(map, key); foreach (var diagnostic in diagnostics) { AddError(errors, diagnostic, key); } } private void AddError<T>(Dictionary<T, Dictionary<DiagnosticData, int>> map, T key, DiagnosticData diagnostic) { var errors = GetErrorSet(map, key); AddError(errors, diagnostic, key); } private void AddError<T>(Dictionary<DiagnosticData, int> errors, DiagnosticData diagnostic, T key) { RecordProjectContainsErrors(); // add only new errors if (!errors.TryGetValue(diagnostic, out _)) { Logger.Log(FunctionId.ExternalErrorDiagnosticUpdateSource_AddError, d => d.ToString(), diagnostic); errors.Add(diagnostic, GetNextIncrement()); } int GetNextIncrement() { return _incrementDoNotAccessDirectly++; } void RecordProjectContainsErrors() { var projectId = (key is DocumentId documentId) ? documentId.ProjectId : (ProjectId)(object)key; if (!_projectsWithErrors.Add(projectId)) { return; } // this will make build only error list to be updated per project rather than per solution. // basically this will make errors up to last project to show up in error list _owner._lastBuiltResult = GetBuildDiagnostics(); _owner.RaiseBuildProgressChanged(BuildProgress.Updated); } } private Dictionary<DiagnosticData, int> GetErrorSet<T>(Dictionary<T, Dictionary<DiagnosticData, int>> map, T key) { return map.GetOrAdd(key, _ => new Dictionary<DiagnosticData, int>(DiagnosticDataComparer.Instance)); } } private sealed class ArgumentKey : BuildToolId.Base<object> { public ArgumentKey(object key) : base(key) { } public override string BuildTool { get { return PredefinedBuildTools.Build; } } public override bool Equals(object obj) => obj is ArgumentKey && base.Equals(obj); public override int GetHashCode() { return base.GetHashCode(); } } private sealed class DiagnosticDataComparer : IEqualityComparer<DiagnosticData> { public static readonly DiagnosticDataComparer Instance = new DiagnosticDataComparer(); public bool Equals(DiagnosticData item1, DiagnosticData item2) { if ((item1.DocumentId == null) != (item2.DocumentId == null) || item1.Id != item2.Id || item1.ProjectId != item2.ProjectId || item1.Severity != item2.Severity || item1.Message != item2.Message || (item1.DataLocation?.MappedStartLine ?? 0) != (item2.DataLocation?.MappedStartLine ?? 0) || (item1.DataLocation?.MappedStartColumn ?? 0) != (item2.DataLocation?.MappedStartColumn ?? 0) || (item1.DataLocation?.OriginalStartLine ?? 0) != (item2.DataLocation?.OriginalStartLine ?? 0) || (item1.DataLocation?.OriginalStartColumn ?? 0) != (item2.DataLocation?.OriginalStartColumn ?? 0)) { return false; } return (item1.DocumentId != null) ? item1.DocumentId == item2.DocumentId : item1.DataLocation?.OriginalFilePath == item2.DataLocation?.OriginalFilePath; } public int GetHashCode(DiagnosticData obj) { var result = Hash.Combine(obj.Id, Hash.Combine(obj.Message, Hash.Combine(obj.ProjectId, Hash.Combine(obj.DataLocation?.MappedStartLine ?? 0, Hash.Combine(obj.DataLocation?.MappedStartColumn ?? 0, Hash.Combine(obj.DataLocation?.OriginalStartLine ?? 0, Hash.Combine(obj.DataLocation?.OriginalStartColumn ?? 0, (int)obj.Severity))))))); return obj.DocumentId != null ? Hash.Combine(obj.DocumentId, result) : Hash.Combine(obj.DataLocation?.OriginalFilePath?.GetHashCode() ?? 0, result); } } } }
abock/roslyn
src/VisualStudio/Core/Def/Implementation/TaskList/ExternalErrorDiagnosticUpdateSource.cs
C#
mit
31,502
package main import ( "github.com/gorilla/handlers" "github.com/gorilla/mux" "html/template" "log" "net/http" "os" ) const ( addr = "127.0.0.1:8090" ) var ( indexTemplate = template.Must(template.ParseFiles("index.html")) tasks = []Task{ Task{1, "Learn golang", true}, Task{2, "Write webapp", true}, Task{3, "???", false}, Task{4, "Profit! $$$", false}, } ) type Index struct { Tasks []Task Addr string } type Task struct { Id uint64 Name string Done bool } func index(w http.ResponseWriter, r *http.Request) { indexTemplate.Execute(w, Index{tasks, addr}) } func main() { r := mux.NewRouter() r.HandleFunc("/", index) r.HandleFunc("/ws", serveWs) static := http.StripPrefix("/static/", http.FileServer(http.Dir("./static/"))) r.PathPrefix("/static/").Handler(static) go h.run() logger := handlers.LoggingHandler(os.Stdout, r) log.Println("Starting server on", addr) log.Fatal(http.ListenAndServe(addr, logger)) }
vinzBad/checklost
main.go
GO
mit
965
module Pwb class OmniauthController < ApplicationController # https://github.com/plataformatec/devise/wiki/How-To:-OmniAuth-inside-localized-scope def localized # Just save the current locale in the session and redirect to the unscoped path as before session[:omniauth_login_locale] = I18n.locale # user_facebook_omniauth_authorize_path # redirect_to user_omniauth_authorize_path(params[:provider]) redirect_to omniauth_authorize_path("user", params[:provider]) end end end
etewiah/property-web-builder
app/controllers/pwb/omniauth_controller.rb
Ruby
mit
520
<?php namespace Alterway\Component\Workflow\Exception; class MoreThanOneOpenTransitionException extends \LogicException { public function __construct() { return parent::__construct('More than one open transition with current context'); } }
alterway/component-workflow
src/Exception/MoreThanOneOpenTransitionException.php
PHP
mit
264
/** * JS initialization and core functions for API test servlet * * @depends {3rdparty/jquery.js} * @depends {3rdparty/bootstrap.js} * @depends {3rdparty/highlight.pack.js} */ var ATS = (function(ATS, $, undefined) { ATS.apiCalls = []; ATS.selectedApiCalls = []; ATS.init = function() { hljs.initHighlightingOnLoad(); ATS.selectedApiCalls = ATS.setSelectedApiCalls(); ATS.selectedApiCallsChange(); $('#search').keyup(function(e) { if (e.keyCode == 13) { ATS.performSearch($(this).val()); } }); $(".collapse-link").click(function(event) { event.preventDefault(); }); $('#navi-show-open').click(function(e) { $('.api-call-All').each(function() { if($(this).find('.panel-collapse.in').length != 0) { $(this).show(); } else { $(this).hide(); } }); $('#navi-show-all').css('font-weight', 'normal'); $(this).css('font-weight', 'bold'); e.preventDefault(); }); $('#navi-show-all').click(function(e) { $('.api-call-All').show(); $('#navi-show-open').css('font-weight', 'normal'); $(this).css('font-weight', 'bold'); e.preventDefault(); }); $('.api-call-sel-ALL').change(function() { if($(this).is(":checked")) { ATS.addToSelected($(this)); } else { ATS.removeFromSelected($(this)); } }); $('#navi-select-all-d-add-btn').click(function(e) { $.each($('.api-call-sel-ALL:visible:not(:checked)'), function(key, value) { ATS.addToSelected($(value)); }); e.preventDefault(); }); $('#navi-select-all-d-replace-btn').click(function(e) { ATS.selectedApiCalls = []; $.each($('.api-call-sel-ALL:visible'), function(key, value) { ATS.addToSelected($(value)); }); e.preventDefault(); }); $('#navi-deselect-all-d-btn').click(function(e) { $.each($('.api-call-sel-ALL:visible'), function(key, value) { ATS.removeFromSelected($(value)); }); e.preventDefault(); }); $('#navi-deselect-all-btn').click(function(e) { ATS.selectedApiCalls = []; $('.api-call-sel-ALL').prop('checked', false); ATS.selectedApiCallsChange(); e.preventDefault(); }); } ATS.performSearch = function(searchStr) { if (searchStr == '') { $('.api-call-All').show(); } else { $('.api-call-All').hide(); $('.topic-link').css('font-weight', 'normal'); for(var i=0; i<ATS.apiCalls.length; i++) { var apiCall = ATS.apiCalls[i]; if (new RegExp(searchStr.toLowerCase()).test(apiCall.toLowerCase())) { $('#api-call-' + apiCall).show(); } } } } ATS.submitForm = function(form) { var url = '/life'; var params = {}; for (i = 0; i < form.elements.length; i++) { if (form.elements[i].type != 'button' && form.elements[i].value && form.elements[i].value != 'submit') { var key = form.elements[i].name; var value = form.elements[i].value; if(key in params) { var index = params[key].length; params[key][index] = value; } else { params[key] = [value]; } } } $.ajax({ url: url, type: 'POST', data: params, traditional: true // "true" needed for duplicate params }) .done(function(result) { var resultStr = JSON.stringify(JSON.parse(result), null, 4); var code_elem = form.getElementsByClassName("result")[0]; code_elem.textContent = resultStr; hljs.highlightBlock(code_elem); }) .error(function() { alert('API not available, check if Life Server is running!'); }); if ($(form).has('.uri-link').length > 0) { var uri = '/life?' + jQuery.param(params, true); var html = '<a href="' + uri + '" target="_blank" style="font-size:12px;font-weight:normal;">Open GET URL</a>'; form.getElementsByClassName("uri-link")[0].innerHTML = html; } return false; } ATS.selectedApiCallsChange = function() { var newUrl = '/test?requestTypes=' + encodeURIComponent(ATS.selectedApiCalls.join('_')); $('#navi-selected').attr('href', newUrl); $('#navi-selected').text('SELECTED (' + ATS.selectedApiCalls.length + ')'); ATS.setCookie('selected_api_calls', ATS.selectedApiCalls.join('_'), 30); } ATS.setSelectedApiCalls = function() { var calls = []; var getParam = ATS.getUrlParameter('requestTypes'); var cookieParam = ATS.getCookie('selected_api_calls'); if (getParam != undefined && getParam != '') { calls=getParam.split('_'); } else if (cookieParam != undefined && cookieParam != ''){ calls=cookieParam.split('_'); } for (var i=0; i<calls.length; i++) { $('#api-call-sel-' + calls[i]).prop('checked', true); } return calls; } ATS.addToSelected = function(elem) { var type=elem.attr('id').substr(13); elem.prop('checked', true); if($.inArray(type, ATS.selectedApiCalls) == -1) { ATS.selectedApiCalls.push(type); ATS.selectedApiCallsChange(); } } ATS.removeFromSelected = function(elem) { var type=elem.attr('id').substr(13); elem.prop('checked', false); var index = ATS.selectedApiCalls.indexOf(type); if (index > -1) { ATS.selectedApiCalls.splice(index, 1); ATS.selectedApiCallsChange(); } } return ATS; }(ATS || {}, jQuery)); $(document).ready(function() { ATS.init(); });
YawLife/LIFE
html/ui/js/ats.js
JavaScript
mit
6,337
<?php /** * ====================================================================== * LICENSE: This file is subject to the terms and conditions defined in * * file 'license.txt', which is part of this source code package. * * ====================================================================== */ /** * Abstract subject * * @package AAM * @author Vasyl Martyniuk <vasyl@vasyltech.com> */ abstract class AAM_Core_Subject { /** * Subject ID * * Whether it is User ID or Role ID * * @var string|int * * @access private */ private $_id; /** * WordPres Subject * * It can be WP_User or WP_Role, based on what class has been used * * @var WP_Role|WP_User * * @access private */ private $_subject; /** * List of Objects to be access controlled for current subject * * All access control objects like Admin Menu, Metaboxes, Posts etc * * @var array * * @access private */ private $_objects = array(); /** * Constructor * * @param string|int $id * * @return void * * @access public */ public function __construct($id = '') { //set subject $this->setId($id); //retrieve and set subject itself $this->setSubject($this->retrieveSubject()); } /** * Trigger Subject native methods * * @param string $name * @param array $args * * @return mixed * * @access public */ public function __call($name, $args) { $subject = $this->getSubject(); //make sure that method is callable if (method_exists($subject, $name)) { $response = call_user_func_array(array($subject, $name), $args); } else { $response = null; } return $response; } /** * Get Subject's native properties * * @param string $name * * @return mixed * * @access public */ public function __get($name) { $subject = $this->getSubject(); return (!empty($subject->$name) ? $subject->$name : null); } /** * Set Subject's native properties * * @param string $name * * @return mixed * * @access public */ public function __set($name, $value) { $subject = $this->getSubject(); if ($subject) { $subject->$name = $value; } } /** * Set Subject ID * * @param string|int * * @return void * * @access public */ public function setId($id) { $this->_id = $id; } /** * Get Subject ID * * @return string|int * * @access public */ public function getId() { return $this->_id; } /** * Get subject name * * @return string * * @access public */ public function getName() { return ''; } /** * * @return int */ public function getMaxLevel() { return 0; } /** * Get Subject * * @return WP_Role|WP_User * * @access public */ public function getSubject() { return $this->_subject; } /** * Set Subject * * @param WP_Role|WP_User $subject * * @return void * * @access public */ public function setSubject($subject) { $this->_subject = $subject; } /** * Get Individual Object * * @param string $type * @param mixed $id * * @return AAM_Core_Object * * @access public */ public function getObject($type, $id = 'none', $param = null) { $object = null; //performance optimization $id = (is_scalar($id) ? $id : 'none'); //prevent from any surprises //check if there is an object with specified ID if (!isset($this->_objects[$type][$id])) { $classname = 'AAM_Core_Object_' . ucfirst($type); if (class_exists($classname)) { $object = new $classname($this, (is_null($param) ? $id : $param)); } $object = apply_filters('aam-object-filter', $object, $type, $id, $this); if (is_a($object, 'AAM_Core_Object')) { $this->_objects[$type][$id] = $object; } } else { $object = $this->_objects[$type][$id]; } return $object; } /** * Check if subject has capability * * @param string $capability * * @return boolean * * @access public */ public function hasCapability($capability) { $subject = $this->getSubject(); return ($subject ? $subject->has_cap($capability) : false); } /** * Save option * * @param string $param * @param mixed $value * @param string $object * @param mixed $objectId * * @return boolean * * @access public */ public function save($param, $value, $object, $objectId = 0) { return $this->getObject($object, $objectId)->save($param, $value); } /** * Reset object * * @param string $object * * @return boolean * * @access public */ public function resetObject($object) { return $this->deleteOption($object); } /** * Delete option * * @param string $object * @param mixed $id * * @return boolean * * @access public */ public function deleteOption($object, $id = 0) { return AAM_Core_API::deleteOption($this->getOptionName($object, $id)); } /** * Retrieve list of subject's capabilities * * @return array * * @access public */ public function getCapabilities() { return array(); } /** * Retrieve subject based on used class * * @return void * * @access protected */ protected function retrieveSubject() { return null; } /** * */ abstract public function getOptionName($object, $id); /** * Read object from parent subject * * @param string $object * @param mixed $id * * @return mixed * * @access public */ public function inheritFromParent($object, $id = '', $param = null){ if ($subject = $this->getParent()){ $option = $subject->getObject($object, $id, $param)->getOption(); } else { $option = null; } return $option; } /** * Retrieve parent subject * * If there is no parent subject, return null * * @return AAM_Core_Subject|null * * @access public */ public function getParent() { return null; } }
mandino/nu
wp-content/plugins/advanced-access-manager/Application/Core/Subject.php
PHP
mit
7,033
package org.diorite.impl.connection.packets.play.server; import java.io.IOException; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import org.diorite.impl.connection.EnumProtocol; import org.diorite.impl.connection.EnumProtocolDirection; import org.diorite.impl.connection.packets.PacketClass; import org.diorite.impl.connection.packets.PacketDataSerializer; import org.diorite.impl.connection.packets.play.PacketPlayServerListener; import org.diorite.impl.connection.packets.play.client.PacketPlayClientResourcePackStatus; @PacketClass(id = 0x48, protocol = EnumProtocol.PLAY, direction = EnumProtocolDirection.CLIENTBOUND, size = 180) public class PacketPlayServerResourcePackSend extends PacketPlayServer { private String url; // ~130 bytes private String hash; // ~41 bytes public PacketPlayServerResourcePackSend() { } public PacketPlayServerResourcePackSend(final String url, final String hash) { if (hash.length() > PacketPlayClientResourcePackStatus.MAX_HASH_SIZE) { throw new IllegalArgumentException("Hash is too long (max 40, was " + hash.length() + ")"); } this.url = url; this.hash = hash; } public String getUrl() { return this.url; } public void setUrl(final String url) { this.url = url; } public String getHash() { return this.hash; } public void setHash(final String hash) { this.hash = hash; } @Override public void readPacket(final PacketDataSerializer data) throws IOException { this.url = data.readText(Short.MAX_VALUE); this.hash = data.readText(PacketPlayClientResourcePackStatus.MAX_HASH_SIZE); } @Override public void writeFields(final PacketDataSerializer data) throws IOException { data.writeText(this.url); data.writeText(this.hash); } @Override public void handle(final PacketPlayServerListener listener) { listener.handle(this); } @Override public String toString() { return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE).appendSuper(super.toString()).append("url", this.url).append("hash", this.hash).toString(); } }
marszczybrew/Diorite
DioriteCore/src/main/java/org/diorite/impl/connection/packets/play/server/PacketPlayServerResourcePackSend.java
Java
mit
2,319
using UnityEngine; using System.Collections; public class ShapeInfo { public int Column { get; set; } public int Row { get; set; } }
michael-munoz/MooMooPlanet
Project455/Assets/Scripts/ShapeInfo.cs
C#
mit
145
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.resourcemanager.trafficmanager.implementation; import com.azure.core.management.Region; import com.azure.resourcemanager.resources.fluentcore.utils.ResourceManagerUtils; import com.azure.resourcemanager.trafficmanager.fluent.EndpointsClient; import com.azure.resourcemanager.trafficmanager.fluent.models.EndpointInner; import com.azure.resourcemanager.trafficmanager.models.TrafficManagerNestedProfileEndpoint; /** Implementation for {@link TrafficManagerNestedProfileEndpoint}. */ class TrafficManagerNestedProfileEndpointImpl extends TrafficManagerEndpointImpl implements TrafficManagerNestedProfileEndpoint { TrafficManagerNestedProfileEndpointImpl( String name, TrafficManagerProfileImpl parent, EndpointInner inner, EndpointsClient client) { super(name, parent, inner, client); } @Override public String nestedProfileId() { return innerModel().targetResourceId(); } @Override public long minimumChildEndpointCount() { return ResourceManagerUtils.toPrimitiveLong(innerModel().minChildEndpoints()); } @Override public Region sourceTrafficLocation() { return Region.fromName((innerModel().endpointLocation())); } }
selvasingh/azure-sdk-for-java
sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/implementation/TrafficManagerNestedProfileEndpointImpl.java
Java
mit
1,325
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _assign = require('lodash/assign'); var _assign2 = _interopRequireDefault(_assign); exports.default = termsAggregation; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } /** * Construct a Terms aggregation. * * @param {String} field Field name to aggregate over. * @param {String} name Aggregation name. Defaults to agg_terms_<field>. * @param {Object} opts Additional options to include in the aggregation. * @return {Object} Terms aggregation. */ function termsAggregation(field, name, opts) { name = name || 'agg_terms_' + field; return _defineProperty({}, name, { terms: function () { return (0, _assign2.default)({ field: field }, opts); }() }); }
evgenypoyarkov/bodybuilder
lib/aggregations/terms-aggregation.js
JavaScript
mit
1,036
YUI.add('selector', function (Y, NAME) { }, '3.10.3', {"requires": ["selector-native"]});
braz/mojito-helloworld
node_modules/mojito/node_modules/yui/selector/selector.js
JavaScript
mit
93
using System.Linq; using Xunit; using Signum.Engine; using Signum.Entities; using Signum.Utilities; using Signum.Test.Environment; namespace Signum.Test.LinqProvider { /// <summary> /// Summary description for LinqProvider /// </summary> public class JoinGroupTest { public JoinGroupTest() { MusicStarter.StartAndLoad(); Connector.CurrentLogger = new DebugTextWriter(); } [Fact] public void Join() { var songsAlbum = (from a in Database.Query<AlbumEntity>() join b in Database.Query<AlbumEntity>().SelectMany(a => a.Songs) on a.Name equals b.Name select new { a.Name, Label = a.Label.Name }).ToList(); } [Fact] public void JoinEntity() { var songsAlbum = (from a in Database.Query<ArtistEntity>() join b in Database.Query<AlbumEntity>() on a equals b.Author select new { Artist = a.Name, Album = b.Name }).ToList(); } [Fact] public void JoinEntityTwice() { var algums = (from a1 in Database.Query<AlbumEntity>() join a2 in Database.Query<AlbumEntity>() on a1.Label equals a2.Label join a3 in Database.Query<AlbumEntity>() on a2.Label equals a3.Label select new { Name1 = a1.Name, Name2 = a2.Name, Name3 = a3.Name }).ToList(); } [Fact] public void JoinerExpansions() { var labels = Database.Query<AlbumEntity>().Join( Database.Query<AlbumEntity>(), a => a.Year, a => a.Year, (a1, a2) => a1.Label.Name + " " + a2.Label.Name).ToList(); } [Fact] public void LeftOuterJoinEntity() { var songsAlbum = (from a in Database.Query<ArtistEntity>().DefaultIfEmpty() join b in Database.Query<AlbumEntity>() on a equals b.Author select new { Artist = a.Name, Album = b.Name }).ToList(); } [Fact] public void LeftOuterJoinEntityNotNull() { var songsAlbum = (from a in Database.Query<ArtistEntity>().DefaultIfEmpty() join b in Database.Query<AlbumEntity>() on a equals b.Author select new { Artist = a.Name, Album = b.Name, HasArtist = a != null }).ToList(); } [Fact] public void RightOuterJoinEntity() { var songsAlbum = (from a in Database.Query<ArtistEntity>() join b in Database.Query<AlbumEntity>().DefaultIfEmpty() on a equals b.Author select new { Artist = a.Name, Album = b.Name }).ToList(); } [Fact] public void RightOuterJoinEntityNotNull() { var songsAlbum = (from a in Database.Query<ArtistEntity>() join b in Database.Query<AlbumEntity>().DefaultIfEmpty() on a equals b.Author select new { Artist = a.Name, Album = b.Name, HasArtist = b != null }).ToList(); } [Fact] public void FullOuterJoinEntity() { var songsAlbum = (from a in Database.Query<ArtistEntity>().DefaultIfEmpty() join b in Database.Query<AlbumEntity>().DefaultIfEmpty() on a equals b.Author select new { Artist = a.Name, Album = b.Name }).ToList(); } [Fact] public void FullOuterJoinEntityNotNull() { var songsAlbum = (from a in Database.Query<ArtistEntity>().DefaultIfEmpty() join b in Database.Query<AlbumEntity>().DefaultIfEmpty() on a equals b.Author select new { Artist = a.Name, Album = b.Name, HasArtist = a != null, HasAlbum = b != null }).ToList(); } [Fact] public void JoinGroup() { var songsAlbum = (from a in Database.Query<ArtistEntity>() join b in Database.Query<AlbumEntity>() on a equals b.Author into g select new { a.Name, Albums = (int?)g.Count() }).ToList(); } [Fact] public void LeftOuterJoinGroup() { var songsAlbum = (from a in Database.Query<ArtistEntity>() join b in Database.Query<AlbumEntity>().DefaultIfEmpty() on a equals b.Author into g select new { a.Name, Albums = (int?)g.Count() }).ToList(); } [TableName("#MyView")] class MyTempView : IView { [ViewPrimaryKey] public Lite<ArtistEntity> Artist { get; set; } } [Fact] public void LeftOuterMyView() { using (Transaction tr = new Transaction()) { Administrator.CreateTemporaryTable<MyTempView>(); Database.Query<ArtistEntity>().Where(a => a.Name.StartsWith("M")).UnsafeInsertView(a => new MyTempView { Artist = a.ToLite() }); var artists = (from a in Database.Query<ArtistEntity>() join b in Database.View<MyTempView>() on a.ToLite() equals b.Artist into g select a.ToLite()).ToList(); Assert.True(artists.All(a => a.ToString()!.StartsWith("M"))); var list1 = Database.View<MyTempView>().ToList(); var list2 = Database.Query<ArtistEntity>().Where(a => a.Name.StartsWith("M")).ToList(); Assert.Equal(list1.Count, list2.Count); tr.Commit(); } } } }
AlejandroCano/framework
Signum.Test/LinqProvider/JoinGroupTest.cs
C#
mit
6,007
<?php session_start(); require('php/userProfile.class.php'); //load userProfileclass ?> <!DOCTYPE html> <html> <head> <?php require("head_userpage.php"); //load special header only for this page ?> </head> <body> <?php if(isset($_SESSION['ID'])){ //load the appropriate menu require("menu_co.php"); }else{ require("menu_pasco_general.php"); } ?> <div class="site-pusher"> <div class="content"> <?php if(!isset($errorProfile)){ require("disp_user_profile.php"); //load banner, pseudo and avatar of the current user require("disp_info_user.php"); //load info box for the user ?> <div class="fade"></div> <div class=blockallz> <?php $userPage->printPosts('profile'); //show all posts of the user (userProfile.class.php) }else{ include('disp_userNotExist.php'); //if we can't find user } ?> </div> <?php require("js/animation_user.php") ?> <script src="js/explore.js"></script> </body> </html>
KamevoTeam/Kamevo
kamevo_src/user.php
PHP
mit
962
<?php /* * This file is part of the PHPExifTool package. * * (c) Alchemy <support@alchemy.fr> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPExiftool\Driver\Tag\Pentax; use JMS\Serializer\Annotation\ExclusionPolicy; use PHPExiftool\Driver\AbstractTag; /** * @ExclusionPolicy("all") */ class InternalSerialNumber extends AbstractTag { protected $Id = 4; protected $Name = 'InternalSerialNumber'; protected $FullName = 'Pentax::CameraInfo'; protected $GroupName = 'Pentax'; protected $g0 = 'MakerNotes'; protected $g1 = 'Pentax'; protected $g2 = 'Camera'; protected $Type = 'int32u'; protected $Writable = true; protected $Description = 'Internal Serial Number'; protected $flag_Permanent = true; }
bburnichon/PHPExiftool
lib/PHPExiftool/Driver/Tag/Pentax/InternalSerialNumber.php
PHP
mit
862
using StyletIoC.Creation; using System; using System.Collections.Generic; using System.Linq.Expressions; namespace StyletIoC.Internal.Creators { /// <summary> /// Base class for all ICreators (which want to use it). Provides convenience /// </summary> internal abstract class CreatorBase : ICreator { public virtual RuntimeTypeHandle TypeHandle { get; protected set; } protected IRegistrationContext ParentContext { get; set; } protected CreatorBase(IRegistrationContext parentContext) { this.ParentContext = parentContext; } // Common utility method protected Expression CompleteExpressionFromCreator(Expression creator, ParameterExpression registrationContext) { var type = Type.GetTypeFromHandle(this.TypeHandle); var instanceVar = Expression.Variable(type, "instance"); var assignment = Expression.Assign(instanceVar, creator); var buildUpExpression = this.ParentContext.GetBuilderUpper(type).GetExpression(instanceVar, registrationContext); // We always start with: // var instance = new Class(.....) // instance.Property1 = new .... // instance.Property2 = new .... var blockItems = new List<Expression>() { assignment, buildUpExpression }; // If it implements IInjectionAware, follow that up with: // instance.ParametersInjected() if (typeof(IInjectionAware).IsAssignableFrom(type)) blockItems.Add(Expression.Call(instanceVar, typeof(IInjectionAware).GetMethod("ParametersInjected"))); // Final appearance of instanceVar, as this sets the return value of the block blockItems.Add(instanceVar); var completeExpression = Expression.Block(new[] { instanceVar }, blockItems); return completeExpression; } public abstract Expression GetInstanceExpression(ParameterExpression registrationContext); } }
canton7/Stylet
Stylet/StyletIoC/Internal/Creators/CreatorBase.cs
C#
mit
2,037
import { Directive, ElementRef, EventEmitter, Output, Input, OnInit } from '@angular/core'; import { TcCollectionService } from '../tc-collection/tc-collection.service'; import { TcCollection } from '../tc-collection/tc-collection.class'; declare var $: any; @Directive({ selector: '[tc-sortable]' }) export class TcSortableDirective { @Input('ignoreItem') ignoreItem = 0; @Input('list') list: any[]; @Input('ghostClass') ghostClass: string; @Output() itemMoved = new EventEmitter(); private element: HTMLElement; constructor(public el: ElementRef, private collectionService: TcCollectionService) { } ngOnInit() { this.element = this.el.nativeElement; var elCopy = this.element; let newIndex; let oldIndex; $(this.element).sortable({ placeholder: this.ghostClass, helper: function(x, y){ y.addClass('card-moving'); return y }, handle: '.card-collection--drag-handle', cancel: '.cancel-sort', tolerance: "pointer", items: "> :not(.not-sortable-item)", scroll: false, start: (event, ui) => { $(this).attr('data-previndex', ui.item.index()); }, update: (event, ui) => { newIndex = ui.item.index()-this.ignoreItem; oldIndex = $(this).attr('data-previndex')-this.ignoreItem; $(this).removeAttr('data-previndex'); }, stop: (event, ui) => { ui.item.removeClass('card-moving'); let tmpItem = this.list[oldIndex]; if(!tmpItem) return; tmpItem.position = newIndex; tmpItem.updatePosition = true; this.itemMoved.emit({ value: {modifiedItem: tmpItem} }) tmpItem.updatePosition = false; this.list.splice(oldIndex,1); this.list.splice(newIndex, 0, tmpItem); for(let i in this.list){ this.list[i].position = i; } } }) } }
OlivierCoue/invow
src/app/tc-shared/tc-sortable.directive.ts
TypeScript
mit
2,177
#include "stdafx.h" #include "WindowClient.h" #include <SDL2/SDL.h> int main(int, char *[]) { try { CWindow window(ContextProfile::RobustOpenGL_3_2, ContextMode::Normal); // window.ShowFullscreen("Demo #19 (Particle Systems)"); window.Show("Demo #19 (Particle Systems)", {800, 600}); CWindowClient client(window); window.DoMainLoop(); } catch (const std::exception &ex) { const char *title = "Fatal Error"; const char *message = ex.what(); SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, title, message, nullptr); } return 0; }
PS-Group/cg_course_examples
chapter_4/lesson_19/main.cpp
C++
mit
620
/** */ package gluemodel.COSEM.COSEMObjects.impl; import gluemodel.COSEM.COSEMObjects.COSEMObjectsPackage; import gluemodel.COSEM.COSEMObjects.PushSchedule; import gluemodel.COSEM.InterfaceClasses.impl.SingleactionscheduleImpl; import org.eclipse.emf.ecore.EClass; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Push Schedule</b></em>'. * <!-- end-user-doc --> * * @generated */ public class PushScheduleImpl extends SingleactionscheduleImpl implements PushSchedule { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected PushScheduleImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return COSEMObjectsPackage.eINSTANCE.getPushSchedule(); } } //PushScheduleImpl
georghinkel/ttc2017smartGrids
solutions/eMoflon/rgse.ttc17.metamodels.src/src/gluemodel/COSEM/COSEMObjects/impl/PushScheduleImpl.java
Java
mit
844
//------------------------------------------------------------------------------ // dummyFSWrapper.cc //------------------------------------------------------------------------------ #include "Pre.h" #include "dummyFSWrapper.h" namespace Oryol { namespace _priv { //------------------------------------------------------------------------------ dummyFSWrapper::handle dummyFSWrapper::openRead(const char* path) { return invalidHandle; } //------------------------------------------------------------------------------ dummyFSWrapper::handle dummyFSWrapper::openWrite(const char* path) { return invalidHandle; } //------------------------------------------------------------------------------ int dummyFSWrapper::write(handle f, const void* ptr, int numBytes) { return 0; } //------------------------------------------------------------------------------ int dummyFSWrapper::read(handle f, void* ptr, int numBytes) { return 0; } //------------------------------------------------------------------------------ bool dummyFSWrapper::seek(handle f, int offset) { return true; } //------------------------------------------------------------------------------ int dummyFSWrapper::size(handle f) { return 0; } //------------------------------------------------------------------------------ void dummyFSWrapper::close(handle f) { // empty } //------------------------------------------------------------------------------ String dummyFSWrapper::getExecutableDir() { return String(); } //------------------------------------------------------------------------------ String dummyFSWrapper::getCwd() { return String(); } } // namespace _priv } // namespace Oryol
floooh/oryol
code/Modules/LocalFS/private/dummy/dummyFSWrapper.cc
C++
mit
1,707
module Jekyll VERSION = '3.0.0.pre.beta6' end
mixxmac/jekyll
lib/jekyll/version.rb
Ruby
mit
48
import logging from django.conf import settings from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.db import models from django.utils.translation import ugettext_lazy as _ from wagtail.admin.edit_handlers import FieldPanel, MultiFieldPanel from wagtail.core.fields import RichTextField from wagtail.core.models import Page from wagtail.images.models import Image from wagtail.images.edit_handlers import ImageChooserPanel class PhotoGalleryIndexPage(Page): intro = RichTextField(blank=True) feed_image = models.ForeignKey( Image, help_text="An optional image to represent the page", null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) indexed_fields = ('intro') @property def galleries(self): galleries = GalleryIndex.objects.live().descendant_of(self) galleries = galleries.order_by('-first_published_at') return galleries def get_context(self, request): galleries = self.galleries page = request.GET.get('page') paginator = Paginator(galleries, 16) try: galleries = paginator.page(page) except PageNotAnInteger: galleries = paginator.page(1) except EmptyPage: galleries = paginator.page(paginator.num_pages) context = super(PhotoGalleryIndexPage, self).get_context(request) context['galleries'] = galleries return context class Meta: verbose_name = _('Photo Gallery Index') PhotoGalleryIndexPage.content_panels = [ FieldPanel('title', classname="full title"), FieldPanel('intro', classname="full"), ] PhotoGalleryIndexPage.promote_panels = [ MultiFieldPanel(Page.promote_panels, "Common page configuration"), ImageChooserPanel('feed_image'), ] IMAGE_ORDER_TYPES = ( (1, 'Image title'), (2, 'Newest image first'), ) class GalleryIndex(Page): intro = RichTextField( blank=True, verbose_name=_('Intro text'), help_text=_('Optional text to go with the intro text.') ) collection = models.ForeignKey( 'wagtailcore.Collection', verbose_name=_('Collection'), null=True, blank=False, on_delete=models.SET_NULL, related_name='+', help_text=_('Show images in this collection in the gallery view.') ) images_per_page = models.IntegerField( default=20, verbose_name=_('Images per page'), help_text=_('How many images there should be on one page.') ) order_images_by = models.IntegerField(choices=IMAGE_ORDER_TYPES, default=1) feed_image = models.ForeignKey( Image, help_text="An optional image to represent the page", null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) content_panels = Page.content_panels + [ FieldPanel('intro', classname='full title'), FieldPanel('collection'), FieldPanel('images_per_page', classname='full title'), FieldPanel('order_images_by'), ] promote_panels = [ MultiFieldPanel(Page.promote_panels, "Common page configuration"), ImageChooserPanel('feed_image'), ] @property def images(self): return get_gallery_images(self.collection.name, self) def get_context(self, request): images = self.images page = request.GET.get('page') paginator = Paginator(images, self.images_per_page) try: images = paginator.page(page) except PageNotAnInteger: images = paginator.page(1) except EmptyPage: images = paginator.page(paginator.num_pages) context = super(GalleryIndex, self).get_context(request) context['gallery_images'] = images return context class Meta: verbose_name = _('Photo Gallery') verbose_name_plural = _('Photo Galleries') template = getattr(settings, 'GALLERY_TEMPLATE', 'gallery/gallery_index.html') def get_gallery_images(collection, page=None, tags=None): images = None try: images = Image.objects.filter(collection__name=collection) if page: if page.order_images_by == 0: images = images.order_by('title') elif page.order_images_by == 1: images = images.order_by('-created_at') except Exception as e: logging.exception(e) if images and tags: images = images.filter(tags__name__in=tags).distinct() return images
ilendl2/wagtail-cookiecutter-foundation
{{cookiecutter.project_slug}}/gallery/models.py
Python
mit
4,587
// // client.cpp // ~~~~~~~~~~ // // Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <asio.hpp> #include <boost/lambda/lambda.hpp> #include <boost/lambda/bind.hpp> #include <boost/lambda/if.hpp> #include <boost/shared_ptr.hpp> #include <algorithm> #include <cstdlib> #include <exception> #include <iostream> #include <string> #include "protocol.hpp" using namespace boost; using asio::ip::tcp; using asio::ip::udp; int main(int argc, char* argv[]) { try { if (argc != 3) { std::cerr << "Usage: client <host> <port>\n"; return 1; } using namespace std; // For atoi. std::string host_name = argv[1]; std::string port = argv[2]; asio::io_context io_context; // Determine the location of the server. tcp::resolver resolver(io_context); tcp::endpoint remote_endpoint = *resolver.resolve(host_name, port).begin(); // Establish the control connection to the server. tcp::socket control_socket(io_context); control_socket.connect(remote_endpoint); // Create a datagram socket to receive data from the server. boost::shared_ptr<udp::socket> data_socket( new udp::socket(io_context, udp::endpoint(udp::v4(), 0))); // Determine what port we will receive data on. udp::endpoint data_endpoint = data_socket->local_endpoint(); // Ask the server to start sending us data. control_request start = control_request::start(data_endpoint.port()); asio::write(control_socket, start.to_buffers()); unsigned long last_frame_number = 0; for (;;) { // Receive 50 messages on the current data socket. for (int i = 0; i < 50; ++i) { // Receive a frame from the server. frame f; data_socket->receive(f.to_buffers(), 0); if (f.number() > last_frame_number) { last_frame_number = f.number(); std::cout << "\n" << f.payload(); } } // Time to switch to a new socket. To ensure seamless handover we will // continue to receive packets using the old socket until data arrives on // the new one. std::cout << " Starting renegotiation"; // Create the new data socket. boost::shared_ptr<udp::socket> new_data_socket( new udp::socket(io_context, udp::endpoint(udp::v4(), 0))); // Determine the new port we will use to receive data. udp::endpoint new_data_endpoint = new_data_socket->local_endpoint(); // Ask the server to switch over to the new port. control_request change = control_request::change( data_endpoint.port(), new_data_endpoint.port()); asio::error_code control_result; asio::async_write(control_socket, change.to_buffers(), ( lambda::var(control_result) = lambda::_1 )); // Try to receive a frame from the server on the new data socket. If we // successfully receive a frame on this new data socket we can consider // the renegotation complete. In that case we will close the old data // socket, which will cause any outstanding receive operation on it to be // cancelled. frame f1; asio::error_code new_data_socket_result; new_data_socket->async_receive(f1.to_buffers(), ( // Note: lambda::_1 is the first argument to the callback handler, // which in this case is the error code for the operation. lambda::var(new_data_socket_result) = lambda::_1, lambda::if_(!lambda::_1) [ // We have successfully received a frame on the new data socket, // so we can close the old data socket. This will cancel any // outstanding receive operation on the old data socket. lambda::var(data_socket) = boost::shared_ptr<udp::socket>() ] )); // This loop will continue until we have successfully completed the // renegotiation (i.e. received a frame on the new data socket), or some // unrecoverable error occurs. bool done = false; while (!done) { // Even though we're performing a renegotation, we want to continue // receiving data as smoothly as possible. Therefore we will continue to // try to receive a frame from the server on the old data socket. If we // receive a frame on this socket we will interrupt the io_context, // print the frame, and resume waiting for the other operations to // complete. frame f2; done = true; // Let's be optimistic. if (data_socket) // Might have been closed by new_data_socket's handler. { data_socket->async_receive(f2.to_buffers(), 0, ( lambda::if_(!lambda::_1) [ // We have successfully received a frame on the old data // socket. Stop the io_context so that we can print it. lambda::bind(&asio::io_context::stop, &io_context), lambda::var(done) = false ] )); } // Run the operations in parallel. This will block until all operations // have finished, or until the io_context is interrupted. (No threads!) io_context.restart(); io_context.run(); // If the io_context.run() was interrupted then we have received a frame // on the old data socket. We need to keep waiting for the renegotation // operations to complete. if (!done) { if (f2.number() > last_frame_number) { last_frame_number = f2.number(); std::cout << "\n" << f2.payload(); } } } // Since the loop has finished, we have either successfully completed // the renegotation, or an error has occurred. First we'll check for // errors. if (control_result) throw asio::system_error(control_result); if (new_data_socket_result) throw asio::system_error(new_data_socket_result); // If we get here it means we have successfully started receiving data on // the new data socket. This new data socket will be used from now on // (until the next time we renegotiate). std::cout << " Renegotiation complete"; data_socket = new_data_socket; data_endpoint = new_data_endpoint; if (f1.number() > last_frame_number) { last_frame_number = f1.number(); std::cout << "\n" << f1.payload(); } } } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << std::endl; } return 0; }
mojmir-svoboda/BlackBoxTT
3rd_party/asio/src/examples/cpp03/porthopper/client.cpp
C++
mit
6,839
'use strict'; //Setting up route angular.module('mean.articles').config(['$stateProvider', 'markedProvider', function($stateProvider, markedProvider) { markedProvider.setOptions({ gfm: true, tables: true, breaks: true, highlight: function (code) { /* jshint ignore:start */ return hljs.highlightAuto(code).value; /* jshint ignore:end */ } }); // Check if the user is connected var checkLoggedin = function($q, $timeout, $http, $location) { // Initialize a new promise var deferred = $q.defer(); // Make an AJAX call to check if the user is logged in $http.get('/loggedin').success(function(user) { // Authenticated if (user !== '0') $timeout(deferred.resolve); // Not Authenticated else { $timeout(deferred.reject); $location.url('/login'); } }); return deferred.promise; }; // states for my app $stateProvider .state('all articles', { url: '/articles', templateUrl: 'articles/views/list.html', //resolve: { // loggedin: checkLoggedin //} }) .state('create article', { url: '/articles/create', templateUrl: 'articles/views/create.html', resolve: { loggedin: checkLoggedin } }) .state('edit article', { url: '/articles/:articleId/edit', templateUrl: 'articles/views/edit.html', resolve: { loggedin: checkLoggedin } }) .state('article by id', { url: '/articles/:articleId', templateUrl: 'articles/views/view.html', //resolve: { // loggedin: checkLoggedin //} }); } ]);
darul75/nsjoy.github.io2
packages/articles/public/routes/articles.js
JavaScript
mit
1,768
/**************************************************************************** Copyright (c) 2011-2013,WebJet Business Division,CYOU http://www.genesis-3d.com.cn Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ using System; using System.Runtime.CompilerServices; using ScriptRuntime; namespace ScriptRuntime { /// <summary> /// 网格渲染组件类 /// </summary> public partial class MeshRenderComponent : RenderComponent { // - internal call declare [MethodImplAttribute(MethodImplOptions.InternalCall)] extern private static void ICall_MeshRenderComponent_SetMeshID(MeshRenderComponent self, String sMeshId, int priority); [MethodImplAttribute(MethodImplOptions.InternalCall)] extern private static void ICall_MeshRenderComponent_SetDrawDepth(MeshRenderComponent self, bool bDraw); [MethodImplAttribute(MethodImplOptions.InternalCall)] extern private static int ICall_MeshRenderComponent_GetTriangleCount(MeshRenderComponent self); [MethodImplAttribute(MethodImplOptions.InternalCall)] extern private static int ICall_MeshRenderComponent_GetVertexCount(MeshRenderComponent self); [MethodImplAttribute(MethodImplOptions.InternalCall)] extern private static string ICall_MeshRenderComponent_GetMeshID(MeshRenderComponent self); } }
EngineDreamer/DreamEngine
Engine/script/runtimelibrary/MeshRenderComponent_register.cs
C#
mit
2,409
using System; using System.Text; using System.Threading.Tasks; using System.Collections.Generic; using AuthorizeNet.Api.Controllers; using AuthorizeNet.Api.Contracts.V1; using AuthorizeNet.Api.Controllers.Bases; namespace net.authorize.sample { class PayPalPriorAuthorizationCapture { public static void Run(String ApiLoginID, String ApiTransactionKey, string TransactionID) { Console.WriteLine("PayPal Prior Authorization Transaction"); ApiOperationBase<ANetApiRequest, ANetApiResponse>.RunEnvironment = AuthorizeNet.Environment.SANDBOX; // define the merchant information (authentication / transaction id) ApiOperationBase<ANetApiRequest, ANetApiResponse>.MerchantAuthentication = new merchantAuthenticationType() { name = ApiLoginID, ItemElementName = ItemChoiceType.transactionKey, Item = ApiTransactionKey }; var payPalType = new payPalType { cancelUrl = "http://www.merchanteCommerceSite.com/Success/TC25262", successUrl = "http://www.merchanteCommerceSite.com/Success/TC25262", // the url where the user will be returned to }; //standard api call to retrieve response var paymentType = new paymentType { Item = payPalType }; var transactionRequest = new transactionRequestType { transactionType = transactionTypeEnum.priorAuthCaptureTransaction.ToString(), // capture a prior authorization payment = paymentType, amount = 19.45m, refTransId = TransactionID // the TransID value that was returned from the first AuthOnlyTransaction call }; var request = new createTransactionRequest { transactionRequest = transactionRequest }; // instantiate the contoller that will call the service var controller = new createTransactionController(request); controller.Execute(); // get the response from the service (errors contained if any) var response = controller.GetApiResponse(); //validate if (response.messages.resultCode == messageTypeEnum.Ok) { if (response.transactionResponse != null) { Console.WriteLine("Success, Auth Code : " + response.transactionResponse.authCode); } } else { Console.WriteLine("Error: " + response.messages.message[0].code + " " + response.messages.message[0].text); if (response.transactionResponse != null) { Console.WriteLine("Transaction Error : " + response.transactionResponse.errors[0].errorCode + " " + response.transactionResponse.errors[0].errorText); } } } } }
rmorrin/sample-code-csharp
PaypalExpressCheckout/PriorAuthorizationCapture.cs
C#
mit
3,051
BASE.require(["Object"], function () { BASE.namespace("LG.core.dataModel.core"); LG.core.dataModel.core.PeopleGroupToPermission = (function (Super) { var PeopleGroupToPermission = function () { var self = this; if (!(self instanceof arguments.callee)) { return new PeopleGroupToPermission(); } Super.call(self); return self; }; BASE.extend(PeopleGroupToPermission, Super); return PeopleGroupToPermission; }(Object)); });
jaredjbarnes/WoodlandCreatures
packages/WebLib.2.0.0.724/content/lib/weblib/lib/BASE/LG/core/dataModel/core/PeopleGroupToPermission.js
JavaScript
mit
545
<?php /* * This File is part of the Lucid\Mux package * * (c) iwyg <mail@thomas-appel.com> * * For full copyright and license information, please refer to the LICENSE file * that was distributed with this package. */ namespace Lucid\Mux\Tests; use Lucid\Mux\Route; /** * @class RouteTest * * @package Lucid\Mux * @version $Id$ * @author iwyg <mail@thomas-appel.com> */ class RouteTest extends \PHPUnit_Framework_TestCase { /** @test */ public function itShouldBeInstantiable() { $this->assertInstanceOf('Lucid\Mux\RouteInterface', $this->newRoute()); } /** @test */ public function itShouldGetPattern() { $route = new Route($pattern = '/user/{id}', 'action'); $this->assertSame($pattern, $route->getPattern()); } /** @test */ public function itShouldBeSerializable() { $route = new Route( $pattern = '/user/{id}', $handler = 'action', $methods = ['DELETE'], $host = 'example.com', $defaults = ['id' => 12], $constraints = ['id' => '\d+'], $schemes = ['https'] ); $newRoute = unserialize(serialize($route)); $this->assertSame($pattern, $newRoute->getPattern()); $this->assertSame($handler, $newRoute->getHandler()); $this->assertSame($methods, $newRoute->getMethods()); $this->assertSame($host, $newRoute->getHost()); $this->assertSame($defaults, $newRoute->getDefaults()); $this->assertSame($constraints, $newRoute->getConstraints()); $this->assertSame($schemes, $newRoute->getSchemes()); } /** @test */ public function itShouldThrowIfSerializedAndAnderIsClosure() { $route = new Route('/', function () { }); try { serialize($route); } catch (\LogicException $e) { $this->assertEquals('Cannot serialize handler.', $e->getMessage()); } } /** @test */ public function itShouldGetMethods() { $route = new Route('/', 'action', ['POST']); $this->assertTrue($route->hasMethod('post')); $route = new Route('/', 'action', $methods = ['get', 'head']); $this->assertTrue($route->hasMethod('get')); $this->assertTrue($route->hasMethod('head')); $this->assertSame(['GET', 'HEAD'], $route->getMethods()); } /** @test */ public function itShouldGetSchemes() { $route = new Route('/', 'action'); $this->assertTrue($route->hasScheme('http')); $this->assertTrue($route->hasScheme('https')); $route = new Route('/', 'action', null, null, null, null, ['https']); $this->assertFalse($route->hasScheme('http')); $this->assertTrue($route->hasScheme('HTTPS')); $route = new Route('/', 'action', null, null, null, null, null, ['HTTP', 'https']); $this->assertSame(['http', 'https'], $route->getSchemes()); } /** @test */ public function itShouldGetHost() { $route = new Route('/', 'action'); $this->assertNull($route->getHost()); $route = new Route('/', 'action', null, $host = 'example.com'); $this->assertSame($host, $route->getHost()); } /** @test */ public function itShouldGetDefaults() { $route = new Route('/', 'action', null, null, $def = ['foo' => 'bar']); $this->assertSame($def, $route->getDefaults()); $this->assertSame('bar', $route->getDefault('foo')); } /** @test */ public function itShouldGetConstraints() { $route = new Route('/', 'action', null, null, null, $const = ['foo' => 'bar']); $this->assertSame($const, $route->getConstraints()); $this->assertSame('bar', $route->getConstraint('foo')); } /** @test */ public function itShouldCallParser() { $route = $this->getMock(Route::class, ['getParserFunc'], ['/', 'action']); $route->method('getParserFunc')->willReturnCallback(function () { return function () { return 'RouteContext'; }; }); $this->assertSame('RouteContext', $route->getContext()); } private function newRoute($path = '/', $handler = 'action') { return new Route($path, $handler); } }
lucidphp/mux
tests/RouteTest.php
PHP
mit
4,374
"""Splits the time dimension into an reftime and a leadtime so that multiple files can be concatenated more easily""" import sys from netCDF4 import Dataset, num2date, date2num for f in sys.argv[1:]: dataset = Dataset(f, 'a') # rename record dimension to reftime dataset.renameDimension('record', 'reftime') # rename time dimension to leadtime dataset.renameDimension('time', 'leadtime') dataset.renameVariable('time', 'leadtime') time = dataset.variables['leadtime'] reftime = dataset.createVariable('reftime', 'f8', ('reftime',)) reftime.units = time.units reftime.calendar = time.calendar reftime[0] = time[0] reftime.standard_name = "forecast_reference_time" reftime.long_name = "Time of model initialization" dt = num2date(time[:], units=time.units, calendar=time.calendar) lt = date2num(dt, units="hours since %s" % dt[0], calendar=time.calendar) # use the existing time variable to hold lead time information time.units = "hours" time.standard_name = "forecast_period" time.long_name = "hours since forecast_reference_time" time[:] = lt del(time.calendar) dataset.renameVariable('location', 'old_location') dataset.renameVariable('lat', 'old_lat') dataset.renameVariable('lon', 'old_lon') dataset.renameVariable('height', 'old_height') loc = dataset.createVariable('location', 'S1', ('location','loc_str_length')) lat = dataset.createVariable('lat', 'f8', ('location',)) lon = dataset.createVariable('lon', 'f8', ('location',)) hgt = dataset.createVariable('height','i4',('height',)) loc[:] = dataset.variables['old_location'][0] lat[:] = dataset.variables['old_lat'][0] lon[:] = dataset.variables['old_lon'][0] hgt[:] = dataset.variables['old_height'][0] dataset.close()
samwisehawkins/wrftools
util/split_time_dimension.py
Python
mit
1,878
/* global chrome */ const VERSION = 1; const handlers = { 'vclub:screenShare:requestSourceId': () => { chrome.runtime.sendMessage({ type: 'vclub:requestSourceId' }, (response) => { window.postMessage({ type: 'vclub:screenShare:response', response, }, '*'); }); }, 'vclub:ping': () => { window.postMessage({ type: 'vclub:extension:loaded', version: VERSION, }, '*'); }, }; window.addEventListener('message', (event) => { if (event.source !== window) return; const handler = handlers[event.data.type]; if (handler) { handler(event.data, event); } }); handlers['vclub:ping']();
VirtualClub/vclub
browserExtensions/chromeExtension/content-script.js
JavaScript
mit
658
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.Collections.ObjectModel; using System.Windows.Markup; using System.Windows.Controls.Primitives; namespace GAPPSF.UIControls { /// <summary> /// Interaction logic for TimeCtrl.xaml /// </summary> [ContentProperty("Children")] public partial class TimeCtrl : UserControl, IFrameTxtBoxCtrl { private static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(DateTime), typeof(TimeCtrl), new PropertyMetadata(DateTime.Now, ValueChangedCallback)); private static readonly DependencyProperty TimePatternProperty = DependencyProperty.Register("TimePattern", typeof(string), typeof(TimeCtrl), new PropertyMetadata(SystemDateInfo.LongTimePattern)); private static readonly DependencyProperty TextAlignmentProperty = DependencyProperty.Register("TextAlignment", typeof(TextAlignment), typeof(TimeCtrl), new PropertyMetadata(TextAlignment.Left, TextAlignmentChangedCallback)); public static readonly DependencyProperty UseValidTimesProperty = DependencyProperty.Register("UseValidTimes", typeof(bool), typeof(TimeCtrl), new PropertyMetadata(false, UseValidTimesChangedCallback)); public static readonly DependencyProperty ValidTimesNameProperty = DependencyProperty.Register("ValidTimesName", typeof(string), typeof(TimeCtrl), new PropertyMetadata(LanguageStrings.ValidTimes)); public static readonly DependencyProperty NoValidTimesStringProperty = DependencyProperty.Register("NoValidTimesString", typeof(string), typeof(TimeCtrl), new PropertyMetadata(LanguageStrings.None)); private static readonly DependencyProperty InvalidTimeTextBrushProperty = DependencyProperty.Register("InvalidTimeTextBrush", typeof(Brush), typeof(TimeCtrl), new PropertyMetadata(Brushes.Red)); public static readonly DependencyProperty IsValidTimeProperty = DependencyProperty.Register("IsValidTime", typeof(bool), typeof(TimeCtrl), new PropertyMetadata(true, IsValidTimeChangedCallback)); private static void ValueChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { TimeCtrl tc = d as TimeCtrl; if (tc != null && e.NewValue is DateTime) { foreach (UIElement ele in tc.TimeCtrls.Children) { var ctrl = ele as FrameworkElement; HMSType hmsType = ctrl.get_HMSType(); if (hmsType != HMSType.unknown) { var tb = ctrl as TextBox; if (tb != null) tb.set_HMSText((DateTime)e.NewValue); } } tc.SetIsValidTime(); } } private static void TextAlignmentChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { TimeCtrl tc = d as TimeCtrl; if (tc != null && e.NewValue is TextAlignment) { tc.TextBoxCtrl.TextAlignment = (TextAlignment)e.NewValue; tc.ReloadTimeCtrlsGrid(); } } private static void IsValidTimeChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { TimeCtrl tc = d as TimeCtrl; if (tc != null && e.NewValue is bool) { foreach (FrameworkElement fe in tc.TimeCtrls.Children) { if (fe is TextBox) ((TextBox)fe).Foreground = tc.TextBrush; else if (fe is TextBlock) ((TextBlock)fe).Foreground = tc.TextBrush; } } } private static void UseValidTimesChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { TimeCtrl tc = d as TimeCtrl; if (tc != null && e.NewValue is bool) tc.SetIsValidTime(); } static TimeCtrl() { Coercer.Initialize<TimeCtrl>(); } public TimeCtrl() { Children = new ObservableCollection<ValidTimeItem>(); InitializeComponent(); this.Children.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(Children_CollectionChanged); } public DateTime Value { get { return (DateTime)GetValue(ValueProperty); } set { SetValue(ValueProperty, value); } } public string TimePattern { get { return (string)GetValue(TimePatternProperty); } set { SetValue(TimePatternProperty, value); } } public TextAlignment TextAlignment { get { return (TextAlignment)GetValue(TextAlignmentProperty); } set { SetValue(TextAlignmentProperty, value); } } public bool UseValidTimes { get { return (bool)GetValue(UseValidTimesProperty); } set { SetValue(UseValidTimesProperty, value); } } public string ValidTimesName { get { return (string)GetValue(ValidTimesNameProperty); } set { SetValue(ValidTimesNameProperty, value); } } public string NoValidTimesString { get { return (string)GetValue(NoValidTimesStringProperty); } set { SetValue(NoValidTimesStringProperty, value); } } public Brush InvalidTimeTextBrush { get { return (Brush)GetValue(InvalidTimeTextBrushProperty); } set { SetValue(InvalidTimeTextBrushProperty, value); } } public bool IsValidTime { get { return (bool)GetValue(IsValidTimeProperty); } private set { SetValue(IsValidTimeProperty, value); } } public ObservableCollection<ValidTimeItem> Children { get; private set; } private Brush TextBrush { get { return IsEnabled ? (IsValidTime ? Foreground : InvalidTimeTextBrush) : SystemColors.GrayTextBrush; } } private void SetIsValidTime() { if (!UseValidTimes) IsValidTime = true; else { IsValidTime = false; foreach (ValidTimeItem vti in Children) { if (Value >= vti.BeginTime && Value <= vti.EndTime) { IsValidTime = true; break; } } } } private void Children_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { SetIsValidTime(); } TextBox IFrameTxtBoxCtrl.TextBox { get { return TextBoxCtrl; } } private bool MouseClicked = false; private void AddGridCtrl(FrameworkElement ctrl) { var cd = new ColumnDefinition(); cd.Width = new GridLength(1, GridUnitType.Auto); TimeCtrls.ColumnDefinitions.Add(cd); TimeCtrls.Children.Add(ctrl); Grid.SetColumn(ctrl, TimeCtrls.ColumnDefinitions.Count - 1); } private void AddHMSCtrlContextMenuItems(TextBox tb, params ICommand[] Commands) { foreach (ICommand Command in Commands) { MenuItem mi = new MenuItem(); mi.Command = Command; tb.ContextMenu.Items.Add(mi); } } private bool CmdBindCutPasteExecuteHandler(object sender, bool Execute, bool Cut) { var tb = sender as TextBox; bool CanExecute = false; string ClipTxt = ""; if (tb != null) { int CurPos = tb.SelectionStart, CurrentValue = 0, SelLength = tb.SelectionLength; if (Cut) ClipTxt = tb.Text.Substring(CurPos, tb.SelectionLength); string Txt = tb.Text.Remove(CurPos, tb.SelectionLength); if (!Cut) // If paste ClipTxt = (string)System.Windows.Clipboard.GetData("Text"); CanExecute = (!Cut && string.IsNullOrEmpty(ClipTxt)) ? false : (tb.IsAM_PM() ? (ClipTxt == SystemDateInfo.AMDesignator || ClipTxt == SystemDateInfo.PMDesignator) : ValidateInput(tb, (Cut)? Txt : Txt.Insert(CurPos, ClipTxt), out CurrentValue)); if (Execute) { Value = tb.IsAM_PM() ? Value.Reset_AM_PM_Time(ClipTxt == SystemDateInfo.AMDesignator) : Value.ResetTime(CurrentValue, tb.get_HMSType()); tb.SelectionStart = CurPos + SelLength; if (Cut) System.Windows.Clipboard.SetData("Text", ClipTxt); } } return CanExecute; } private void CmdBindCutExecuted(object sender, ExecutedRoutedEventArgs e) { CmdBindCutPasteExecuteHandler(sender, true, true); e.Handled = true; } void CmdBindCutCanExecute(object sender, CanExecuteRoutedEventArgs e) { var tb = sender as TextBox; e.CanExecute = (tb != null) && tb.SelectionLength > 0 && !tb.IsAM_PM(); } private void CmdBindPasteExecuted(object sender, ExecutedRoutedEventArgs e) { CmdBindCutPasteExecuteHandler(sender, true, false); e.Handled = true; } void CmdBindPasteCanExecute(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = CmdBindCutPasteExecuteHandler(sender, false, false); e.Handled = true; } private void CmdBindCopyTimeExecuted(object sender, ExecutedRoutedEventArgs e) { string strClipTime = ""; foreach (FrameworkElement fe in TimeCtrls.Children) { if (fe is TextBox) strClipTime += ((TextBox)fe).Text; else if (fe is TextBlock) strClipTime += ((TextBlock)fe).Text; } System.Windows.Clipboard.SetData("Text", strClipTime); e.Handled = true; } private void CmdBindPasteTimeExecuted(object sender, ExecutedRoutedEventArgs e) { int Hour, Minute, Second; if (TimeCtrlExtensions.IsValidTime((string)System.Windows.Clipboard.GetData("Text"), TimePattern, out Hour, out Minute, out Second)) Value = new DateTime(Value.Year, Value.Month, Value.Day, Hour, Minute, Second, Value.Millisecond, Value.Kind); } void CmdBindPasteTimeCanExecute(object sender, CanExecuteRoutedEventArgs e) { int Hour, Minute, Second; e.CanExecute = TimeCtrlExtensions.IsValidTime((string)System.Windows.Clipboard.GetData("Text"), TimePattern, out Hour, out Minute, out Second); } private void AddValidTimeString(string str, bool Highlighted = false) { var rd = new RowDefinition(); ValidTimesGrid.RowDefinitions.Add(rd); TextBlock tb = new TextBlock(); tb.Text = str; if (Highlighted) tb.FontWeight = FontWeights.Bold; tb.HorizontalAlignment = HorizontalAlignment.Center; tb.Background = Background; tb.Foreground = Foreground; tb.Margin = new Thickness(0.0); ValidTimesGrid.Children.Add(tb); Grid.SetRow(tb, ValidTimesGrid.RowDefinitions.Count - 1); ; ValidTimesGrid.Height += tb.Height; } private string GetFormatedStr(TimeEntry te) { string strFormat = ""; string strAMPM = (te.Hour >= 12) ? SystemDateInfo.PMDesignator : SystemDateInfo.AMDesignator; char AMPMShort = (te.Hour >= 12) ? SystemDateInfo.PMDesignator[TimeCtrlExtensions.Get_t_Idx()] : SystemDateInfo.AMDesignator[TimeCtrlExtensions.Get_t_Idx()]; foreach (FrameworkElement fe in TimeCtrls.Children) strFormat += fe.get_TextFormat(); return string.Format(strFormat, te.Hour, te.Hour.Get12Hour(), te.Minute, te.Second, strAMPM, AMPMShort); } private void CmdBindShowValidTimesExecuted(object sender, ExecutedRoutedEventArgs e) { if (ValidTimesGrid.Background == null) ValidTimesGrid.Background = Brushes.White; ValidTimesGrid.Children.Clear(); ValidTimesGrid.ColumnDefinitions.Clear(); ValidTimesGrid.RowDefinitions.Clear(); var cd = new ColumnDefinition(); ValidTimesGrid.ColumnDefinitions.Add(cd); ValidTimesGrid.Height = 0; AddValidTimeString(" " + ValidTimesName + " ", true); string str; foreach (ValidTimeItem vti in Children) { str = " " + LanguageStrings.From + " " + GetFormatedStr(vti.BeginTime) + " " + LanguageStrings.To + " " + GetFormatedStr(vti.EndTime) + " "; AddValidTimeString(str); } if (Children.Count == 0) AddValidTimeString(" " + NoValidTimesString + " "); ValidTimesPopup.IsOpen = true; } private void AddHMSCtrlContextMenu(TextBox tb) { ContextMenu cmSource = new ContextMenu(); tb.ContextMenu = cmSource; cmSource.PlacementTarget = tb; // Very important line: without this, context menu won't work if cursor not over a TextBox (but will otherwise!) AddHMSCtrlContextMenuItems(tb, ApplicationCommands.Cut, ApplicationCommands.Copy, ApplicationCommands.Paste, TimeCtrlCustomCommands.CopyTime, TimeCtrlCustomCommands.PasteTime); if (UseValidTimes) { TimeCtrlCustomCommands.ShowValidTimes.Text = ValidTimesName; AddHMSCtrlContextMenuItems(tb, TimeCtrlCustomCommands.ShowValidTimes); } CommandBinding CmdBindCut = new CommandBinding(ApplicationCommands.Cut, CmdBindCutExecuted, CmdBindCutCanExecute); tb.CommandBindings.Add(CmdBindCut); CommandBinding CmdBindPaste = new CommandBinding(ApplicationCommands.Paste, CmdBindPasteExecuted, CmdBindPasteCanExecute); tb.CommandBindings.Add(CmdBindPaste); CommandBinding CmdBindCopyTime = new CommandBinding(TimeCtrlCustomCommands.CopyTime, CmdBindCopyTimeExecuted); tb.CommandBindings.Add(CmdBindCopyTime); CommandBinding CmdBindPasteTime = new CommandBinding(TimeCtrlCustomCommands.PasteTime, CmdBindPasteTimeExecuted, CmdBindPasteTimeCanExecute); tb.CommandBindings.Add(CmdBindPasteTime); CommandBinding CmdBindShowValidTimes = new CommandBinding(TimeCtrlCustomCommands.ShowValidTimes, CmdBindShowValidTimesExecuted); tb.CommandBindings.Add(CmdBindShowValidTimes); } private void AddHMSCtrl(HMSType hmsType) { TextBox tb = new TextBox(); tb.set_HMSType(hmsType); tb.set_HMSText(Value); tb.Height = ActualHeight; tb.Margin = new Thickness(0.0); tb.BorderThickness = new Thickness(); tb.Background = Background; tb.Foreground = TextBrush; tb.IsEnabled = IsEnabled; if (hmsType == HMSType.t || hmsType == HMSType.tt) { tb.Focusable = true; tb.AllowDrop = false; tb.IsReadOnly = true; tb.IsUndoEnabled = false; tb.GotKeyboardFocus += new KeyboardFocusChangedEventHandler(tb_tt_GotKeyboardFocus); tb.PreviewMouseLeftButtonDown += new MouseButtonEventHandler(tb_tt_PreviewMouseLeftButtonDown); tb.PreviewKeyDown += new KeyEventHandler(tb_tt_PreviewKeyDown); tb.PreviewTextInput += new TextCompositionEventHandler(tb_tt_PreviewTextInput); } else { tb.PreviewTextInput += new TextCompositionEventHandler(tb_PreviewTextInput); tb.PreviewLostKeyboardFocus += new KeyboardFocusChangedEventHandler(tb_PreviewLostKeyboardFocus); tb.GotKeyboardFocus += new KeyboardFocusChangedEventHandler(tb_GotKeyboardFocus); tb.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(tb_LostKeyboardFocus); tb.PreviewKeyDown += new KeyEventHandler(tb_PreviewKeyDown); tb.PreviewMouseLeftButtonDown += new MouseButtonEventHandler(tb_PreviewMouseLeftButtonDown); tb.PreviewMouseRightButtonDown += new MouseButtonEventHandler(tb_PreviewMouseRightButtonDown); tb.PreviewQueryContinueDrag += new QueryContinueDragEventHandler(tb_PreviewQueryContinueDrag); tb.PreviewDragEnter += new DragEventHandler(tb_PreviewDrag); tb.PreviewDragOver += new DragEventHandler(tb_PreviewDrag); } AddHMSCtrlContextMenu(tb); tb.PreviewMouseWheel += new MouseWheelEventHandler(tb_PreviewMouseWheel); AddGridCtrl(tb); } private void AddString(string str) { TextBlock tb = new TextBlock(); tb.Text = str; tb.Background = Brushes.Transparent; tb.Foreground = TextBrush; tb.Margin = new Thickness(0.0); tb.Height = Height; AddGridCtrl(tb); } void tb_PreviewMouseWheel(object sender, MouseWheelEventArgs e) { // MouseWheel does not work very well. The mouse cursor has to be over the item for it to work. // CodePlex sample does same, which is why I am leaving implementation as such. var tb = sender as TextBox; if (tb != null) { if (e.Delta > 0) ManipulateValue(tb, IncrementValue); else ManipulateValue(tb, DecrementValue); // Following is illegal: !!!!! (would replace 4 lines above) // ManipulateValue(tb, (e.Delta > 0) ? IncrementValue : DecrementValue); tb.Focus(); e.Handled = true; } } void tb_tt_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) { var tb = sender as TextBox; if (tb != null) tb.SelectAll(); } void tb_tt_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) { var tb = sender as TextBox; if (tb != null) { tb.Focus(); e.Handled = true; } } void AM_PM_Handle(TextBox tb) { bool IsAm; if (tb.get_HMSType() == HMSType.tt) IsAm = (tb.Text == SystemDateInfo.AMDesignator); else // tb.get_HMSType() == HMSType.t IsAm = (tb.Text == SystemDateInfo.AMDesignator[TimeCtrlExtensions.Get_t_Idx()].ToString()); Value = Value.Reset_AM_PM_Time(IsAm); tb.SelectAll(); } void AM_PM_Change(TextBox tb) { if (tb.get_HMSType() == HMSType.tt) tb.Text = (tb.Text == SystemDateInfo.AMDesignator) ? SystemDateInfo.PMDesignator : SystemDateInfo.AMDesignator; else // tb.get_HMSType() == HMSType.t { int Idx = TimeCtrlExtensions.Get_t_Idx(); tb.Text = (tb.Text == SystemDateInfo.AMDesignator[Idx].ToString()) ? SystemDateInfo.PMDesignator[Idx].ToString() : SystemDateInfo.AMDesignator[Idx].ToString(); } AM_PM_Handle(tb); } void tb_tt_PreviewKeyDown(object sender, KeyEventArgs e) { var tb = sender as TextBox; if (tb == null) return; if (e.Key == Key.Up || e.Key == Key.Down) { AM_PM_Change(tb); e.Handled = true; } } bool AM_PM_HandleInput(TextBox tb, string InputTxt, string AM_PM_Designator, int Idx) { if (string.Compare(InputTxt, AM_PM_Designator[Idx].ToString(), true) == 0) { if (tb.get_HMSType() == HMSType.tt) tb.Text = AM_PM_Designator; else // tb.get_HMSType() == HMSType.t tb.Text = AM_PM_Designator[Idx].ToString(); AM_PM_Handle(tb); return true; } return false; } void tb_tt_PreviewTextInput(object sender, TextCompositionEventArgs e) { TextBox tb = sender as TextBox; if (tb != null) { int Idx = TimeCtrlExtensions.Get_t_Idx(); if (!AM_PM_HandleInput(tb, e.Text, SystemDateInfo.AMDesignator, Idx)) e.Handled = AM_PM_HandleInput(tb, e.Text, SystemDateInfo.PMDesignator, Idx); else e.Handled = true; } } void tb_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) { var tb = sender as TextBox; if (tb != null && tb.Text == "") tb.set_HMSText(Value); } void tb_PreviewDrag(object sender, DragEventArgs e) { e.Effects = DragDropEffects.None; e.Handled = true; } void tb_PreviewQueryContinueDrag(object sender, QueryContinueDragEventArgs e) { e.Action = DragAction.Cancel; e.Handled = true; } void tb_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e) { MouseClicked = true; } void tb_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) { MouseClicked = true; } private delegate void ValueManipulator(TextBox tb, int NewValue); private int AdjustHalfDayHour(TextBox tb, int CurrentValue) { if (tb.IsHalfDayHour()) { if (CurrentValue == 12) { if (Value.Hour < 12) CurrentValue = 0; } else if (Value.Hour >= 12) CurrentValue += 12; } return CurrentValue; } private void IncrementValue(TextBox tb, int NewValue) { NewValue = (NewValue < tb.get_Max() - 1) ? NewValue + 1 : tb.get_Min(); NewValue = AdjustHalfDayHour(tb, NewValue); Value = Value.ResetTime(NewValue, tb.get_HMSType()); } private void DecrementValue(TextBox tb, int NewValue) { NewValue = (NewValue > tb.get_Min()) ? NewValue - 1 : tb.get_Max() - 1; NewValue = AdjustHalfDayHour(tb, NewValue); Value = Value.ResetTime(NewValue, tb.get_HMSType()); } private void ManipulateValue(TextBox tb, ValueManipulator ValMan) { if (tb.get_HMSType() == HMSType.t || tb.get_HMSType() == HMSType.tt) { AM_PM_Change(tb); return; } int NewValue; if (int.TryParse(tb.Text, out NewValue)) ValMan(tb, NewValue); tb.Focus(); tb.SelectAll(); } void tb_PreviewKeyDown(object sender, KeyEventArgs e) { var tb = sender as TextBox; if (tb == null) return; if (e.Key == Key.Up) { ManipulateValue(tb, IncrementValue); e.Handled = true; } else if (e.Key == Key.Down) { ManipulateValue(tb, DecrementValue); e.Handled = true; } else if (e.Key == Key.Delete || e.Key == Key.Back) { int CurPos = tb.SelectionStart; string Txt = tb.Text; e.Handled = true; if (tb.SelectionLength > 0) Txt = Txt.Remove(CurPos, tb.SelectionLength); else if (e.Key == Key.Delete && CurPos < Txt.Length) { Txt = Txt.Remove(CurPos, 1); if (tb.IsAlways2CharInt()) CurPos++; } else if (e.Key == Key.Back && CurPos > 0) { Txt = Txt.Remove(CurPos - 1, 1); if (!tb.IsAlways2CharInt()) --CurPos; } else e.Handled = false; if (e.Handled) { int CurrentValue; if (ValidateInput(tb, Txt, out CurrentValue)) { Value = Value.ResetTime(CurrentValue, tb.get_HMSType()); tb.SelectionStart = CurPos; } else if (Txt == "" || (Txt == "0" && tb.get_HMSType() == HMSType.hhour)) { tb.SelectionStart = 0; tb.Text = ""; } else e.Handled = false; } } else if (e.Key == Key.Space) // Want to prevent entering spaces. Amazingly, tb_PreviewTextInput not called, even though // tb_PreviewTextInput IS called when enter return key (and e.Text = '\r') ??!!! e.Handled = true; } void tb_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) { var tb = sender as TextBox; if (tb != null && MouseClicked == false) // We do not want to select all when user has clicked on TextBox. // Without the MouseClicked parameter, everything is selected/deselected immediately, which looks ugly. // I agree having this parameter is not the most pretty programming style, but know no better way. tb.SelectAll(); MouseClicked = false; } void tb_PreviewLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) { var tb = sender as TextBox; if (tb != null && e.NewFocus == tb.ContextMenu) { tb.Focus(); tb.ContextMenu.DataContext = tb; e.Handled = true; } } /// <param name="shortHMS">An HMS tag corresponding to 'H', 'h', 'm', 's', 't' </param> /// <param name="longHMS">An HMS tag corresponding to 'HH', 'hh', 'mm', 'ss', 'tt'</param> private int LoadTimeTag(string TimePattern, int Idx, HMSType shortHMS, HMSType longHMS) { if (Idx < TimePattern.Length - 1 && TimePattern[Idx + 1] == TimePattern[Idx]) { AddHMSCtrl(longHMS); Idx++; } else AddHMSCtrl(shortHMS); return Idx; } private int LoadTimeSeparator(string TimePattern, int Idx) { // Assume the separator is something like ':' or '.'. Not considering case when want to use a character normally used // to indicate a time tag. int StartIdx = Idx; while (Idx < TimePattern.Length - 1 && TimePattern[Idx + 1] != 'H' && TimePattern[Idx + 1] != 'h' && TimePattern[Idx + 1] != 'm' && TimePattern[Idx + 1] != 's' && TimePattern[Idx + 1] != 't') Idx++; AddString(TimePattern.Substring(StartIdx, Idx - StartIdx + 1)); return Idx; } private void LoadTimePattern(string TimePattern) { for (int Idx = 0; Idx < TimePattern.Length; Idx++) { switch (TimePattern[Idx]) { case 'H': Idx = LoadTimeTag(TimePattern, Idx, HMSType.Hour, HMSType.HHour); break; case 'h': Idx = LoadTimeTag(TimePattern, Idx, HMSType.hour, HMSType.hhour); break; case 'm': Idx = LoadTimeTag(TimePattern, Idx, HMSType.minute, HMSType.mminute); break; case 's': Idx = LoadTimeTag(TimePattern, Idx, HMSType.second, HMSType.ssecond); break; case 't': Idx = LoadTimeTag(TimePattern, Idx, HMSType.t, HMSType.tt); break; default: Idx = LoadTimeSeparator(TimePattern, Idx); break; } } } private void ReloadTimeCtrlsGrid() { TimeCtrls.Children.Clear(); TimeCtrls.ColumnDefinitions.Clear(); TimeCtrls.RowDefinitions.Clear(); TimeCtrls.RowDefinitions.Add(new RowDefinition()); if (TextAlignment == TextAlignment.Right || TextAlignment == TextAlignment.Center) TimeCtrls.ColumnDefinitions.Add(new ColumnDefinition()); LoadTimePattern(TimePattern); if (TextAlignment == TextAlignment.Left || TextAlignment == TextAlignment.Center) TimeCtrls.ColumnDefinitions.Add(new ColumnDefinition()); } private void Root_Loaded(object sender, RoutedEventArgs e) { ReloadTimeCtrlsGrid(); } private TextBox GetNextTextBox(int Idx) { while (++Idx < TimeCtrls.Children.Count && !(TimeCtrls.Children[Idx] is TextBox)) ; return (Idx < TimeCtrls.Children.Count) ? (TextBox)TimeCtrls.Children[Idx] : null; } void tb_PreviewTextInput(object sender, TextCompositionEventArgs e) { TextBox tb = sender as TextBox; if (tb != null) { int CurrentValue; int CurPos = tb.SelectionStart, SelLen = tb.SelectionLength; string Txt = tb.Text.Remove(CurPos, SelLen); if (Keyboard.GetKeyStates(Key.Insert) == KeyStates.Toggled && CurPos < Txt.Length) Txt = Txt.Remove(CurPos, 1); Txt = Txt.Insert(CurPos, e.Text); // Don't do anything for entries like "003" "012" or "05" (not '0' prefixed) when entry is a '0' only if (!(e.Text == "0" && ((Txt.Length == 3 && Txt[0] == '0' && CurPos == 0) || (!tb.IsAlways2CharInt() && Txt.Length == 2 && Txt[0] == '0'))) && ValidateInput(tb, Txt, out CurrentValue)) { CurrentValue = AdjustHalfDayHour(tb, CurrentValue); Value = Value.ResetTime(CurrentValue, tb.get_HMSType()); tb.SelectionStart = (tb.Text.Length == 1 || (CurPos == 0 && SelLen < 2 && Txt.Length >= 2) || (Txt.Length == 3 && Txt[0] == '0' && CurPos == 1 && SelLen == 0)) ? 1 : 2; } else if (tb.IsHalfDayHour() && (Txt == "0" || Txt == "00")) tb.Text = ""; } e.Handled = true; } private bool ValidateInput(TextBox tb, string Txt, out int CurrentValue) { if (int.TryParse(Txt, out CurrentValue)) return (CurrentValue < tb.get_Max() && CurrentValue >= tb.get_Min()); return false; } private TextBox SetFocusToClosestTextBox() { Point pt; TextBox tbClosest = null; double MinDist = 0; foreach (UIElement ele in TimeCtrls.Children) { var tb = ele as TextBox; if (tb != null) { pt = Mouse.GetPosition(tb); if (tbClosest == null || Math.Abs(pt.X) < MinDist) { tbClosest = tb; MinDist = Math.Abs(pt.X); } } } if (tbClosest != null) { tbClosest.Focus(); tbClosest.CaptureMouse(); } return tbClosest; } private void Root_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { MouseClicked = true; SetFocusToClosestTextBox(); } private void Root_MouseRightButtonDown(object sender, MouseButtonEventArgs e) { MouseClicked = true; TextBox tb = SetFocusToClosestTextBox(); if (tb != null) { tb.ContextMenu.IsOpen = true; e.Handled = true; } } private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = false; e.Handled = true; } private TextBox GetTextBoxToFocusOn() { var tb = FocusManager.GetFocusedElement(this) as TextBox; if (tb == null) tb = GetNextTextBox(-1); return tb; } private void UpDown_UpClick(object sender, RoutedEventArgs e) { var tb = GetTextBoxToFocusOn(); if (tb != null) ManipulateValue(tb, IncrementValue); } private void UpDown_DownClick(object sender, RoutedEventArgs e) { var tb = GetTextBoxToFocusOn(); if (tb != null) ManipulateValue(tb, DecrementValue); } private void Root_IsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e) { foreach (FrameworkElement fe in TimeCtrls.Children) { if (fe is TextBox) { ((TextBox)fe).IsEnabled = (bool)e.NewValue; ((TextBox)fe).Foreground = TextBrush; } else if (fe is TextBlock) ((TextBlock)fe).Foreground = TextBrush; } } } }
GlobalcachingEU/GAPP
GAPPSF/UIControls/UpDownCtrls/TimeCtrl.xaml.cs
C#
mit
35,541
/* * The MIT License * * Copyright (c) 2015, Mahmoud Ben Hassine (mahmoud@benhassine.fr) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.easybatch.integration.apache.common.csv; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVRecord; import org.easybatch.core.api.Record; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.io.StringReader; import static org.assertj.core.api.Assertions.assertThat; /** * Test class for {@link ApacheCommonCsvRecordReader}. * * @author Mahmoud Ben Hassine (mahmoud@benhassine.fr) */ public class ApacheCommonCsvRecordReaderTest { private ApacheCommonCsvRecordReader recordReader; @Before public void setUp() throws Exception { StringReader stringReader = new StringReader("foo,bar,15,true"); CSVFormat csvFormat = CSVFormat.DEFAULT.withHeader("firstName", "lastName", "age", "married"); CSVParser parser = new CSVParser(stringReader, csvFormat); recordReader = new ApacheCommonCsvRecordReader(parser); recordReader.open(); } @Test public void testHasNextRecord() throws Exception { Assert.assertTrue(recordReader.hasNextRecord()); } @Test public void testReadNextRecord() throws Exception { recordReader.hasNextRecord(); Record record = recordReader.readNextRecord(); assertThat(record).isNotNull().isInstanceOf(ApacheCommonCsvRecord.class); ApacheCommonCsvRecord apacheCommonCsvRecord = (ApacheCommonCsvRecord) record; assertThat(apacheCommonCsvRecord.getHeader()).isNotNull(); assertThat(apacheCommonCsvRecord.getHeader().getNumber()).isEqualTo(1); CSVRecord csvRecord = apacheCommonCsvRecord.getPayload(); assertThat(csvRecord.get("firstName")).isEqualTo("foo"); assertThat(csvRecord.get("lastName")).isEqualTo("bar"); assertThat(csvRecord.get("age")).isEqualTo("15"); assertThat(csvRecord.get("married")).isEqualTo("true"); } @After public void tearDown() throws Exception { recordReader.close(); } }
dmullins78/easybatch-framework
easybatch-integration/easybatch-apache-commons-csv/src/test/java/org/easybatch/integration/apache/common/csv/ApacheCommonCsvRecordReaderTest.java
Java
mit
3,254
""" Module. Includes classes for all time dependent lattice. """ import sys import os import math from orbit.teapot import TEAPOT_Lattice from orbit.parsers.mad_parser import MAD_Parser, MAD_LattLine from orbit.lattice import AccNode, AccActionsContainer from orbit.time_dep import waveform class TIME_DEP_Lattice(TEAPOT_Lattice): """ The subclass of the TEAPOT_Lattice. TIME_DEP_Lattice has the ability to set time dependent parameters to the Lattice. Multi-turn track also available. """ def __init__(self, name = "no name"): TEAPOT_Lattice.__init__(self,name) self.__latticeDict = {} self.__TDNodeDict = {} self.__turns = 1 def setLatticeOrder(self): """ Sets the time dependent lattice names to the lattice. """ accNodes = self.getNodes() elemInLine = {} for i in range(len(accNodes)): elem = accNodes[i] elemname = elem.getName() if(elemInLine.has_key(elemname)): elemInLine[elemname] += 1 else: elemInLine[elemname] = 1 node = self.getNodes()[i] node.setParam("TPName",node.getName()+"_"+str(elemInLine[elemname])) #node.setParam("sequence",i+1) #print "debug node",node.getName(),node.getParamsDict() def setTimeDepNode(self, TPName, waveform): """ Sets the waveform function to the TP node before track. """ flag = 0 for node in self.getNodes(): if (TPName == node.getParam("TPName")): flag = 1 node.setParam("waveform",waveform) self.__TDNodeDict[TPName] = node if not flag: print "The",TPName,"is not found." sys.exit(1) def setTimeDepStrength(self, time): """ Set strength to the TP node while running. """ NodeDict = self.__TDNodeDict for i in NodeDict.keys(): node = NodeDict[i] waveform = node.getParam("waveform") waveform.calc(time) waveformType = waveform.getType() if waveformType == "kicker waveform": if node.getType() == "kick teapot": self.setParam(node,"kx",waveform.getKx()) self.setParam(node,"ky",waveform.getKy()) else: print "No kicker waveform added. Please check node type." elif waveformType == "magnet waveform": strength = waveform.getStrength() if node.getType() == "multipole teapot": self.setParam(node,"kls",strength) elif node.getType() == "quad teapot": self.setParam(node,"kls",strength) self.setParam(node,"kq",strength) elif node.getType() == "solenoid teapot": self.setParam(node,"B",strength) else: print "No magnet waveform added. Please check node type." def setParam(self, node, Kparam, strength): if node.hasParam(Kparam): paramval = node.getParam(Kparam) if Kparam == "kls": newparamval = [] for i in range(len(paramval)): newparamval.append(paramval[i]*strength) paramval = newparamval else:paramval = paramval*strength node.setParam(Kparam,paramval) def trackBunchTurns(self, bunch): """ It tracks the bunch through the lattice with multi-turn. """ turns = self.__turns #start for i in range(turns-1): self.trackBunch(bunch) syncPart = bunch.getSyncParticle() time = syncPart.time() self.setTimeDepStrength(time) print "debug trackBunchTurns time",time,"in",i,"turn" #getsublattice #sublattice.trackBunch(bunch) def setTurns(self, turns, startPosition = 0, endPosition = -1): """ Sets the turns and start end position before track. """ startNode = StartNode("start node") endNode = EndNode("end node") self.addNode(startNode, startPosition) self.addNode(endNode, endPosition) self.__turns = turns #print self.getNodes() class StartNode(AccNode): def __init__(self, name = "no name"): AccNode.__init__(self,name) self.setType("start node") def track(self, paramsDict): bunch = paramsDict["bunch"] #bunch.getSyncParticle().time(0.) class EndNode(AccNode): def __init__(self, name = "no name"): AccNode.__init__(self,name) self.setType("end node") def track(self, paramsDict): pass
PyORBIT-Collaboration/py-orbit
py/orbit/time_dep/time_dep.py
Python
mit
4,174
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // // This is used internally to create best fit behavior as per the original windows best fit behavior. // using System; using System.Globalization; using System.Text; using System.Threading; using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.Text { [Serializable] internal class InternalEncoderBestFitFallback : EncoderFallback { // Our variables internal Encoding encoding = null; internal char[] arrayBestFit = null; internal InternalEncoderBestFitFallback(Encoding encoding) { // Need to load our replacement characters table. this.encoding = encoding; this.bIsMicrosoftBestFitFallback = true; } public override EncoderFallbackBuffer CreateFallbackBuffer() { return new InternalEncoderBestFitFallbackBuffer(this); } // Maximum number of characters that this instance of this fallback could return public override int MaxCharCount { get { return 1; } } public override bool Equals(Object value) { InternalEncoderBestFitFallback that = value as InternalEncoderBestFitFallback; if (that != null) { return (this.encoding.CodePage == that.encoding.CodePage); } return (false); } public override int GetHashCode() { return this.encoding.CodePage; } } internal sealed class InternalEncoderBestFitFallbackBuffer : EncoderFallbackBuffer { // Our variables private char cBestFit = '\0'; private InternalEncoderBestFitFallback oFallback; private int iCount = -1; private int iSize; // Private object for locking instead of locking on a public type for SQL reliability work. private static Object s_InternalSyncObject; private static Object InternalSyncObject { get { if (s_InternalSyncObject == null) { Object o = new Object(); Interlocked.CompareExchange<Object>(ref s_InternalSyncObject, o, null); } return s_InternalSyncObject; } } // Constructor public InternalEncoderBestFitFallbackBuffer(InternalEncoderBestFitFallback fallback) { oFallback = fallback; if (oFallback.arrayBestFit == null) { // Lock so we don't confuse ourselves. lock (InternalSyncObject) { // Double check before we do it again. if (oFallback.arrayBestFit == null) oFallback.arrayBestFit = fallback.encoding.GetBestFitUnicodeToBytesData(); } } } // Fallback methods public override bool Fallback(char charUnknown, int index) { // If we had a buffer already we're being recursive, throw, it's probably at the suspect // character in our array. // Shouldn't be able to get here for all of our code pages, table would have to be messed up. Debug.Assert(iCount < 1, "[InternalEncoderBestFitFallbackBuffer.Fallback(non surrogate)] Fallback char " + ((int)cBestFit).ToString("X4", CultureInfo.InvariantCulture) + " caused recursive fallback"); iCount = iSize = 1; cBestFit = TryBestFit(charUnknown); if (cBestFit == '\0') cBestFit = '?'; return true; } public override bool Fallback(char charUnknownHigh, char charUnknownLow, int index) { // Double check input surrogate pair if (!Char.IsHighSurrogate(charUnknownHigh)) throw new ArgumentOutOfRangeException(nameof(charUnknownHigh), Environment.GetResourceString("ArgumentOutOfRange_Range", 0xD800, 0xDBFF)); if (!Char.IsLowSurrogate(charUnknownLow)) throw new ArgumentOutOfRangeException(nameof(charUnknownLow), Environment.GetResourceString("ArgumentOutOfRange_Range", 0xDC00, 0xDFFF)); Contract.EndContractBlock(); // If we had a buffer already we're being recursive, throw, it's probably at the suspect // character in our array. 0 is processing last character, < 0 is not falling back // Shouldn't be able to get here, table would have to be messed up. Debug.Assert(iCount < 1, "[InternalEncoderBestFitFallbackBuffer.Fallback(surrogate)] Fallback char " + ((int)cBestFit).ToString("X4", CultureInfo.InvariantCulture) + " caused recursive fallback"); // Go ahead and get our fallback, surrogates don't have best fit cBestFit = '?'; iCount = iSize = 2; return true; } // Default version is overridden in EncoderReplacementFallback.cs public override char GetNextChar() { // We want it to get < 0 because == 0 means that the current/last character is a fallback // and we need to detect recursion. We could have a flag but we already have this counter. iCount--; // Do we have anything left? 0 is now last fallback char, negative is nothing left if (iCount < 0) return '\0'; // Need to get it out of the buffer. // Make sure it didn't wrap from the fast count-- path if (iCount == int.MaxValue) { iCount = -1; return '\0'; } // Return the best fit character return cBestFit; } public override bool MovePrevious() { // Exception fallback doesn't have anywhere to back up to. if (iCount >= 0) iCount++; // Return true if we could do it. return (iCount >= 0 && iCount <= iSize); } // How many characters left to output? public override int Remaining { get { return (iCount > 0) ? iCount : 0; } } // Clear the buffer public override unsafe void Reset() { iCount = -1; charStart = null; bFallingBack = false; } // private helper methods private char TryBestFit(char cUnknown) { // Need to figure out our best fit character, low is beginning of array, high is 1 AFTER end of array int lowBound = 0; int highBound = oFallback.arrayBestFit.Length; int index; // Binary search the array int iDiff; while ((iDiff = (highBound - lowBound)) > 6) { // Look in the middle, which is complicated by the fact that we have 2 #s for each pair, // so we don't want index to be odd because we want to be on word boundaries. // Also note that index can never == highBound (because diff is rounded down) index = ((iDiff / 2) + lowBound) & 0xFFFE; char cTest = oFallback.arrayBestFit[index]; if (cTest == cUnknown) { // We found it Debug.Assert(index + 1 < oFallback.arrayBestFit.Length, "[InternalEncoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array"); return oFallback.arrayBestFit[index + 1]; } else if (cTest < cUnknown) { // We weren't high enough lowBound = index; } else { // We weren't low enough highBound = index; } } for (index = lowBound; index < highBound; index += 2) { if (oFallback.arrayBestFit[index] == cUnknown) { // We found it Debug.Assert(index + 1 < oFallback.arrayBestFit.Length, "[InternalEncoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array"); return oFallback.arrayBestFit[index + 1]; } } // Char wasn't in our table return '\0'; } } }
sjsinju/coreclr
src/mscorlib/src/System/Text/EncoderBestFitFallback.cs
C#
mit
8,893
'use strict'; var Pagelet = require('pagelet') , async = require('async') , path = require('path'); Pagelet.extend({ view: 'view.ejs', css: 'css.styl', js: 'client.js', // // Allow FORM submits to be streaming. // streaming: true, // // Force a name. // name: 'service-select', // // What data needs to be synced with the front-end. // query: ['services'], pagelets: { target: Pagelet.extend({ view: 'target.ejs', streaming: true }).on(module) }, // // External dependencies that should be included on the page using a regular // script tag. This dependency is needed for the `package.js` client file. // dependencies: [ path.join(__dirname, '/selectize.default.css'), '//code.jquery.com/jquery-2.1.0.min.js', path.join(__dirname, '/selectize.js') ], /** * Respond to POST requests. * * @param {Object} fields The input fields. * @param {Object} files Optional uploaded files. * @param {Function} next Completion callback. * @api public */ post: function post(fields, files, next) { if ('delete' in fields) { this.remove(fields, next); } else if ('add' in fields) { this.add(fields, next); } else { next(new Error('Invalid form data')); } }, /** * Called when a new service has to be added. * * @param {Object} data The data to add. * @param {FUnction} next Continuation function. * @api public */ add: function add(data, next) { throw new Error([ 'You, as a developer need to implement the `.add` method of the service', 'select pagelet. If you dont know how to do this, see the documenation', 'about Pagelet.extend({});' ].join(' ')); }, /** * A service has been removed from the UI. * * @param {Object} data The data containing the info about the service */ remove: function remove(data, next) { throw new Error([ 'You, as a developer need to implement the `.remove` method of the service', 'select pagelet. If you dont know how to do this, see the documenation', 'about Pagelet.extend({});' ].join(' ')); }, /** * The available services that should be listed in the UI. * * @param {Function} next Continuation callback * @api public */ services: function services(next) { throw new Error([ 'You, as a developer need to implement the `.services` method of the service', 'select pagelet. If you dont know how to do this, see the documenation', 'about Pagelet.extend({});' ].join(' ')); }, /** * List of added services that should be displayed in the UI. * * @param {Fucntion} next Continuation callback. * @api public */ added: function added(next) { throw new Error([ 'You, as a developer need to implement the `.added` method of the service', 'select pagelet. If you dont know how to do this, see the documenation', 'about Pagelet.extend({});' ].join(' ')); }, /** * Render the HTML things. * * @param {Function} done Continuation callback. * @api public */ get: function get(done) { var pagelet = this; async.parallel({ services: this.services.bind(this), added: this.added.bind(this) }, function completed(err, data) { if (err) return done(err); data.services = data.services || []; data.added = data.added || []; ['services', 'added'].forEach(function transform(key) { if (Array.isArray(data[key])) return; data[key] = Object.keys(data[key]).map(function map(name) { var thing = data[key][name]; thing.name = thing.name || name; return thing; }); }); data.description = pagelet.description; data.name = pagelet.name.replace('-', ' '); data.name = data.name.slice(0, 1).toUpperCase() + data.name.slice(1); done(err, data); }); } }).on(module);
nodejitsu/service-select
index.js
JavaScript
mit
3,961
#region Licence /* The MIT License (MIT) Copyright © 2015 Ian Cooper <ian_hammond_cooper@yahoo.co.uk> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endregion using System; namespace Paramore.Brighter.Core.Tests.CommandProcessors.TestDoubles { class MyPostLoggingHandlerAsyncAttribute : RequestHandlerAttribute { public MyPostLoggingHandlerAsyncAttribute(int step, HandlerTiming timing) : base(step, timing) { } public override Type GetHandlerType() { return typeof(MyLoggingHandlerAsync<>); } } }
BrighterCommand/Brighter
tests/Paramore.Brighter.Core.Tests/CommandProcessors/TestDoubles/MyPostLoggingHandlerAsyncAttribute.cs
C#
mit
1,576
using System; using System.Collections.Generic; using System.Windows.Forms; namespace DotMaysWind.Data.Test { static class Program { /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); } } }
GuanLee1990/DotMaysWind.Data
DotMaysWind.Data.Test/Program.cs
C#
mit
465
using System; using Fluky.Extensions; using Fluky.Types; namespace Fluky { public partial class Randomizer { public float DistributionNormal(float mean, float standardDeviation) { // Get random normal from Standard Normal Distribution var randomNormalNumber = DistributionStandardNormal(); // Stretch distribution to the requested sigma variance randomNormalNumber *= standardDeviation; // Shift mean to requested mean: randomNormalNumber += mean; // now you have a number selected from a normal distribution with requested mean and sigma! return randomNormalNumber; } public float DistributionStandardNormal() { // This code follows the polar form of the muller transform: // https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform#Polar_form // also known as Marsaglia polar method // https://en.wikipedia.org/wiki/Marsaglia_polar_method // calculate points on a circle float u, v; float s; // this is the hypotenuse squared. do { u = Float(-1, 1); v = Float(-1, 1); s = (u * u) + (v * v); } while (!(Math.Abs(s) > 0.001f && s < 1)); // keep going until s is nonzero and less than one // TODO: allow a user to specify how many random numbers they want! // choose between u and v for seed (z0 vs z1) var seed = Integer(0, 2) == 0 ? u : v; // create normally distributed number. var z = (seed * Math.Sqrt(-2.0f * Math.Log(s) / s)); var result = z.ToFloat(); return result; } //-------------------------------------------------------------------------------------------- // Sloped Distribution //-------------------------------------------------------------------------------------------- public float DistributionRangeSlope(float min, float max, float skew, DistributionDirection direction) { return min + DistributionSloped(skew, direction) * (max - min); } public float DistributionSloped(float skew, DistributionDirection direction) { // the difference in scale is just the same as the max y-value.. var maxY = skew; // our curve will go from 0 to max_x. var maxX = Inverse_Sec_Sqrd(maxY); var maxCdf = Sec_Sqrd_CumulativeDistributionFunction(maxX); var u = Float(0, maxCdf); var xVal = Sec_Sqrd_InverseCumulativeDistributionFunction(u); // scale to [0,1] var value = xVal / maxX; if (direction == DistributionDirection.Left) value = 1.0f - value; return value; } //-------------------------------------------------------------------------------------------- // Linear Distribution //-------------------------------------------------------------------------------------------- // Returns random in range [min, max] with linear distribution of given slope. public float DistributionRangeLinear(float min, float max, float slope) { var val = DistributionRandomLinear(slope); return min + (max - min) * val; } // Returns random in range [0,1] with linear distribution of given slope. public float DistributionRandomLinear(float slope) { var absValue = DistributionLinearWithPositiveSlope(Math.Abs(slope)); if (slope < 0) return 1 - absValue; return absValue; } private float DistributionLinearWithPositiveSlope(float slope) { if (Math.Abs(slope) < 0.001f) return Float(0.0f, 1.0f); float x, y; do { x = Float(0.0f, 1.0f); y = Float(0.0f, 1.0f); if (slope < 1) { y -= (1 - slope) / 2.0f; } } while (y > x * slope); return x; } //-------------------------------------------------------------------------------------------- // Exponential Distribution //-------------------------------------------------------------------------------------------- public float DistributionExponentialRange(float min, float max, float exponent, DistributionDirection direction) { return min + DistributionExponential(exponent, direction) * (max - min); } public float DistributionExponential(float exponent, DistributionDirection direction) { // our curve will go from 0 to 1. var maxCdf = ExponentialRightCdf(1.0f, exponent); var u = Float(0.0f, maxCdf); var xVal = EponentialRightInverseCDF(u, exponent); if (direction == DistributionDirection.Left) xVal = 1.0f - xVal; return xVal; } // The inverse of the curve. private float DistributionExponentialRightInverse(float y, float exponent) { return Math.Pow(y, 1.0f / exponent).ToFloat(); } // The integral of the exponent curve. private static float ExponentialRightCdf(float x, float exponent) { var integralExp = exponent + 1.0f; var exponentialRightCdf = (Math.Pow(x, integralExp)) / integralExp; return exponentialRightCdf.ToFloat(); } // The inverse of the integral of the exponent curve. private static float EponentialRightInverseCDF(float x, float exponent) { var integralExp = exponent + 1.0f; return Math.Pow(integralExp * x, 1.0f / integralExp).ToFloat(); } /// <summary> /// The inverse of the sec^2 function. /// </summary> /// <param name="y">The y coordinate. if y < 1, returns NaN. </param> private float Inverse_Sec_Sqrd(float y) { // Note: arcsec(x) = arccos(1/x) // return arcsec(sqrt(y)) var inverseSecSqrd = Math.Acos(1.0f / Math.Sqrt(y)); return inverseSecSqrd.ToFloat(); } /// <summary> /// The integral of sec^2 /// </summary> /// <param name="x"></param> /// <returns></returns> private static float Sec_Sqrd_CumulativeDistributionFunction(float x) { // The cumulative distribution function for sec^2 is just the definite integral of sec^2(x) = tan(x) - tan(0) = tan(x) return Math.Tan(x).ToFloat(); } /// <summary> /// The inverse of the integral of sec^2 /// </summary> /// <param name="x"></param> /// <returns></returns> private static float Sec_Sqrd_InverseCumulativeDistributionFunction(float x) { // The cumulative distribution function for sec^2 is just the definite integral of sec^2(x) = tan(x) - tan(0) = tan(x) // Then the Inverse cumulative distribution function is just atan(x) return Math.Atan(x).ToFloat(); } } }
michaeljbaird/Fluky
src/Fluky/Randomizer.Distribution.cs
C#
mit
6,560
/* * The MIT License * * Copyright (c) 2019 CloudBees, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.cloudbees.plugins.credentials.builds; import com.cloudbees.plugins.credentials.CredentialsParameterDefinition; import com.cloudbees.plugins.credentials.CredentialsParameterValue; import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.CredentialsScope; import com.cloudbees.plugins.credentials.common.IdCredentials; import com.cloudbees.plugins.credentials.domains.Domain; import com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl; import hudson.model.Cause; import hudson.model.CauseAction; import hudson.model.ParametersAction; import hudson.model.ParametersDefinitionProperty; import hudson.model.User; import hudson.model.queue.QueueTaskFuture; import hudson.security.ACL; import hudson.security.ACLContext; import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition; import org.jenkinsci.plugins.workflow.cps.replay.ReplayAction; import org.jenkinsci.plugins.workflow.job.WorkflowJob; import org.jenkinsci.plugins.workflow.job.WorkflowRun; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; import java.util.UUID; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; public class CredentialsParameterBinderReplayActionIntegrationTest { private static final String PARAMETER_NAME = "parameterName"; @Rule public JenkinsRule j = new JenkinsRule(); private String credentialsId; @Before public void setUp() throws Exception { j.jenkins.setSecurityRealm(j.createDummySecurityRealm()); final User alpha = User.getById("alpha", true); try (ACLContext ignored = ACL.as(alpha)) { credentialsId = UUID.randomUUID().toString(); CredentialsProvider.lookupStores(alpha).iterator().next() .addCredentials(Domain.global(), new UsernamePasswordCredentialsImpl( CredentialsScope.USER, credentialsId, null, "user", "pass")); } } @Test public void replayActionShouldNotCopyCredentialsParameterBindingUserIds() throws Exception { final WorkflowJob job = j.createProject(WorkflowJob.class); job.addProperty(new ParametersDefinitionProperty(new CredentialsParameterDefinition( PARAMETER_NAME, null, null, IdCredentials.class.getName(), true))); job.setDefinition(new CpsFlowDefinition("echo 'hello, world'", true)); final WorkflowRun run = j.assertBuildStatusSuccess(job.scheduleBuild2(0, new CauseAction(new Cause.UserIdCause("alpha")), new ParametersAction(new CredentialsParameterValue(PARAMETER_NAME, credentialsId, null)) )); final CredentialsParameterBinding original = CredentialsParameterBinder.getOrCreate(run).forParameterName(PARAMETER_NAME); assertNotNull(original); assertEquals("alpha", original.getUserId()); assertNotNull(CredentialsProvider.findCredentialById(PARAMETER_NAME, IdCredentials.class, run)); final User beta = User.getById("beta", true); final WorkflowRun replayedRun = replayRunAs(run, beta); final CredentialsParameterBinding replayed = CredentialsParameterBinder.getOrCreate(replayedRun).forParameterName(PARAMETER_NAME); assertNotNull(replayed); assertEquals("beta", replayed.getUserId()); assertNull(CredentialsProvider.findCredentialById(PARAMETER_NAME, IdCredentials.class, replayedRun)); } @SuppressWarnings("unchecked") private WorkflowRun replayRunAs(WorkflowRun run, User user) throws Exception { final ReplayAction replay = run.getAction(ReplayAction.class); assertNotNull(replay); final QueueTaskFuture<WorkflowRun> futureRun; try (ACLContext ignored = ACL.as(user)) { futureRun = replay.run(replay.getOriginalScript(), replay.getOriginalLoadedScripts()); } return j.assertBuildStatusSuccess(futureRun); } }
jenkinsci/credentials-plugin
src/test/java/com/cloudbees/plugins/credentials/builds/CredentialsParameterBinderReplayActionIntegrationTest.java
Java
mit
5,191
export * from './card-demo.component';
blackbaud/skyux2
src/demos/card/index.ts
TypeScript
mit
39
function listEvent(login, userCity, done, fail, always) { done = typeof done !== 'undefined' ? done : function() { }; fail = typeof fail !== 'undefined' ? fail : function() { }; always = typeof always !== 'undefined' ? always : function() { }; $.ajax({ url : 'rest/event/' + login + '/' + userCity, type : 'GET' }).done(done).fail(fail).always(always); } function joinEvent(login, eventId, done, fail, always) { done = typeof done !== 'undefined' ? done : function() { }; fail = typeof fail !== 'undefined' ? fail : function() { }; always = typeof always !== 'undefined' ? always : function() { }; $.ajax({ url : 'rest/event/' + eventId + '/' + login, type : 'POST' }).done(done).fail(fail).always(always); }
michada/HYS2
DAAExample-master/src/main/webapp/js/dao/event.js
JavaScript
mit
737
require 'fileutils' require 'simplecov' SimpleCov.start def fixture *args File.join File.dirname(__FILE__), "fixtures", *args end def directory path full = fixture(path) FileUtils::mkdir_p full return full end def file *args file = File.join(*args[0..-2]) directory File.dirname(file) File.open(file, 'w') {|f| f.write args[-1] } return file end def rm path FileUtils::rm_rf path end RSpec::Matchers.define :match_stdout do |check| @capture = nil match do |block| begin stdout_saved = $stdout $stdout = StringIO.new block.call ensure @capture = $stdout $stdout = stdout_saved end @capture.string.match check end failure_message do "expected to #{description}" end failure_message_when_negated do "expected not to #{description}" end description do "match [#{check}] on stdout [#{@capture.string}]" end end
clarete/s3sync
spec/spec_helper.rb
Ruby
mit
912
// Copyright (c) 2007-2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "amount.h" #include "chain.h" #include "chainparams.h" #include "checkpoints.h" #include "checkpointsync.h" #include "coins.h" #include "consensus/validation.h" #include "validation.h" #include "policy/policy.h" #include "primitives/transaction.h" #include "rpc/server.h" #include "streams.h" #include "sync.h" #include "txmempool.h" #include "util.h" #include "utilstrencodings.h" #include "hash.h" #include <stdint.h> #include <univalue.h> #include <boost/thread/thread.hpp> // boost::thread::interrupt #include <mutex> #include <condition_variable> using namespace std; struct CUpdatedBlock { uint256 hash; int height; }; static std::mutex cs_blockchange; static std::condition_variable cond_blockchange; static CUpdatedBlock latestblock; extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry); void ScriptPubKeyToJSON(const CScript& scriptPubKey, UniValue& out, bool fIncludeHex); double GetDifficulty(const CBlockIndex* blockindex) { // Floating point number that is a multiple of the minimum difficulty, // minimum difficulty = 1.0. if (blockindex == NULL) { if (chainActive.Tip() == NULL) return 1.0; else blockindex = chainActive.Tip(); } int nShift = (blockindex->nBits >> 24) & 0xff; double dDiff = (double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff); while (nShift < 29) { dDiff *= 256.0; nShift++; } while (nShift > 29) { dDiff /= 256.0; nShift--; } return dDiff; } UniValue blockheaderToJSON(const CBlockIndex* blockindex) { UniValue result(UniValue::VOBJ); result.push_back(Pair("hash", blockindex->GetBlockHash().GetHex())); int confirmations = -1; // Only report confirmations if the block is on the main chain if (chainActive.Contains(blockindex)) confirmations = chainActive.Height() - blockindex->nHeight + 1; result.push_back(Pair("confirmations", confirmations)); result.push_back(Pair("height", blockindex->nHeight)); result.push_back(Pair("version", blockindex->nVersion)); result.push_back(Pair("versionHex", strprintf("%08x", blockindex->nVersion))); result.push_back(Pair("merkleroot", blockindex->hashMerkleRoot.GetHex())); result.push_back(Pair("time", (int64_t)blockindex->nTime)); result.push_back(Pair("mediantime", (int64_t)blockindex->GetMedianTimePast())); result.push_back(Pair("nonce", (uint64_t)blockindex->nNonce)); result.push_back(Pair("bits", strprintf("%08x", blockindex->nBits))); result.push_back(Pair("difficulty", GetDifficulty(blockindex))); result.push_back(Pair("chainwork", blockindex->nChainWork.GetHex())); if (blockindex->pprev) result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex())); CBlockIndex *pnext = chainActive.Next(blockindex); if (pnext) result.push_back(Pair("nextblockhash", pnext->GetBlockHash().GetHex())); return result; } UniValue blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool txDetails = false, bool fQueuedBlock = false) { UniValue result(UniValue::VOBJ); result.push_back(Pair("hash", !fQueuedBlock ? blockindex->GetBlockHash().GetHex() : block.GetHash().GetHex())); int confirmations = -1; // Only report confirmations if the block is on the main chain if (chainActive.Contains(blockindex)) confirmations = chainActive.Height() - blockindex->nHeight + 1; result.push_back(Pair("confirmations", confirmations)); result.push_back(Pair("strippedsize", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS))); result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS))); result.push_back(Pair("height", fQueuedBlock ? blockindex->nHeight+1 : blockindex->nHeight)); result.push_back(Pair("version", block.nVersion)); result.push_back(Pair("versionHex", strprintf("%08x", block.nVersion))); result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex())); UniValue txs(UniValue::VARR); for(const auto& tx : block.vtx) { if(txDetails) { UniValue objTx(UniValue::VOBJ); TxToJSON(*tx, uint256(), objTx); txs.push_back(objTx); } else txs.push_back(tx->GetHash().GetHex()); } result.push_back(Pair("tx", txs)); result.push_back(Pair("time", block.GetBlockTime())); result.push_back(Pair("mediantime", blockindex->GetMedianTimePast())); result.push_back(Pair("nonce", (uint64_t)block.nNonce)); result.push_back(Pair("bits", strprintf("%08x", block.nBits))); result.push_back(Pair("difficulty", GetDifficulty(blockindex))); result.push_back(Pair("chainwork", blockindex ? blockindex->nChainWork.GetHex() : 0)); if (!fQueuedBlock && blockindex->pprev) result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex())); else result.push_back(Pair("previousblockhash", blockindex->GetBlockHash().GetHex())); if (!fQueuedBlock) { CBlockIndex *pnext = chainActive.Next(blockindex); if (pnext) result.push_back(Pair("nextblockhash", pnext->GetBlockHash().GetHex())); } return result; } UniValue getblockcount(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 0) throw runtime_error( "getblockcount\n" "\nReturns the number of blocks in the longest blockchain.\n" "\nResult:\n" "n (numeric) The current block count\n" "\nExamples:\n" + HelpExampleCli("getblockcount", "") + HelpExampleRpc("getblockcount", "") ); LOCK(cs_main); return chainActive.Height(); } UniValue getbestblockhash(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 0) throw runtime_error( "getbestblockhash\n" "\nReturns the hash of the best (tip) block in the longest blockchain.\n" "\nResult:\n" "\"hex\" (string) the block hash hex encoded\n" "\nExamples:\n" + HelpExampleCli("getbestblockhash", "") + HelpExampleRpc("getbestblockhash", "") ); LOCK(cs_main); return chainActive.Tip()->GetBlockHash().GetHex(); } void RPCNotifyBlockChange(bool ibd, const CBlockIndex * pindex) { if(pindex) { std::lock_guard<std::mutex> lock(cs_blockchange); latestblock.hash = pindex->GetBlockHash(); latestblock.height = pindex->nHeight; } cond_blockchange.notify_all(); } UniValue waitfornewblock(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() > 1) throw runtime_error( "waitfornewblock (timeout)\n" "\nWaits for a specific new block and returns useful info about it.\n" "\nReturns the current block on timeout or exit.\n" "\nArguments:\n" "1. timeout (int, optional, default=0) Time in milliseconds to wait for a response. 0 indicates no timeout.\n" "\nResult:\n" "{ (json object)\n" " \"hash\" : { (string) The blockhash\n" " \"height\" : { (int) Block height\n" "}\n" "\nExamples:\n" + HelpExampleCli("waitfornewblock", "1000") + HelpExampleRpc("waitfornewblock", "1000") ); int timeout = 0; if (request.params.size() > 0) timeout = request.params[0].get_int(); CUpdatedBlock block; { std::unique_lock<std::mutex> lock(cs_blockchange); block = latestblock; if(timeout) cond_blockchange.wait_for(lock, std::chrono::milliseconds(timeout), [&block]{return latestblock.height != block.height || latestblock.hash != block.hash || !IsRPCRunning(); }); else cond_blockchange.wait(lock, [&block]{return latestblock.height != block.height || latestblock.hash != block.hash || !IsRPCRunning(); }); block = latestblock; } UniValue ret(UniValue::VOBJ); ret.push_back(Pair("hash", block.hash.GetHex())); ret.push_back(Pair("height", block.height)); return ret; } UniValue waitforblock(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) throw runtime_error( "waitforblock <blockhash> (timeout)\n" "\nWaits for a specific new block and returns useful info about it.\n" "\nReturns the current block on timeout or exit.\n" "\nArguments:\n" "1. \"blockhash\" (required, string) Block hash to wait for.\n" "2. timeout (int, optional, default=0) Time in milliseconds to wait for a response. 0 indicates no timeout.\n" "\nResult:\n" "{ (json object)\n" " \"hash\" : { (string) The blockhash\n" " \"height\" : { (int) Block height\n" "}\n" "\nExamples:\n" + HelpExampleCli("waitforblock", "\"0000000000079f8ef3d2c688c244eb7a4570b24c9ed7b4a8c619eb02596f8862\", 1000") + HelpExampleRpc("waitforblock", "\"0000000000079f8ef3d2c688c244eb7a4570b24c9ed7b4a8c619eb02596f8862\", 1000") ); int timeout = 0; uint256 hash = uint256S(request.params[0].get_str()); if (request.params.size() > 1) timeout = request.params[1].get_int(); CUpdatedBlock block; { std::unique_lock<std::mutex> lock(cs_blockchange); if(timeout) cond_blockchange.wait_for(lock, std::chrono::milliseconds(timeout), [&hash]{return latestblock.hash == hash || !IsRPCRunning();}); else cond_blockchange.wait(lock, [&hash]{return latestblock.hash == hash || !IsRPCRunning(); }); block = latestblock; } UniValue ret(UniValue::VOBJ); ret.push_back(Pair("hash", block.hash.GetHex())); ret.push_back(Pair("height", block.height)); return ret; } UniValue waitforblockheight(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) throw runtime_error( "waitforblockheight <height> (timeout)\n" "\nWaits for (at least) block height and returns the height and hash\n" "of the current tip.\n" "\nReturns the current block on timeout or exit.\n" "\nArguments:\n" "1. height (required, int) Block height to wait for (int)\n" "2. timeout (int, optional, default=0) Time in milliseconds to wait for a response. 0 indicates no timeout.\n" "\nResult:\n" "{ (json object)\n" " \"hash\" : { (string) The blockhash\n" " \"height\" : { (int) Block height\n" "}\n" "\nExamples:\n" + HelpExampleCli("waitforblockheight", "\"100\", 1000") + HelpExampleRpc("waitforblockheight", "\"100\", 1000") ); int timeout = 0; int height = request.params[0].get_int(); if (request.params.size() > 1) timeout = request.params[1].get_int(); CUpdatedBlock block; { std::unique_lock<std::mutex> lock(cs_blockchange); if(timeout) cond_blockchange.wait_for(lock, std::chrono::milliseconds(timeout), [&height]{return latestblock.height >= height || !IsRPCRunning();}); else cond_blockchange.wait(lock, [&height]{return latestblock.height >= height || !IsRPCRunning(); }); block = latestblock; } UniValue ret(UniValue::VOBJ); ret.push_back(Pair("hash", block.hash.GetHex())); ret.push_back(Pair("height", block.height)); return ret; } UniValue getdifficulty(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 0) throw runtime_error( "getdifficulty\n" "\nReturns the proof-of-work difficulty as a multiple of the minimum difficulty.\n" "\nResult:\n" "n.nnn (numeric) the proof-of-work difficulty as a multiple of the minimum difficulty.\n" "\nExamples:\n" + HelpExampleCli("getdifficulty", "") + HelpExampleRpc("getdifficulty", "") ); LOCK(cs_main); return GetDifficulty(); } std::string EntryDescriptionString() { return " \"size\" : n, (numeric) actual transaction size\n" " \"fee\" : n, (numeric) transaction fee in " + CURRENCY_UNIT + "\n" " \"modifiedfee\" : n, (numeric) transaction fee with fee deltas used for mining priority\n" " \"time\" : n, (numeric) local time transaction entered pool in seconds since 1 Jan 1970 GMT\n" " \"height\" : n, (numeric) block height when transaction entered pool\n" " \"startingpriority\" : n, (numeric) DEPRECATED. Priority when transaction entered pool\n" " \"currentpriority\" : n, (numeric) DEPRECATED. Transaction priority now\n" " \"descendantcount\" : n, (numeric) number of in-mempool descendant transactions (including this one)\n" " \"descendantsize\" : n, (numeric) virtual transaction size of in-mempool descendants (including this one)\n" " \"descendantfees\" : n, (numeric) modified fees (see above) of in-mempool descendants (including this one)\n" " \"ancestorcount\" : n, (numeric) number of in-mempool ancestor transactions (including this one)\n" " \"ancestorsize\" : n, (numeric) transaction size of in-mempool ancestors (including this one)\n" " \"ancestorfees\" : n, (numeric) modified fees (see above) of in-mempool ancestors (including this one)\n" " \"depends\" : [ (array) unconfirmed transactions used as inputs for this transaction\n" " \"transactionid\", (string) parent transaction id\n" " ... ]\n"; } void entryToJSON(UniValue &info, const CTxMemPoolEntry &e) { AssertLockHeld(mempool.cs); info.push_back(Pair("size", (int)e.GetTxSize())); info.push_back(Pair("fee", ValueFromAmount(e.GetFee()))); info.push_back(Pair("modifiedfee", ValueFromAmount(e.GetModifiedFee()))); info.push_back(Pair("time", e.GetTime())); info.push_back(Pair("height", (int)e.GetHeight())); info.push_back(Pair("startingpriority", e.GetPriority(e.GetHeight()))); info.push_back(Pair("currentpriority", e.GetPriority(chainActive.Height()))); info.push_back(Pair("descendantcount", e.GetCountWithDescendants())); info.push_back(Pair("descendantsize", e.GetSizeWithDescendants())); info.push_back(Pair("descendantfees", e.GetModFeesWithDescendants())); info.push_back(Pair("ancestorcount", e.GetCountWithAncestors())); info.push_back(Pair("ancestorsize", e.GetSizeWithAncestors())); info.push_back(Pair("ancestorfees", e.GetModFeesWithAncestors())); const CTransaction& tx = e.GetTx(); set<string> setDepends; BOOST_FOREACH(const CTxIn& txin, tx.vin) { if (mempool.exists(txin.prevout.hash)) setDepends.insert(txin.prevout.hash.ToString()); } UniValue depends(UniValue::VARR); BOOST_FOREACH(const string& dep, setDepends) { depends.push_back(dep); } info.push_back(Pair("depends", depends)); } UniValue mempoolToJSON(bool fVerbose = false) { if (fVerbose) { LOCK(mempool.cs); UniValue o(UniValue::VOBJ); BOOST_FOREACH(const CTxMemPoolEntry& e, mempool.mapTx) { const uint256& hash = e.GetTx().GetHash(); UniValue info(UniValue::VOBJ); entryToJSON(info, e); o.push_back(Pair(hash.ToString(), info)); } return o; } else { vector<uint256> vtxid; mempool.queryHashes(vtxid); UniValue a(UniValue::VARR); BOOST_FOREACH(const uint256& hash, vtxid) a.push_back(hash.ToString()); return a; } } UniValue getrawmempool(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() > 1) throw runtime_error( "getrawmempool ( verbose )\n" "\nReturns all transaction ids in memory pool as a json array of string transaction ids.\n" "\nArguments:\n" "1. verbose (boolean, optional, default=false) True for a json object, false for array of transaction ids\n" "\nResult: (for verbose = false):\n" "[ (json array of string)\n" " \"transactionid\" (string) The transaction id\n" " ,...\n" "]\n" "\nResult: (for verbose = true):\n" "{ (json object)\n" " \"transactionid\" : { (json object)\n" + EntryDescriptionString() + " }, ...\n" "}\n" "\nExamples:\n" + HelpExampleCli("getrawmempool", "true") + HelpExampleRpc("getrawmempool", "true") ); bool fVerbose = false; if (request.params.size() > 0) fVerbose = request.params[0].get_bool(); return mempoolToJSON(fVerbose); } UniValue getmempoolancestors(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) { throw runtime_error( "getmempoolancestors txid (verbose)\n" "\nIf txid is in the mempool, returns all in-mempool ancestors.\n" "\nArguments:\n" "1. \"txid\" (string, required) The transaction id (must be in mempool)\n" "2. verbose (boolean, optional, default=false) True for a json object, false for array of transaction ids\n" "\nResult (for verbose=false):\n" "[ (json array of strings)\n" " \"transactionid\" (string) The transaction id of an in-mempool ancestor transaction\n" " ,...\n" "]\n" "\nResult (for verbose=true):\n" "{ (json object)\n" " \"transactionid\" : { (json object)\n" + EntryDescriptionString() + " }, ...\n" "}\n" "\nExamples:\n" + HelpExampleCli("getmempoolancestors", "\"mytxid\"") + HelpExampleRpc("getmempoolancestors", "\"mytxid\"") ); } bool fVerbose = false; if (request.params.size() > 1) fVerbose = request.params[1].get_bool(); uint256 hash = ParseHashV(request.params[0], "parameter 1"); LOCK(mempool.cs); CTxMemPool::txiter it = mempool.mapTx.find(hash); if (it == mempool.mapTx.end()) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not in mempool"); } CTxMemPool::setEntries setAncestors; uint64_t noLimit = std::numeric_limits<uint64_t>::max(); std::string dummy; mempool.CalculateMemPoolAncestors(*it, setAncestors, noLimit, noLimit, noLimit, noLimit, dummy, false); if (!fVerbose) { UniValue o(UniValue::VARR); BOOST_FOREACH(CTxMemPool::txiter ancestorIt, setAncestors) { o.push_back(ancestorIt->GetTx().GetHash().ToString()); } return o; } else { UniValue o(UniValue::VOBJ); BOOST_FOREACH(CTxMemPool::txiter ancestorIt, setAncestors) { const CTxMemPoolEntry &e = *ancestorIt; const uint256& _hash = e.GetTx().GetHash(); UniValue info(UniValue::VOBJ); entryToJSON(info, e); o.push_back(Pair(_hash.ToString(), info)); } return o; } } UniValue getmempooldescendants(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) { throw runtime_error( "getmempooldescendants txid (verbose)\n" "\nIf txid is in the mempool, returns all in-mempool descendants.\n" "\nArguments:\n" "1. \"txid\" (string, required) The transaction id (must be in mempool)\n" "2. verbose (boolean, optional, default=false) True for a json object, false for array of transaction ids\n" "\nResult (for verbose=false):\n" "[ (json array of strings)\n" " \"transactionid\" (string) The transaction id of an in-mempool descendant transaction\n" " ,...\n" "]\n" "\nResult (for verbose=true):\n" "{ (json object)\n" " \"transactionid\" : { (json object)\n" + EntryDescriptionString() + " }, ...\n" "}\n" "\nExamples:\n" + HelpExampleCli("getmempooldescendants", "\"mytxid\"") + HelpExampleRpc("getmempooldescendants", "\"mytxid\"") ); } bool fVerbose = false; if (request.params.size() > 1) fVerbose = request.params[1].get_bool(); uint256 hash = ParseHashV(request.params[0], "parameter 1"); LOCK(mempool.cs); CTxMemPool::txiter it = mempool.mapTx.find(hash); if (it == mempool.mapTx.end()) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not in mempool"); } CTxMemPool::setEntries setDescendants; mempool.CalculateDescendants(it, setDescendants); // CTxMemPool::CalculateDescendants will include the given tx setDescendants.erase(it); if (!fVerbose) { UniValue o(UniValue::VARR); BOOST_FOREACH(CTxMemPool::txiter descendantIt, setDescendants) { o.push_back(descendantIt->GetTx().GetHash().ToString()); } return o; } else { UniValue o(UniValue::VOBJ); BOOST_FOREACH(CTxMemPool::txiter descendantIt, setDescendants) { const CTxMemPoolEntry &e = *descendantIt; const uint256& _hash = e.GetTx().GetHash(); UniValue info(UniValue::VOBJ); entryToJSON(info, e); o.push_back(Pair(_hash.ToString(), info)); } return o; } } UniValue getmempoolentry(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 1) { throw runtime_error( "getmempoolentry txid\n" "\nReturns mempool data for given transaction\n" "\nArguments:\n" "1. \"txid\" (string, required) The transaction id (must be in mempool)\n" "\nResult:\n" "{ (json object)\n" + EntryDescriptionString() + "}\n" "\nExamples:\n" + HelpExampleCli("getmempoolentry", "\"mytxid\"") + HelpExampleRpc("getmempoolentry", "\"mytxid\"") ); } uint256 hash = ParseHashV(request.params[0], "parameter 1"); LOCK(mempool.cs); CTxMemPool::txiter it = mempool.mapTx.find(hash); if (it == mempool.mapTx.end()) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not in mempool"); } const CTxMemPoolEntry &e = *it; UniValue info(UniValue::VOBJ); entryToJSON(info, e); return info; } UniValue getblockhash(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 1) throw runtime_error( "getblockhash height\n" "\nReturns hash of block in best-block-chain at height provided.\n" "\nArguments:\n" "1. height (numeric, required) The height index\n" "\nResult:\n" "\"hash\" (string) The block hash\n" "\nExamples:\n" + HelpExampleCli("getblockhash", "1000") + HelpExampleRpc("getblockhash", "1000") ); LOCK(cs_main); int nHeight = request.params[0].get_int(); if (nHeight < 0 || nHeight > chainActive.Height()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Block height out of range"); CBlockIndex* pblockindex = chainActive[nHeight]; return pblockindex->GetBlockHash().GetHex(); } UniValue getblockheader(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) throw runtime_error( "getblockheader \"hash\" ( verbose )\n" "\nIf verbose is false, returns a string that is serialized, hex-encoded data for blockheader 'hash'.\n" "If verbose is true, returns an Object with information about blockheader <hash>.\n" "\nArguments:\n" "1. \"hash\" (string, required) The block hash\n" "2. verbose (boolean, optional, default=true) true for a json object, false for the hex encoded data\n" "\nResult (for verbose = true):\n" "{\n" " \"hash\" : \"hash\", (string) the block hash (same as provided)\n" " \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n" " \"height\" : n, (numeric) The block height or index\n" " \"version\" : n, (numeric) The block version\n" " \"versionHex\" : \"00000000\", (string) The block version formatted in hexadecimal\n" " \"merkleroot\" : \"xxxx\", (string) The merkle root\n" " \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n" " \"mediantime\" : ttt, (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n" " \"nonce\" : n, (numeric) The nonce\n" " \"bits\" : \"1d00ffff\", (string) The bits\n" " \"difficulty\" : x.xxx, (numeric) The difficulty\n" " \"chainwork\" : \"0000...1f3\" (string) Expected number of hashes required to produce the current chain (in hex)\n" " \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n" " \"nextblockhash\" : \"hash\", (string) The hash of the next block\n" "}\n" "\nResult (for verbose=false):\n" "\"data\" (string) A string that is serialized, hex-encoded data for block 'hash'.\n" "\nExamples:\n" + HelpExampleCli("getblockheader", "\"e2acdf2dd19a702e5d12a925f1e984b01e47a933562ca893656d4afb38b44ee3\"") + HelpExampleRpc("getblockheader", "\"e2acdf2dd19a702e5d12a925f1e984b01e47a933562ca893656d4afb38b44ee3\"") ); LOCK(cs_main); std::string strHash = request.params[0].get_str(); uint256 hash(uint256S(strHash)); bool fVerbose = true; if (request.params.size() > 1) fVerbose = request.params[1].get_bool(); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); CBlockIndex* pblockindex = mapBlockIndex[hash]; if (!fVerbose) { CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION); ssBlock << pblockindex->GetBlockHeader(); std::string strHex = HexStr(ssBlock.begin(), ssBlock.end()); return strHex; } return blockheaderToJSON(pblockindex); } UniValue getblock(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) throw runtime_error( "getblock \"blockhash\" ( verbose )\n" "\nIf verbose is false, returns a string that is serialized, hex-encoded data for block 'hash'.\n" "If verbose is true, returns an Object with information about block <hash>.\n" "\nArguments:\n" "1. \"blockhash\" (string, required) The block hash\n" "2. verbose (boolean, optional, default=true) true for a json object, false for the hex encoded data\n" "\nResult (for verbose = true):\n" "{\n" " \"hash\" : \"hash\", (string) the block hash (same as provided)\n" " \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n" " \"size\" : n, (numeric) The block size\n" " \"weight\" : n (numeric) The block weight as defined in BIP 141\n" " \"height\" : n, (numeric) The block height or index\n" " \"version\" : n, (numeric) The block version\n" " \"versionHex\" : \"00000000\", (string) The block version formatted in hexadecimal\n" " \"merkleroot\" : \"xxxx\", (string) The merkle root\n" " \"tx\" : [ (array of string) The transaction ids\n" " \"transactionid\" (string) The transaction id\n" " ,...\n" " ],\n" " \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n" " \"mediantime\" : ttt, (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n" " \"nonce\" : n, (numeric) The nonce\n" " \"bits\" : \"1d00ffff\", (string) The bits\n" " \"difficulty\" : x.xxx, (numeric) The difficulty\n" " \"chainwork\" : \"xxxx\", (string) Expected number of hashes required to produce the chain up to this block (in hex)\n" " \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n" " \"nextblockhash\" : \"hash\" (string) The hash of the next block\n" "}\n" "\nResult (for verbose=false):\n" "\"data\" (string) A string that is serialized, hex-encoded data for block 'hash'.\n" "\nExamples:\n" + HelpExampleCli("getblock", "\"e2acdf2dd19a702e5d12a925f1e984b01e47a933562ca893656d4afb38b44ee3\"") + HelpExampleRpc("getblock", "\"e2acdf2dd19a702e5d12a925f1e984b01e47a933562ca893656d4afb38b44ee3\"") ); LOCK(cs_main); std::string strHash = request.params[0].get_str(); uint256 hash(uint256S(strHash)); shared_ptr<const CBlock> queuedBlock; bool fVerbose = true; if (request.params.size() > 1) fVerbose = request.params[1].get_bool(); if (mapBlockIndex.count(hash) == 0) { queuedBlock = GetQueuedBlock(); if(queuedBlock == nullptr || queuedBlock->GetHash().Compare(hash) != 0 || nReportQueuedBlocks != REPORT_QUEUED_BLOCK_TRANSACTION) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); } CBlock block; CBlockIndex* pblockindex = queuedBlock == nullptr ? mapBlockIndex[hash] : 0; if(queuedBlock == nullptr) { if (fHavePruned && !(pblockindex->nStatus & BLOCK_HAVE_DATA) && pblockindex->nTx > 0) throw JSONRPCError(RPC_INTERNAL_ERROR, "Block not available (pruned data)"); if(!ReadBlockFromDisk(block, pblockindex, Params().GetConsensus())) throw JSONRPCError(RPC_INTERNAL_ERROR, "Can't read block from disk"); } else { //Copy the block so it is available in the waiting thread. CDataStream stream(SER_NETWORK, PROTOCOL_VERSION); queuedBlock->Serialize(stream); stream.Rewind(stream.size()); block.Unserialize(stream); pblockindex = chainActive.Tip(); } if (!fVerbose) { CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION | RPCSerializationFlags()); ssBlock << block; std::string strHex = HexStr(ssBlock.begin(), ssBlock.end()); return strHex; } return blockToJSON(block, pblockindex, false, queuedBlock != nullptr); } // RPC commands related to sync checkpoints // get information of sync-checkpoint (first introduced in ppcoin) UniValue getcheckpoint(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 0) throw std::runtime_error( "getcheckpoint\n" "Show info of synchronized checkpoint.\n"); UniValue result(UniValue::VARR); UniValue entry(UniValue::VOBJ); CBlockIndex* pindexCheckpoint; entry.push_back(Pair("synccheckpoint", hashSyncCheckpoint.ToString().c_str())); if (mapBlockIndex.count(hashSyncCheckpoint)) { pindexCheckpoint = mapBlockIndex[hashSyncCheckpoint]; entry.push_back(Pair("height", pindexCheckpoint->nHeight)); entry.push_back(Pair("timestamp", (boost::int64_t) pindexCheckpoint->GetBlockTime())); } if (IsArgSet("-checkpointkey")) entry.push_back(Pair("checkpointmaster", true)); result.push_back(entry); return result; } UniValue sendcheckpoint(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 1) throw std::runtime_error( "sendcheckpoint <blockhash>\n" "Send a synchronized checkpoint.\n"); if (IsArgSet("-checkpointkey") || CSyncCheckpoint::strMasterPrivKey.empty()) throw std::runtime_error("Not a checkpointmaster node, first set checkpointkey in configuration and restart client. "); std::string strHash = request.params[0].get_str(); uint256 hash = uint256S(strHash); if (!SendSyncCheckpoint(hash)) throw std::runtime_error("Failed to send checkpoint, check log. "); UniValue result(UniValue::VARR); UniValue entry(UniValue::VOBJ); CBlockIndex* pindexCheckpoint; entry.push_back(Pair("synccheckpoint", hashSyncCheckpoint.ToString().c_str())); if (mapBlockIndex.count(hashSyncCheckpoint)) { pindexCheckpoint = mapBlockIndex[hashSyncCheckpoint]; entry.push_back(Pair("height", pindexCheckpoint->nHeight)); entry.push_back(Pair("timestamp", (boost::int64_t) pindexCheckpoint->GetBlockTime())); } if (IsArgSet("-checkpointkey")) entry.push_back(Pair("checkpointmaster", true)); result.push_back(entry); return result; } struct CCoinsStats { int nHeight; uint256 hashBlock; uint64_t nTransactions; uint64_t nTransactionOutputs; uint64_t nSerializedSize; uint256 hashSerialized; CAmount nTotalAmount; CCoinsStats() : nHeight(0), nTransactions(0), nTransactionOutputs(0), nSerializedSize(0), nTotalAmount(0) {} }; //! Calculate statistics about the unspent transaction output set static bool GetUTXOStats(CCoinsView *view, CCoinsStats &stats) { std::unique_ptr<CCoinsViewCursor> pcursor(view->Cursor()); CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION); stats.hashBlock = pcursor->GetBestBlock(); { LOCK(cs_main); stats.nHeight = mapBlockIndex.find(stats.hashBlock)->second->nHeight; } ss << stats.hashBlock; CAmount nTotalAmount = 0; while (pcursor->Valid()) { boost::this_thread::interruption_point(); uint256 key; CCoins coins; if (pcursor->GetKey(key) && pcursor->GetValue(coins)) { stats.nTransactions++; ss << key; for (unsigned int i=0; i<coins.vout.size(); i++) { const CTxOut &out = coins.vout[i]; if (!out.IsNull()) { stats.nTransactionOutputs++; ss << VARINT(i+1); ss << out; nTotalAmount += out.nValue; } } stats.nSerializedSize += 32 + pcursor->GetValueSize(); ss << VARINT(0); } else { return error("%s: unable to read value", __func__); } pcursor->Next(); } stats.hashSerialized = ss.GetHash(); stats.nTotalAmount = nTotalAmount; return true; } UniValue pruneblockchain(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 1) throw runtime_error( "pruneblockchain\n" "\nArguments:\n" "1. \"height\" (numeric, required) The block height to prune up to. May be set to a discrete height, or a unix timestamp\n" " to prune blocks whose block time is at least 2 hours older than the provided timestamp.\n" "\nResult:\n" "n (numeric) Height of the last block pruned.\n" "\nExamples:\n" + HelpExampleCli("pruneblockchain", "1000") + HelpExampleRpc("pruneblockchain", "1000")); if (!fPruneMode) throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Cannot prune blocks because node is not in prune mode."); LOCK(cs_main); int heightParam = request.params[0].get_int(); if (heightParam < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative block height."); // Height value more than a billion is too high to be a block height, and // too low to be a block time (corresponds to timestamp from Sep 2001). if (heightParam > 1000000000) { // Add a 2 hour buffer to include blocks which might have had old timestamps CBlockIndex* pindex = chainActive.FindEarliestAtLeast(heightParam - 7200); if (!pindex) { throw JSONRPCError(RPC_INTERNAL_ERROR, "Could not find block with at least the specified timestamp."); } heightParam = pindex->nHeight; } unsigned int height = (unsigned int) heightParam; unsigned int chainHeight = (unsigned int) chainActive.Height(); if (chainHeight < Params().PruneAfterHeight()) throw JSONRPCError(RPC_INTERNAL_ERROR, "Blockchain is too short for pruning."); else if (height > chainHeight) throw JSONRPCError(RPC_INVALID_PARAMETER, "Blockchain is shorter than the attempted prune height."); else if (height > chainHeight - MIN_BLOCKS_TO_KEEP) { LogPrint("rpc", "Attempt to prune blocks close to the tip. Retaining the minimum number of blocks."); height = chainHeight - MIN_BLOCKS_TO_KEEP; } PruneBlockFilesManual(height); return uint64_t(height); } UniValue gettxoutsetinfo(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 0) throw runtime_error( "gettxoutsetinfo\n" "\nReturns statistics about the unspent transaction output set.\n" "Note this call may take some time.\n" "\nResult:\n" "{\n" " \"height\":n, (numeric) The current block height (index)\n" " \"bestblock\": \"hex\", (string) the best block hash hex\n" " \"transactions\": n, (numeric) The number of transactions\n" " \"txouts\": n, (numeric) The number of output transactions\n" " \"bytes_serialized\": n, (numeric) The serialized size\n" " \"hash_serialized\": \"hash\", (string) The serialized hash\n" " \"total_amount\": x.xxx (numeric) The total amount\n" "}\n" "\nExamples:\n" + HelpExampleCli("gettxoutsetinfo", "") + HelpExampleRpc("gettxoutsetinfo", "") ); UniValue ret(UniValue::VOBJ); CCoinsStats stats; FlushStateToDisk(); if (GetUTXOStats(pcoinsTip, stats)) { ret.push_back(Pair("height", (int64_t)stats.nHeight)); ret.push_back(Pair("bestblock", stats.hashBlock.GetHex())); ret.push_back(Pair("transactions", (int64_t)stats.nTransactions)); ret.push_back(Pair("txouts", (int64_t)stats.nTransactionOutputs)); ret.push_back(Pair("bytes_serialized", (int64_t)stats.nSerializedSize)); ret.push_back(Pair("hash_serialized", stats.hashSerialized.GetHex())); ret.push_back(Pair("total_amount", ValueFromAmount(stats.nTotalAmount))); } else { throw JSONRPCError(RPC_INTERNAL_ERROR, "Unable to read UTXO set"); } return ret; } UniValue gettxout(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 2 || request.params.size() > 3) throw runtime_error( "gettxout \"txid\" n ( include_mempool )\n" "\nReturns details about an unspent transaction output.\n" "\nArguments:\n" "1. \"txid\" (string, required) The transaction id\n" "2. n (numeric, required) vout number\n" "3. include_mempool (boolean, optional) Whether to include the mempool\n" "\nResult:\n" "{\n" " \"bestblock\" : \"hash\", (string) the block hash\n" " \"confirmations\" : n, (numeric) The number of confirmations\n" " \"value\" : x.xxx, (numeric) The transaction value in " + CURRENCY_UNIT + "\n" " \"scriptPubKey\" : { (json object)\n" " \"asm\" : \"code\", (string) \n" " \"hex\" : \"hex\", (string) \n" " \"reqSigs\" : n, (numeric) Number of required signatures\n" " \"type\" : \"pubkeyhash\", (string) The type, eg pubkeyhash\n" " \"addresses\" : [ (array of string) array of goldcoin addresses\n" " \"address\" (string) goldcoin address\n" " ,...\n" " ]\n" " },\n" " \"version\" : n, (numeric) The version\n" " \"coinbase\" : true|false (boolean) Coinbase or not\n" "}\n" "\nExamples:\n" "\nGet unspent transactions\n" + HelpExampleCli("listunspent", "") + "\nView the details\n" + HelpExampleCli("gettxout", "\"txid\" 1") + "\nAs a json rpc call\n" + HelpExampleRpc("gettxout", "\"txid\", 1") ); LOCK(cs_main); UniValue ret(UniValue::VOBJ); std::string strHash = request.params[0].get_str(); uint256 hash(uint256S(strHash)); int n = request.params[1].get_int(); bool fMempool = true; if (request.params.size() > 2) fMempool = request.params[2].get_bool(); CCoins coins; if (fMempool) { LOCK(mempool.cs); CCoinsViewMemPool view(pcoinsTip, mempool); if (!view.GetCoins(hash, coins)) return NullUniValue; mempool.pruneSpent(hash, coins); // TODO: this should be done by the CCoinsViewMemPool } else { if (!pcoinsTip->GetCoins(hash, coins)) return NullUniValue; } if (n<0 || (unsigned int)n>=coins.vout.size() || coins.vout[n].IsNull()) return NullUniValue; BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock()); CBlockIndex *pindex = it->second; ret.push_back(Pair("bestblock", pindex->GetBlockHash().GetHex())); if ((unsigned int)coins.nHeight == MEMPOOL_HEIGHT) ret.push_back(Pair("confirmations", 0)); else ret.push_back(Pair("confirmations", pindex->nHeight - coins.nHeight + 1)); ret.push_back(Pair("value", ValueFromAmount(coins.vout[n].nValue))); UniValue o(UniValue::VOBJ); ScriptPubKeyToJSON(coins.vout[n].scriptPubKey, o, true); ret.push_back(Pair("scriptPubKey", o)); ret.push_back(Pair("version", coins.nVersion)); ret.push_back(Pair("coinbase", coins.fCoinBase)); return ret; } UniValue verifychain(const JSONRPCRequest& request) { int nCheckLevel = GetArg("-checklevel", DEFAULT_CHECKLEVEL); int nCheckDepth = GetArg("-checkblocks", DEFAULT_CHECKBLOCKS); if (request.fHelp || request.params.size() > 2) throw runtime_error( "verifychain ( checklevel nblocks )\n" "\nVerifies blockchain database.\n" "\nArguments:\n" "1. checklevel (numeric, optional, 0-4, default=" + strprintf("%d", nCheckLevel) + ") How thorough the block verification is.\n" "2. nblocks (numeric, optional, default=" + strprintf("%d", nCheckDepth) + ", 0=all) The number of blocks to check.\n" "\nResult:\n" "true|false (boolean) Verified or not\n" "\nExamples:\n" + HelpExampleCli("verifychain", "") + HelpExampleRpc("verifychain", "") ); LOCK(cs_main); if (request.params.size() > 0) nCheckLevel = request.params[0].get_int(); if (request.params.size() > 1) nCheckDepth = request.params[1].get_int(); return CVerifyDB().VerifyDB(Params(), pcoinsTip, nCheckLevel, nCheckDepth); } /** Implementation of IsSuperMajority with better feedback */ static UniValue SoftForkMajorityDesc(int version, CBlockIndex* pindex, const Consensus::Params& consensusParams) { UniValue rv(UniValue::VOBJ); bool activated = false; bool hasSuperMajority = pindex->nHeight >= consensusParams.BIP65Height ? true : CBlockIndex::IsSuperMajority(4, pindex->pprev, consensusParams, consensusParams.nEnforceBlockUpgradeMajority); switch(version) { case 2: activated = pindex->nHeight >= consensusParams.BIP34Height || hasSuperMajority; break; case 3: activated = pindex->nHeight >= consensusParams.BIP66Height|| hasSuperMajority; break; case 4: activated = pindex->nHeight >= consensusParams.BIP65Height|| hasSuperMajority; break; } rv.push_back(Pair("status", activated)); return rv; } static UniValue SoftForkDesc(const std::string &name, int version, CBlockIndex* pindex, const Consensus::Params& consensusParams) { UniValue rv(UniValue::VOBJ); rv.push_back(Pair("id", name)); rv.push_back(Pair("version", version)); rv.push_back(Pair("reject", SoftForkMajorityDesc(version, pindex, consensusParams))); return rv; } static UniValue BIP9SoftForkDesc(const Consensus::Params& consensusParams, Consensus::DeploymentPos id) { UniValue rv(UniValue::VOBJ); const ThresholdState thresholdState = VersionBitsTipState(consensusParams, id); switch (thresholdState) { case THRESHOLD_DEFINED: rv.push_back(Pair("status", "defined")); break; case THRESHOLD_STARTED: rv.push_back(Pair("status", "started")); break; case THRESHOLD_LOCKED_IN: rv.push_back(Pair("status", "locked_in")); break; case THRESHOLD_ACTIVE: rv.push_back(Pair("status", "active")); break; case THRESHOLD_FAILED: rv.push_back(Pair("status", "failed")); break; } if (THRESHOLD_STARTED == thresholdState) { rv.push_back(Pair("bit", consensusParams.vDeployments[id].bit)); } rv.push_back(Pair("startTime", consensusParams.vDeployments[id].nStartTime)); rv.push_back(Pair("timeout", consensusParams.vDeployments[id].nTimeout)); rv.push_back(Pair("since", VersionBitsTipStateSinceHeight(consensusParams, id))); return rv; } void BIP9SoftForkDescPushBack(UniValue& bip9_softforks, const std::string &name, const Consensus::Params& consensusParams, Consensus::DeploymentPos id) { // Deployments with timeout value of 0 are hidden. // A timeout value of 0 guarantees a softfork will never be activated. // This is used when softfork codes are merged without specifying the deployment schedule. if (consensusParams.vDeployments[id].nTimeout > 0) bip9_softforks.push_back(Pair(name, BIP9SoftForkDesc(consensusParams, id))); } UniValue getblockchaininfo(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 0) throw runtime_error( "getblockchaininfo\n" "Returns an object containing various state info regarding blockchain processing.\n" "\nResult:\n" "{\n" " \"chain\": \"xxxx\", (string) current network name as defined in BIP70 (main, test, regtest)\n" " \"blocks\": xxxxxx, (numeric) the current number of blocks processed in the server\n" " \"headers\": xxxxxx, (numeric) the current number of headers we have validated\n" " \"bestblockhash\": \"...\", (string) the hash of the currently best block\n" " \"difficulty\": xxxxxx, (numeric) the current difficulty\n" " \"mediantime\": xxxxxx, (numeric) median time for the current best block\n" " \"verificationprogress\": xxxx, (numeric) estimate of verification progress [0..1]\n" " \"chainwork\": \"xxxx\" (string) total amount of work in active chain, in hexadecimal\n" " \"pruned\": xx, (boolean) if the blocks are subject to pruning\n" " \"pruneheight\": xxxxxx, (numeric) lowest-height complete block stored\n" " \"softforks\": [ (array) status of softforks in progress\n" " {\n" " \"id\": \"xxxx\", (string) name of softfork\n" " \"version\": xx, (numeric) block version\n" " \"reject\": { (object) progress toward rejecting pre-softfork blocks\n" " \"status\": xx, (boolean) true if threshold reached\n" " },\n" " }, ...\n" " ],\n" " \"bip9_softforks\": { (object) status of BIP9 softforks in progress\n" " \"xxxx\" : { (string) name of the softfork\n" " \"status\": \"xxxx\", (string) one of \"defined\", \"started\", \"locked_in\", \"active\", \"failed\"\n" " \"bit\": xx, (numeric) the bit (0-28) in the block version field used to signal this softfork (only for \"started\" status)\n" " \"startTime\": xx, (numeric) the minimum median time past of a block at which the bit gains its meaning\n" " \"timeout\": xx, (numeric) the median time past of a block at which the deployment is considered failed if not yet locked in\n" " \"since\": xx (numeric) height of the first block to which the status applies\n" " }\n" " }\n" "}\n" "\nExamples:\n" + HelpExampleCli("getblockchaininfo", "") + HelpExampleRpc("getblockchaininfo", "") ); LOCK(cs_main); UniValue obj(UniValue::VOBJ); obj.push_back(Pair("chain", Params().NetworkIDString())); obj.push_back(Pair("blocks", (int)chainActive.Height())); obj.push_back(Pair("headers", pindexBestHeader ? pindexBestHeader->nHeight : -1)); obj.push_back(Pair("bestblockhash", chainActive.Tip()->GetBlockHash().GetHex())); obj.push_back(Pair("difficulty", (double)GetDifficulty())); obj.push_back(Pair("mediantime", (int64_t)chainActive.Tip()->GetMedianTimePast())); obj.push_back(Pair("verificationprogress", GuessVerificationProgress(Params().TxData(), chainActive.Tip()))); obj.push_back(Pair("chainwork", chainActive.Tip()->nChainWork.GetHex())); obj.push_back(Pair("pruned", fPruneMode)); const Consensus::Params& consensusParams = Params().GetConsensus(); CBlockIndex* tip = chainActive.Tip(); UniValue softforks(UniValue::VARR); UniValue bip9_softforks(UniValue::VOBJ); softforks.push_back(SoftForkDesc("bip34", 2, tip, consensusParams)); softforks.push_back(SoftForkDesc("bip66", 3, tip, consensusParams)); softforks.push_back(SoftForkDesc("bip65", 4, tip, consensusParams)); BIP9SoftForkDescPushBack(bip9_softforks, "csv", consensusParams, Consensus::DEPLOYMENT_CSV); obj.push_back(Pair("softforks", softforks)); obj.push_back(Pair("bip9_softforks", bip9_softforks)); if (fPruneMode) { CBlockIndex *block = chainActive.Tip(); while (block && block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA)) block = block->pprev; obj.push_back(Pair("pruneheight", block->nHeight)); } return obj; } /** Comparison function for sorting the getchaintips heads. */ struct CompareBlocksByHeight { bool operator()(const CBlockIndex* a, const CBlockIndex* b) const { /* Make sure that unequal blocks with the same height do not compare equal. Use the pointers themselves to make a distinction. */ if (a->nHeight != b->nHeight) return (a->nHeight > b->nHeight); return a < b; } }; UniValue getchaintips(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 0) throw runtime_error( "getchaintips\n" "Return information about all known tips in the block tree," " including the main chain as well as orphaned branches.\n" "\nResult:\n" "[\n" " {\n" " \"height\": xxxx, (numeric) height of the chain tip\n" " \"hash\": \"xxxx\", (string) block hash of the tip\n" " \"branchlen\": 0 (numeric) zero for main chain\n" " \"status\": \"active\" (string) \"active\" for the main chain\n" " },\n" " {\n" " \"height\": xxxx,\n" " \"hash\": \"xxxx\",\n" " \"branchlen\": 1 (numeric) length of branch connecting the tip to the main chain\n" " \"status\": \"xxxx\" (string) status of the chain (active, valid-fork, valid-headers, headers-only, invalid)\n" " }\n" "]\n" "Possible values for status:\n" "1. \"invalid\" This branch contains at least one invalid block\n" "2. \"headers-only\" Not all blocks for this branch are available, but the headers are valid\n" "3. \"valid-headers\" All blocks are available for this branch, but they were never fully validated\n" "4. \"valid-fork\" This branch is not part of the active chain, but is fully validated\n" "5. \"active\" This is the tip of the active main chain, which is certainly valid\n" "\nExamples:\n" + HelpExampleCli("getchaintips", "") + HelpExampleRpc("getchaintips", "") ); LOCK(cs_main); /* * Idea: the set of chain tips is chainActive.tip, plus orphan blocks which do not have another orphan building off of them. * Algorithm: * - Make one pass through mapBlockIndex, picking out the orphan blocks, and also storing a set of the orphan block's pprev pointers. * - Iterate through the orphan blocks. If the block isn't pointed to by another orphan, it is a chain tip. * - add chainActive.Tip() */ std::set<const CBlockIndex*, CompareBlocksByHeight> setTips; std::set<const CBlockIndex*> setOrphans; std::set<const CBlockIndex*> setPrevs; BOOST_FOREACH(const PAIRTYPE(const uint256, CBlockIndex*)& item, mapBlockIndex) { if (!chainActive.Contains(item.second)) { setOrphans.insert(item.second); setPrevs.insert(item.second->pprev); } } for (std::set<const CBlockIndex*>::iterator it = setOrphans.begin(); it != setOrphans.end(); ++it) { if (setPrevs.erase(*it) == 0) { setTips.insert(*it); } } // Always report the currently active tip. setTips.insert(chainActive.Tip()); /* Construct the output array. */ UniValue res(UniValue::VARR); BOOST_FOREACH(const CBlockIndex* block, setTips) { UniValue obj(UniValue::VOBJ); obj.push_back(Pair("height", block->nHeight)); obj.push_back(Pair("hash", block->phashBlock->GetHex())); const int branchLen = block->nHeight - chainActive.FindFork(block)->nHeight; obj.push_back(Pair("branchlen", branchLen)); string status; if (chainActive.Contains(block)) { // This block is part of the currently active chain. status = "active"; } else if (block->nStatus & BLOCK_FAILED_MASK) { // This block or one of its ancestors is invalid. status = "invalid"; } else if (block->nChainTx == 0) { // This block cannot be connected because full block data for it or one of its parents is missing. status = "headers-only"; } else if (block->IsValid(BLOCK_VALID_SCRIPTS)) { // This block is fully validated, but no longer part of the active chain. It was probably the active block once, but was reorganized. status = "valid-fork"; } else if (block->IsValid(BLOCK_VALID_TREE)) { // The headers for this block are valid, but it has not been validated. It was probably never part of the most-work chain. status = "valid-headers"; } else { // No clue. status = "unknown"; } obj.push_back(Pair("status", status)); res.push_back(obj); } return res; } UniValue mempoolInfoToJSON() { UniValue ret(UniValue::VOBJ); ret.push_back(Pair("size", (int64_t) mempool.size())); ret.push_back(Pair("bytes", (int64_t) mempool.GetTotalTxSize())); ret.push_back(Pair("usage", (int64_t) mempool.DynamicMemoryUsage())); size_t maxmempool = GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000; ret.push_back(Pair("maxmempool", (int64_t) maxmempool)); ret.push_back(Pair("mempoolminfee", ValueFromAmount(mempool.GetMinFee(maxmempool).GetFeePerK()))); return ret; } UniValue getmempoolinfo(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 0) throw runtime_error( "getmempoolinfo\n" "\nReturns details on the active state of the TX memory pool.\n" "\nResult:\n" "{\n" " \"size\": xxxxx, (numeric) Current tx count\n" " \"bytes\": xxxxx, (numeric) Sum of all serialized transaction sizes\n" " \"usage\": xxxxx, (numeric) Total memory usage for the mempool\n" " \"maxmempool\": xxxxx, (numeric) Maximum memory usage for the mempool\n" " \"mempoolminfee\": xxxxx (numeric) Minimum fee for tx to be accepted\n" "}\n" "\nExamples:\n" + HelpExampleCli("getmempoolinfo", "") + HelpExampleRpc("getmempoolinfo", "") ); return mempoolInfoToJSON(); } UniValue preciousblock(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 1) throw runtime_error( "preciousblock \"blockhash\"\n" "\nTreats a block as if it were received before others with the same work.\n" "\nA later preciousblock call can override the effect of an earlier one.\n" "\nThe effects of preciousblock are not retained across restarts.\n" "\nArguments:\n" "1. \"blockhash\" (string, required) the hash of the block to mark as precious\n" "\nResult:\n" "\nExamples:\n" + HelpExampleCli("preciousblock", "\"blockhash\"") + HelpExampleRpc("preciousblock", "\"blockhash\"") ); std::string strHash = request.params[0].get_str(); uint256 hash(uint256S(strHash)); CBlockIndex* pblockindex; { LOCK(cs_main); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); pblockindex = mapBlockIndex[hash]; } CValidationState state; PreciousBlock(state, Params(), pblockindex); if (!state.IsValid()) { throw JSONRPCError(RPC_DATABASE_ERROR, state.GetRejectReason()); } return NullUniValue; } UniValue invalidateblock(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 1) throw runtime_error( "invalidateblock \"blockhash\"\n" "\nPermanently marks a block as invalid, as if it violated a consensus rule.\n" "\nArguments:\n" "1. \"blockhash\" (string, required) the hash of the block to mark as invalid\n" "\nResult:\n" "\nExamples:\n" + HelpExampleCli("invalidateblock", "\"blockhash\"") + HelpExampleRpc("invalidateblock", "\"blockhash\"") ); std::string strHash = request.params[0].get_str(); uint256 hash(uint256S(strHash)); CValidationState state; { LOCK(cs_main); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); CBlockIndex* pblockindex = mapBlockIndex[hash]; InvalidateBlock(state, Params(), pblockindex); } if (state.IsValid()) { ActivateBestChain(state, Params()); } if (!state.IsValid()) { throw JSONRPCError(RPC_DATABASE_ERROR, state.GetRejectReason()); } return NullUniValue; } UniValue reconsiderblock(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 1) throw runtime_error( "reconsiderblock \"blockhash\"\n" "\nRemoves invalidity status of a block and its descendants, reconsider them for activation.\n" "This can be used to undo the effects of invalidateblock.\n" "\nArguments:\n" "1. \"blockhash\" (string, required) the hash of the block to reconsider\n" "\nResult:\n" "\nExamples:\n" + HelpExampleCli("reconsiderblock", "\"blockhash\"") + HelpExampleRpc("reconsiderblock", "\"blockhash\"") ); std::string strHash = request.params[0].get_str(); uint256 hash(uint256S(strHash)); { LOCK(cs_main); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); CBlockIndex* pblockindex = mapBlockIndex[hash]; ResetBlockFailureFlags(pblockindex); } CValidationState state; ActivateBestChain(state, Params()); if (!state.IsValid()) { throw JSONRPCError(RPC_DATABASE_ERROR, state.GetRejectReason()); } return NullUniValue; } static const CRPCCommand commands[] = { // category name actor (function) okSafe argNames // --------------------- ------------------------ ----------------------- ------ ---------- { "blockchain", "getblockchaininfo", &getblockchaininfo, true, {} }, { "blockchain", "getbestblockhash", &getbestblockhash, true, {} }, { "blockchain", "getblockcount", &getblockcount, true, {} }, { "blockchain", "getblock", &getblock, true, {"blockhash","verbose"} }, { "blockchain", "getblockhash", &getblockhash, true, {"height"} }, { "blockchain", "getblockheader", &getblockheader, true, {"blockhash","verbose"} }, { "blockchain", "getcheckpoint", &getcheckpoint, true, {} }, { "blockchain", "sendcheckpoint", &sendcheckpoint, true, {"blockhash"} }, { "blockchain", "getchaintips", &getchaintips, true, {} }, { "blockchain", "getdifficulty", &getdifficulty, true, {} }, { "blockchain", "getmempoolancestors", &getmempoolancestors, true, {"txid","verbose"} }, { "blockchain", "getmempooldescendants", &getmempooldescendants, true, {"txid","verbose"} }, { "blockchain", "getmempoolentry", &getmempoolentry, true, {"txid"} }, { "blockchain", "getmempoolinfo", &getmempoolinfo, true, {} }, { "blockchain", "getrawmempool", &getrawmempool, true, {"verbose"} }, { "blockchain", "gettxout", &gettxout, true, {"txid","n","include_mempool"} }, { "blockchain", "gettxoutsetinfo", &gettxoutsetinfo, true, {} }, { "blockchain", "pruneblockchain", &pruneblockchain, true, {"height"} }, { "blockchain", "verifychain", &verifychain, true, {"checklevel","nblocks"} }, { "blockchain", "preciousblock", &preciousblock, true, {"blockhash"} }, /* Not shown in help */ { "hidden", "invalidateblock", &invalidateblock, true, {"blockhash"} }, { "hidden", "reconsiderblock", &reconsiderblock, true, {"blockhash"} }, { "hidden", "waitfornewblock", &waitfornewblock, true, {"timeout"} }, { "hidden", "waitforblock", &waitforblock, true, {"blockhash","timeout"} }, { "hidden", "waitforblockheight", &waitforblockheight, true, {"height","timeout"} }, }; void RegisterBlockchainRPCCommands(CRPCTable &t) { for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++) t.appendCommand(commands[vcidx].name, &commands[vcidx]); }
goldcoin/Goldcoin-GLD
src/rpc/blockchain.cpp
C++
mit
65,642
package silent // silent import - e.g. only referenced in Go code, not in json imports // frizz type Silent interface { Silent() }
kego/ke
tests/packer/silent/silent.go
GO
mit
134
module.exports = Transport; var C = { // Transport status codes STATUS_READY: 0, STATUS_DISCONNECTED: 1, STATUS_ERROR: 2 }; /** * Expose C object. */ Transport.C = C; /** * Dependencies. */ var debug = require('debug')('JsSIP:Transport'); var debugerror = require('debug')('JsSIP:ERROR:Transport'); debugerror.log = console.warn.bind(console); var JsSIP_C = require('./Constants'); var Parser = require('./Parser'); var UA = require('./UA'); var SIPMessage = require('./SIPMessage'); var sanityCheck = require('./sanityCheck'); // 'websocket' module uses the native WebSocket interface when bundled to run in a browser. var W3CWebSocket = require('websocket').w3cwebsocket; function Transport(ua, server) { this.ua = ua; this.ws = null; this.server = server; this.reconnection_attempts = 0; this.closed = false; this.connected = false; this.reconnectTimer = null; this.lastTransportError = {}; /** * Options for the Node "websocket" library. */ this.node_websocket_options = this.ua.configuration.node_websocket_options || {}; // Add our User-Agent header. this.node_websocket_options.headers = this.node_websocket_options.headers || {}; this.node_websocket_options.headers['User-Agent'] = JsSIP_C.USER_AGENT; } Transport.prototype = { /** * Connect socket. */ connect: function() { var transport = this; if(this.ws && (this.ws.readyState === this.ws.OPEN || this.ws.readyState === this.ws.CONNECTING)) { debug('WebSocket ' + this.server.ws_uri + ' is already connected'); return false; } if(this.ws) { this.ws.close(); } debug('connecting to WebSocket ' + this.server.ws_uri); this.ua.onTransportConnecting(this, (this.reconnection_attempts === 0)?1:this.reconnection_attempts); try { // Hack in case W3CWebSocket is not the class exported by Node-WebSocket // (may just happen if the above `var W3CWebSocket` line is overriden by // `var W3CWebSocket = global.W3CWebSocket`). if (W3CWebSocket.length > 3) { this.ws = new W3CWebSocket(this.server.ws_uri, 'sip', this.node_websocket_options.origin, this.node_websocket_options.headers, this.node_websocket_options.requestOptions, this.node_websocket_options.clientConfig); } else { this.ws = new W3CWebSocket(this.server.ws_uri, 'sip'); } this.ws.binaryType = 'arraybuffer'; this.ws.onopen = function() { transport.onOpen(); }; this.ws.onclose = function(e) { transport.onClose(e); }; this.ws.onmessage = function(e) { transport.onMessage(e); }; this.ws.onerror = function(e) { transport.onError(e); }; } catch(e) { debugerror('error connecting to WebSocket ' + this.server.ws_uri + ': ' + e); this.lastTransportError.code = null; this.lastTransportError.reason = e.message; this.ua.onTransportError(this); } }, /** * Disconnect socket. */ disconnect: function() { if(this.ws) { // Clear reconnectTimer clearTimeout(this.reconnectTimer); // TODO: should make this.reconnectTimer = null here? this.closed = true; debug('closing WebSocket ' + this.server.ws_uri); this.ws.close(); } // TODO: Why this?? if (this.reconnectTimer !== null) { clearTimeout(this.reconnectTimer); this.reconnectTimer = null; this.ua.onTransportDisconnected({ transport: this, code: this.lastTransportError.code, reason: this.lastTransportError.reason }); } }, /** * Send a message. */ send: function(msg) { var message = msg.toString(); if(this.ws && this.ws.readyState === this.ws.OPEN) { debug('sending WebSocket message:\n%s\n', message); this.ws.send(message); return true; } else { debugerror('unable to send message, WebSocket is not open'); return false; } }, // Transport Event Handlers onOpen: function() { this.connected = true; debug('WebSocket ' + this.server.ws_uri + ' connected'); // Clear reconnectTimer since we are not disconnected if (this.reconnectTimer !== null) { clearTimeout(this.reconnectTimer); this.reconnectTimer = null; } // Reset reconnection_attempts this.reconnection_attempts = 0; // Disable closed this.closed = false; // Trigger onTransportConnected callback this.ua.onTransportConnected(this); }, onClose: function(e) { var connected_before = this.connected; this.connected = false; this.lastTransportError.code = e.code; this.lastTransportError.reason = e.reason; debug('WebSocket disconnected (code: ' + e.code + (e.reason? '| reason: ' + e.reason : '') +')'); if(e.wasClean === false) { debugerror('WebSocket abrupt disconnection'); } // Transport was connected if (connected_before === true) { this.ua.onTransportClosed(this); // Check whether the user requested to close. if(!this.closed) { this.reConnect(); } } else { // This is the first connection attempt // May be a network error (or may be UA.stop() was called) this.ua.onTransportError(this); } }, onMessage: function(e) { var message, transaction, data = e.data; // CRLF Keep Alive response from server. Ignore it. if(data === '\r\n') { debug('received WebSocket message with CRLF Keep Alive response'); return; } // WebSocket binary message. else if (typeof data !== 'string') { try { data = String.fromCharCode.apply(null, new Uint8Array(data)); } catch(evt) { debugerror('received WebSocket binary message failed to be converted into string, message discarded'); return; } debug('received WebSocket binary message:\n%s\n', data); } // WebSocket text message. else { debug('received WebSocket text message:\n%s\n', data); } message = Parser.parseMessage(data, this.ua); if (! message) { return; } if(this.ua.status === UA.C.STATUS_USER_CLOSED && message instanceof SIPMessage.IncomingRequest) { return; } // Do some sanity check if(! sanityCheck(message, this.ua, this)) { return; } if(message instanceof SIPMessage.IncomingRequest) { message.transport = this; this.ua.receiveRequest(message); } else if(message instanceof SIPMessage.IncomingResponse) { /* Unike stated in 18.1.2, if a response does not match * any transaction, it is discarded here and no passed to the core * in order to be discarded there. */ switch(message.method) { case JsSIP_C.INVITE: transaction = this.ua.transactions.ict[message.via_branch]; if(transaction) { transaction.receiveResponse(message); } break; case JsSIP_C.ACK: // Just in case ;-) break; default: transaction = this.ua.transactions.nict[message.via_branch]; if(transaction) { transaction.receiveResponse(message); } break; } } }, onError: function(e) { debugerror('WebSocket connection error: %o', e); }, /** * Reconnection attempt logic. */ reConnect: function() { var transport = this; this.reconnection_attempts += 1; if(this.reconnection_attempts > this.ua.configuration.ws_server_max_reconnection) { debugerror('maximum reconnection attempts for WebSocket ' + this.server.ws_uri); this.ua.onTransportError(this); } else { debug('trying to reconnect to WebSocket ' + this.server.ws_uri + ' (reconnection attempt ' + this.reconnection_attempts + ')'); this.reconnectTimer = setTimeout(function() { transport.connect(); transport.reconnectTimer = null; }, this.ua.configuration.ws_server_reconnection_timeout * 1000); } } };
rusekr/JsSIP
lib/Transport.js
JavaScript
mit
8,034
import { async, fakeAsync, tick, ComponentFixture, TestBed } from '@angular/core/testing'; import { TagsRelatedToTagsComponent } from './tags-related-to-tags.component'; import { Component, EventEmitter, Input, Output } from '@angular/core'; import { By } from '@angular/platform-browser'; import * as _ from 'lodash'; import { Tag } from '../../shared/types'; import { ModelService } from '../../model.service'; @Component({ selector: 'app-select-tags', template: '' }) class SelectTagsStubComponent { // tslint:disable-next-line:no-output-on-prefix @Output() onSelected = new EventEmitter<Tag[]>(); } @Component({ selector: 'app-tag-list', template: '' }) class TagListStubComponent { @Input() tags: Tag[] = []; } class ModelStubService { async findTagsByTags(tagsIn: Tag[]): Promise<Tag[]> { const allTags: Tag[] = [ { tagname: 'tag0' }, { tagname: 'tag1' }, { tagname: 'tag2' }, { tagname: 'tag3' }, { tagname: 'tag4' }, { tagname: 'tag5' }, { tagname: 'tag6' } ]; const tagnamesIn = _.map(tagsIn, (tag: Tag) => tag.tagname); const tagsOut: Tag[] = _.filter(allTags, (tag: Tag) => { return tagnamesIn.indexOf(tag.tagname) === -1; }); return tagsOut; } } describe('TagsRelatedToTagsComponent', () => { let component: TagsRelatedToTagsComponent; let fixture: ComponentFixture<TagsRelatedToTagsComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ TagsRelatedToTagsComponent, SelectTagsStubComponent, TagListStubComponent ], providers: [ { provide: ModelService, useClass: ModelStubService } ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(TagsRelatedToTagsComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should be created', () => { expect(component).toBeTruthy(); }); it('should contain tag selecting component', () => { const tagSelector = fixture.debugElement.query(By.css('app-select-tags')); expect(tagSelector).toBeTruthy(); }); it('should contain tag list component', () => { const tagList = fixture.debugElement.query(By.css('app-tag-list')); expect(tagList).toBeTruthy(); }); it('when tags are selected, related tags should be found and provided to app-tag-list', fakeAsync(() => { const selectTagsComponent = fixture.debugElement.query(By.css('app-select-tags')).componentInstance; const emitter = selectTagsComponent.onSelected; emitter.emit([ { tagname: 'tag0' }, { tagname: 'tag1' }, { tagname: 'tag2' }, { tagname: 'tag3' } ]); const tagListComponent = fixture.debugElement.query(By.css('app-tag-list')).componentInstance; fixture.detectChanges(); tick(); fixture.detectChanges(); expect(tagListComponent.tags.length).toEqual(3); })); });
ditup/ditapp-ng
src/app/tags/tags-related-to-tags/tags-related-to-tags.component.spec.ts
TypeScript
mit
2,949
using System.Collections.Generic; using System.Linq; using Xunit; using static LanguageExt.Prelude; namespace LanguageExt.Tests.Transformer.Traverse.IEnumerableT.Collections { public class QueIEnumerable { [Fact] public void EmptyEmptyIsEmptyEmpty() { Que<IEnumerable<int>> ma = Empty; var mb = ma.Traverse(identity); var mc = Enumerable.Empty<Que<int>>(); Assert.True(mb.ToSeq() == mc.ToSeq()); } [Fact] public void QueIEnumerableCrossProduct() { var ma = Queue<IEnumerable<int>>(Seq(1, 2), Seq(10, 20, 30)); var mb = ma.Traverse(identity); var mc = new[] { Queue(1, 10), Queue(1, 20), Queue(1, 30), Queue(2, 10), Queue(2, 20), Queue(2, 30) } .AsEnumerable(); Assert.True(mb.ToSeq() == mc.ToSeq()); } [Fact] public void QueOfEmptiesAndNonEmptiesIsEmpty() { var ma = Queue<IEnumerable<int>>(Seq<int>(), Seq<int>(1, 2, 3)); var mb = ma.Traverse(identity); var mc = Enumerable.Empty<Que<int>>(); Assert.True(mb.ToSeq() == mc.ToSeq()); } [Fact] public void QueOfEmptiesIsEmpty() { var ma = Queue<IEnumerable<int>>(Seq<int>(), Seq<int>()); var mb = ma.Traverse(identity); var mc = Enumerable.Empty<Que<int>>(); Assert.True(mb.ToSeq() == mc.ToSeq()); } } }
StanJav/language-ext
LanguageExt.Tests/Transformer/Traverse/IEnumerable/Collections/Que.cs
C#
mit
1,668
'use strict'; require('../../../lib/common/init'); var assert = require('assert'), request = require('supertest'), danf = require('../../../lib/server/app')(require('../../fixture/http/danf'), null, {environment: 'test', verbosity: 0, cluster: null}) ; danf.buildServer(function(app) { describe('SessionHandler', function() { it('should allow to get and set values in session', function(done) { request(app) .get('/session/0') .expect(204) .end(function(err, res) { if (err) { if (res) { console.log(res.text); } else { console.log(err); } throw err; } done(); }) ; }) it('should allow to regenerate the session', function(done) { request(app) .get('/session/1') .expect(204) .end(function(err, res) { if (err) { if (res) { console.log(res.text); } else { console.log(err); } throw err; } done(); }) ; }) it('should allow to destroy a session', function(done) { request(app) .get('/session/2') .expect(500) .end(function(err, res) { if (err) { if (res) { /^The session does not exist or has been destroyed\./.test(res.text); } else { /^The session does not exist or has been destroyed\./.test(err); } throw err; } done(); }) ; }) it('should allow to save and reload a session', function(done) { request(app) .get('/session/3') .expect(204) .end(function(err, res) { if (err) { if (res) { console.log(res.text); } else { console.log(err); } throw err; } done(); }) ; }) }) });
Gnucki/danf
test/unit/http/session-handler.js
JavaScript
mit
2,669
require 'uri' module Biller::WHMCSAutoAuth def self.redirect_url(email, action) ensure_autoauth_params time = Time.now.to_i query= ["email=#{email}","timestamp=#{time}", "hash="+ autoauth_hash(email, time), "goto="+ URI.encode("clientarea.php?action=#{action}")].join('&') return [SiteSetting.whmcs_autoauth_url, query].join("?") end private def self.ensure_autoauth_params raise Nilavu::NotFound unless SiteSetting.whmcs_autoauth_url && SiteSetting.whmcs_autoauth_key end def self.autoauth_hash(email, time) Digest::SHA1([email, time,SiteSetting.whmcs_autoauth_key].join('')) end end
jaeko44/nilavu
lib/biller/whmcs_auto_auth.rb
Ruby
mit
701
require 'test_helper' describe Factree::Aggregate do describe ".alternatives" do let(:facts) { :facts } let(:nil_decision) { -> (_) { nil } } let(:final_decision) { -> (_) { conclusion } } let(:conclusion) { Factree::Conclusion.new(:b) } let(:decisions) { [] } subject { Factree::Aggregate.alternatives(facts, *decisions) } describe "with a nil decision followed by a final decision" do let(:decisions) { [nil_decision, final_decision] } it "decides on conclusion" do assert_equal subject, conclusion end end describe "with a final decision followed by a nil decision" do let(:decisions) { [final_decision, nil_decision] } it "decides on conclusion" do assert_equal subject, conclusion end end describe "with only a nil decision" do let(:decisions) { [nil_decision] } it "decides on nil" do assert_nil subject end end it "returns a nil decision" do assert_nil subject end describe "with a mock decision" do let(:mock_decision) { Minitest::Mock.new } let(:decisions) { [mock_decision] } it "passes facts through to decision procs" do mock_decision.expect(:call, nil, [facts]) subject mock_decision.verify end end end end
ConsultingMD/factree
test/factree/aggregate_test.rb
Ruby
mit
1,330
<?php use yii\helpers\Html; /* @var $this yii\web\View */ /* @var $model core\models\Station */ $this->title = 'Create Station'; $this->params['breadcrumbs'][] = ['label' => 'Stations', 'url' => ['index']]; $this->params['breadcrumbs'][] = $this->title; ?> <div class="station-create"> <h1><?= Html::encode($this->title) ?></h1> <?= $this->render('_form', [ 'model' => $model, ]) ?> </div>
tony-wuhongtao/OurYincart2
star-core/modules/station/views/default/create.php
PHP
mit
417
/** * @author Richard Davey <rich@photonstorm.com> * @copyright 2019 Photon Storm Ltd. * @license {@link https://opensource.org/licenses/MIT|MIT License} */ var CONST = require('../../const'); var Smoothing = require('./Smoothing'); // The pool into which the canvas elements are placed. var pool = []; // Automatically apply smoothing(false) to created Canvas elements var _disableContextSmoothing = false; /** * The CanvasPool is a global static object, that allows Phaser to recycle and pool 2D Context Canvas DOM elements. * It does not pool WebGL Contexts, because once the context options are set they cannot be modified again, * which is useless for some of the Phaser pipelines / renderer. * * This singleton is instantiated as soon as Phaser loads, before a Phaser.Game instance has even been created. * Which means all instances of Phaser Games on the same page can share the one single pool. * * @namespace Phaser.Display.Canvas.CanvasPool * @since 3.0.0 */ var CanvasPool = function () { /** * Creates a new Canvas DOM element, or pulls one from the pool if free. * * @function Phaser.Display.Canvas.CanvasPool.create * @since 3.0.0 * * @param {*} parent - The parent of the Canvas object. * @param {integer} [width=1] - The width of the Canvas. * @param {integer} [height=1] - The height of the Canvas. * @param {integer} [canvasType=Phaser.CANVAS] - The type of the Canvas. Either `Phaser.CANVAS` or `Phaser.WEBGL`. * @param {boolean} [selfParent=false] - Use the generated Canvas element as the parent? * * @return {HTMLCanvasElement} The canvas element that was created or pulled from the pool */ var create = function (parent, width, height, canvasType, selfParent) { if (width === undefined) { width = 1; } if (height === undefined) { height = 1; } if (canvasType === undefined) { canvasType = CONST.CANVAS; } if (selfParent === undefined) { selfParent = false; } var canvas; var container = first(canvasType); if (container === null) { container = { parent: parent, canvas: document.createElement('canvas'), type: canvasType }; if (canvasType === CONST.CANVAS) { pool.push(container); } canvas = container.canvas; } else { container.parent = parent; canvas = container.canvas; } if (selfParent) { container.parent = canvas; } canvas.width = width; canvas.height = height; if (_disableContextSmoothing && canvasType === CONST.CANVAS) { Smoothing.disable(canvas.getContext('2d')); } return canvas; }; /** * Creates a new Canvas DOM element, or pulls one from the pool if free. * * @function Phaser.Display.Canvas.CanvasPool.create2D * @since 3.0.0 * * @param {*} parent - The parent of the Canvas object. * @param {integer} [width=1] - The width of the Canvas. * @param {integer} [height=1] - The height of the Canvas. * * @return {HTMLCanvasElement} The created canvas. */ var create2D = function (parent, width, height) { return create(parent, width, height, CONST.CANVAS); }; /** * Creates a new Canvas DOM element, or pulls one from the pool if free. * * @function Phaser.Display.Canvas.CanvasPool.createWebGL * @since 3.0.0 * * @param {*} parent - The parent of the Canvas object. * @param {integer} [width=1] - The width of the Canvas. * @param {integer} [height=1] - The height of the Canvas. * * @return {HTMLCanvasElement} The created WebGL canvas. */ var createWebGL = function (parent, width, height) { return create(parent, width, height, CONST.WEBGL); }; /** * Gets the first free canvas index from the pool. * * @function Phaser.Display.Canvas.CanvasPool.first * @since 3.0.0 * * @param {integer} [canvasType=Phaser.CANVAS] - The type of the Canvas. Either `Phaser.CANVAS` or `Phaser.WEBGL`. * * @return {HTMLCanvasElement} The first free canvas, or `null` if a WebGL canvas was requested or if the pool doesn't have free canvases. */ var first = function (canvasType) { if (canvasType === undefined) { canvasType = CONST.CANVAS; } if (canvasType === CONST.WEBGL) { return null; } for (var i = 0; i < pool.length; i++) { var container = pool[i]; if (!container.parent && container.type === canvasType) { return container; } } return null; }; /** * Looks up a canvas based on its parent, and if found puts it back in the pool, freeing it up for re-use. * The canvas has its width and height set to 1, and its parent attribute nulled. * * @function Phaser.Display.Canvas.CanvasPool.remove * @since 3.0.0 * * @param {*} parent - The canvas or the parent of the canvas to free. */ var remove = function (parent) { // Check to see if the parent is a canvas object var isCanvas = parent instanceof HTMLCanvasElement; pool.forEach(function (container) { if ((isCanvas && container.canvas === parent) || (!isCanvas && container.parent === parent)) { container.parent = null; container.canvas.width = 1; container.canvas.height = 1; } }); }; /** * Gets the total number of used canvas elements in the pool. * * @function Phaser.Display.Canvas.CanvasPool.total * @since 3.0.0 * * @return {integer} The number of used canvases. */ var total = function () { var c = 0; pool.forEach(function (container) { if (container.parent) { c++; } }); return c; }; /** * Gets the total number of free canvas elements in the pool. * * @function Phaser.Display.Canvas.CanvasPool.free * @since 3.0.0 * * @return {integer} The number of free canvases. */ var free = function () { return pool.length - total(); }; /** * Disable context smoothing on any new Canvas element created. * * @function Phaser.Display.Canvas.CanvasPool.disableSmoothing * @since 3.0.0 */ var disableSmoothing = function () { _disableContextSmoothing = true; }; /** * Enable context smoothing on any new Canvas element created. * * @function Phaser.Display.Canvas.CanvasPool.enableSmoothing * @since 3.0.0 */ var enableSmoothing = function () { _disableContextSmoothing = false; }; return { create2D: create2D, create: create, createWebGL: createWebGL, disableSmoothing: disableSmoothing, enableSmoothing: enableSmoothing, first: first, free: free, pool: pool, remove: remove, total: total }; }; // If we export the called function here, it'll only be invoked once (not every time it's required). module.exports = CanvasPool();
mahill/phaser
src/display/canvas/CanvasPool.js
JavaScript
mit
7,526
from .cpu import Cpu
Hexadorsimal/pynes
nes/processors/cpu/__init__.py
Python
mit
21
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <?php require_once("globals.php"); ?> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <?php $page_title = "Projects"; require_once("meta.php"); ?> </head> <body> <div id="logo"> <?php require_once("header.php"); ?> </div> <!-- end of logo --> <div id="header"> <div id="navigation"> <?php require_once("navigation.php"); ?> </div> <!-- end of navigation --> </div> <!-- end of header --> <div id="wrap"> <div id="wrap-btm"> <div id="main"> <div id="content"> <div class="post"> projects </div> </div> <!-- end of content --> <!-- start sidebar --> <div id="sidepanel"> <?php require_once("leftpanel.php"); ?> </div> <div style="clear: both;">&nbsp;</div> </div> <!-- end of main --> </div> <!-- end of wrap --> </div> <!-- end of wrap-btm --> <div id="footer-wrap"> <div id="footer"> <?php require_once("footer.php"); ?> </div> </div> <!-- end of footer --> </body> </html>
JayWalker512/brandonfoltz.com
projects.php
PHP
mit
1,055
<?php /** * * Copyright © 2013-2017 Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\Tax\Controller\Adminhtml\Rule; use Magento\Framework\Controller\ResultFactory; class Delete extends \Magento\Tax\Controller\Adminhtml\Rule { /** * @return \Magento\Backend\Model\View\Result\Redirect */ public function execute() { /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); $ruleId = (int)$this->getRequest()->getParam('rule'); try { $this->ruleService->deleteById($ruleId); $this->messageManager->addSuccess(__('The tax rule has been deleted.')); return $resultRedirect->setPath('tax/*/'); } catch (\Magento\Framework\Exception\NoSuchEntityException $e) { $this->messageManager->addError(__('This rule no longer exists.')); return $resultRedirect->setPath('tax/*/'); } catch (\Magento\Framework\Exception\LocalizedException $e) { $this->messageManager->addError($e->getMessage()); } catch (\Exception $e) { $this->messageManager->addError(__('Something went wrong deleting this tax rule.')); } return $resultRedirect->setUrl($this->_redirect->getRedirectUrl($this->getUrl('*'))); } }
j-froehlich/magento2_wk
vendor/magento/module-tax/Controller/Adminhtml/Rule/Delete.php
PHP
mit
1,412
/// <reference path="initialization.ts" /> function initializeAppInsights() { try { // only initialize if we are running in a browser that supports JSON serialization (ie7<, node.js, cordova) if (typeof window !== "undefined" && typeof JSON !== "undefined") { // get snippet or initialize to an empty object var aiName = "appInsights"; if (window[aiName] === undefined) { // if no snippet is present, initialize default values Microsoft.ApplicationInsights.AppInsights.defaultConfig = Microsoft.ApplicationInsights.Initialization.getDefaultConfig(); } else { // this is the typical case for browser+snippet var snippet: Microsoft.ApplicationInsights.Snippet = window[aiName] || <any>{}; // overwrite snippet with full appInsights var init = new Microsoft.ApplicationInsights.Initialization(snippet); var appInsightsLocal = init.loadAppInsights(); // apply full appInsights to the global instance that was initialized in the snippet for (var field in appInsightsLocal) { snippet[field] = appInsightsLocal[field]; } init.emptyQueue(); init.pollInteralLogs(appInsightsLocal); init.addHousekeepingBeforeUnload(appInsightsLocal); } } } catch (e) { console.error('Failed to initialize AppInsights JS SDK: ' + e.message); } } initializeAppInsights();
reyno-uk/ApplicationInsights-JS
JavaScript/JavaScriptSDK/Init.ts
TypeScript
mit
1,610
import React from 'react'; import { Link as RouterLink } from 'react-router'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import counterActions from 'actions/counter'; import Radium from 'radium'; import { Scroll, Link, Element, Events } from 'react-scroll'; import { FlatButton, Paper } from 'material-ui/lib'; import { styles } from 'styles/HomeViewStyles'; const mapStateToProps = (state) => ({ counter: state.counter, routerState: state.router }); const mapDispatchToProps = (dispatch) => ({ actions: bindActionCreators(counterActions, dispatch) }); @Radium class HomeView extends React.Component { static propTypes = { actions: React.PropTypes.object, counter: React.PropTypes.number } render() { return ( <div className='landing main-body' style={styles.mainBody}> <div style={styles.heroDiv}> <img src={require('styles/assets/splash3.png')} style={styles.heroImg} draggable='false' /> <div style={styles.heroText}> a simple, intuitive, <br/>drag-and-drop resume builder </div> {Radium.getState(this.state, 'callToAction', 'hover')} <RouterLink to='/resume'> <div style={styles.callToAction} key='callToAction'> get started </div> </RouterLink> {Radium.getState(this.state, 'circle', 'hover')} <Link to='Features' spy={true} smooth={true} duration={800}> <div style={styles.circle} key='circle'> <img src={require('styles/assets/downArrow.png')} style={styles.downArrow} /> </div> </Link> <div style={styles.diagonalLine}></div> </div> <div style={styles.grayDivMiddle}> <div style={styles.copy}> <Element name='Features'> <div style={styles.wysiwyg}>what you see is what you get</div> <div style={styles.video}> <iframe src="https://player.vimeo.com/video/149104789?color=ff9f10&title=0&byline=0&portrait=0" width="500" height="281" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe> </div> </Element> <div style={styles.middleCopy}> <div>Import your information from LinkedIn</div> <div>Save your progress to the cloud</div> <div>Easily print or export to PDF when you're done</div> </div> <RouterLink to='/resume'> <div style={styles.getStartedButton}> get started </div> </RouterLink> </div> </div> </div> ); } } export default connect(mapStateToProps, mapDispatchToProps)(HomeView); /* Here lies the counter. It was a good counter; it incremented when clicked. But it was more than just a simple counter. It was a window into another world; a stateful lighthouse to our souls. The counter is dead. Long live the counter! <div style={{ margin: '20px' }}> <div style={{ margin: '5px' }}> For no reason, a counter: {this.props.counter} </div> <RaisedButton label='Increment' onClick={this.props.actions.increment} /> </div> */
dont-fear-the-repo/fear-the-repo
src/views/HomeView.js
JavaScript
mit
3,354
require 'test_helper' class LockableTest < ActiveSupport::TestCase def setup setup_mailer end test "should respect maximum attempts configuration" do user = create_user user.confirm! swap Devise, :maximum_attempts => 2 do 3.times { user.valid_for_authentication?{ false } } assert user.reload.access_locked? end end test "should increment failed_attempts on successfull validation if the user is already locked" do user = create_user user.confirm! swap Devise, :maximum_attempts => 2 do 3.times { user.valid_for_authentication?{ false } } assert user.reload.access_locked? end user.valid_for_authentication?{ true } assert_equal 4, user.reload.failed_attempts end test "should not touch failed_attempts if lock_strategy is none" do user = create_user user.confirm! swap Devise, :lock_strategy => :none, :maximum_attempts => 2 do 3.times { user.valid_for_authentication?{ false } } assert !user.access_locked? assert_equal 0, user.failed_attempts end end test 'should be valid for authentication with a unlocked user' do user = create_user user.lock_access! user.unlock_access! assert user.valid_for_authentication?{ true } end test "should verify whether a user is locked or not" do user = create_user assert_not user.access_locked? user.lock_access! assert user.access_locked? end test "active_for_authentication? should be the opposite of locked?" do user = create_user user.confirm! assert user.active_for_authentication? user.lock_access! assert_not user.active_for_authentication? end test "should unlock a user by cleaning locked_at, falied_attempts and unlock_token" do user = create_user user.lock_access! assert_not_nil user.reload.locked_at assert_not_nil user.reload.unlock_token user.unlock_access! assert_nil user.reload.locked_at assert_nil user.reload.unlock_token assert_equal 0, user.reload.failed_attempts end test "new user should not be locked and should have zero failed_attempts" do assert_not new_user.access_locked? assert_equal 0, create_user.failed_attempts end test "should unlock user after unlock_in period" do swap Devise, :unlock_in => 3.hours do user = new_user user.locked_at = 2.hours.ago assert user.access_locked? Devise.unlock_in = 1.hour assert_not user.access_locked? end end test "should not unlock in 'unlock_in' if :time unlock strategy is not set" do swap Devise, :unlock_strategy => :email do user = new_user user.locked_at = 2.hours.ago assert user.access_locked? end end test "should set unlock_token when locking" do user = create_user assert_nil user.unlock_token user.lock_access! assert_not_nil user.unlock_token end test "should never generate the same unlock token for different users" do unlock_tokens = [] 3.times do user = create_user user.lock_access! token = user.unlock_token assert !unlock_tokens.include?(token) unlock_tokens << token end end test "should not generate unlock_token when :email is not an unlock strategy" do swap Devise, :unlock_strategy => :time do user = create_user user.lock_access! assert_nil user.unlock_token end end test "should send email with unlock instructions when :email is an unlock strategy" do swap Devise, :unlock_strategy => :email do user = create_user assert_email_sent do user.lock_access! end end end test "should not send email with unlock instructions when :email is not an unlock strategy" do swap Devise, :unlock_strategy => :time do user = create_user assert_email_not_sent do user.lock_access! end end end test 'should find and unlock a user automatically' do user = create_user user.lock_access! locked_user = User.unlock_access_by_token(user.unlock_token) assert_equal locked_user, user assert_not user.reload.access_locked? end test 'should return a new record with errors when a invalid token is given' do locked_user = User.unlock_access_by_token('invalid_token') assert_not locked_user.persisted? assert_equal "is invalid", locked_user.errors[:unlock_token].join end test 'should return a new record with errors when a blank token is given' do locked_user = User.unlock_access_by_token('') assert_not locked_user.persisted? assert_equal "can't be blank", locked_user.errors[:unlock_token].join end test 'should find a user to send unlock instructions' do user = create_user user.lock_access! unlock_user = User.send_unlock_instructions(:email => user.email) assert_equal unlock_user, user end test 'should return a new user if no email was found' do unlock_user = User.send_unlock_instructions(:email => "invalid@example.com") assert_not unlock_user.persisted? end test 'should add error to new user email if no email was found' do unlock_user = User.send_unlock_instructions(:email => "invalid@example.com") assert_equal 'not found', unlock_user.errors[:email].join end test 'should find a user to send unlock instructions by authentication_keys' do swap Devise, :authentication_keys => [:username, :email] do user = create_user unlock_user = User.send_unlock_instructions(:email => user.email, :username => user.username) assert_equal unlock_user, user end end test 'should require all unlock_keys' do swap Devise, :unlock_keys => [:username, :email] do user = create_user unlock_user = User.send_unlock_instructions(:email => user.email) assert_not unlock_user.persisted? assert_equal "can't be blank", unlock_user.errors[:username].join end end test 'should not be able to send instructions if the user is not locked' do user = create_user assert_not user.resend_unlock_token assert_not user.access_locked? assert_equal 'was not locked', user.errors[:email].join end test 'should unlock account if lock has expired and increase attempts on failure' do swap Devise, :unlock_in => 1.minute do user = create_user user.confirm! user.failed_attempts = 2 user.locked_at = 2.minutes.ago user.valid_for_authentication? { false } assert_equal 1, user.failed_attempts end end test 'should unlock account if lock has expired on success' do swap Devise, :unlock_in => 1.minute do user = create_user user.confirm! user.failed_attempts = 2 user.locked_at = 2.minutes.ago user.valid_for_authentication? { true } assert_equal 0, user.failed_attempts assert_nil user.locked_at end end test 'required_fields should contain the all the fields when all the strategies are enabled' do swap Devise, :unlock_strategy => :both do swap Devise, :lock_strategy => :failed_attempts do assert_same_content Devise::Models::Lockable.required_fields(User), [ :failed_attempts, :locked_at, :unlock_token ] end end end test 'required_fields should contain only failed_attempts and locked_at when the strategies are time and failed_attempts are enabled' do swap Devise, :unlock_strategy => :time do swap Devise, :lock_strategy => :failed_attempts do assert_same_content Devise::Models::Lockable.required_fields(User), [ :failed_attempts, :locked_at ] end end end test 'required_fields should contain only failed_attempts and unlock_token when the strategies are token and failed_attempts are enabled' do swap Devise, :unlock_strategy => :email do swap Devise, :lock_strategy => :failed_attempts do assert_same_content Devise::Models::Lockable.required_fields(User), [ :failed_attempts, :unlock_token ] end end end test 'should not return a locked unauthenticated message if in paranoid mode' do swap Devise, :paranoid => :true do user = create_user user.failed_attempts = Devise.maximum_attempts + 1 user.lock_access! assert_equal :invalid, user.unauthenticated_message end end end
piousbox/microsites2-cities
vendor/ruby/1.9.1/gems/devise-2.2.3/test/models/lockable_test.rb
Ruby
mit
8,403
#! /usr/bin/python2 # # Copyright 2016 the V8 project authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # import argparse import collections import re import subprocess import sys __DESCRIPTION = """ Processes a perf.data sample file and reports the hottest Ignition bytecodes, or write an input file for flamegraph.pl. """ __HELP_EPILOGUE = """ examples: # Get a flamegraph for Ignition bytecode handlers on Octane benchmark, # without considering the time spent compiling JS code, entry trampoline # samples and other non-Ignition samples. # $ tools/run-perf.sh out/x64.release/d8 \\ --ignition --noturbo --noopt run.js $ tools/ignition/linux_perf_report.py --flamegraph -o out.collapsed $ flamegraph.pl --colors js out.collapsed > out.svg # Same as above, but show all samples, including time spent compiling JS code, # entry trampoline samples and other samples. $ # ... $ tools/ignition/linux_perf_report.py \\ --flamegraph --show-all -o out.collapsed $ # ... # Same as above, but show full function signatures in the flamegraph. $ # ... $ tools/ignition/linux_perf_report.py \\ --flamegraph --show-full-signatures -o out.collapsed $ # ... # See the hottest bytecodes on Octane benchmark, by number of samples. # $ tools/run-perf.sh out/x64.release/d8 \\ --ignition --noturbo --noopt octane/run.js $ tools/ignition/linux_perf_report.py """ COMPILER_SYMBOLS_RE = re.compile( r"v8::internal::(?:\(anonymous namespace\)::)?Compile|v8::internal::Parser") JIT_CODE_SYMBOLS_RE = re.compile( r"(LazyCompile|Compile|Eval|Script):(\*|~)") GC_SYMBOLS_RE = re.compile( r"v8::internal::Heap::CollectGarbage") def strip_function_parameters(symbol): if symbol[-1] != ')': return symbol pos = 1 parenthesis_count = 0 for c in reversed(symbol): if c == ')': parenthesis_count += 1 elif c == '(': parenthesis_count -= 1 if parenthesis_count == 0: break else: pos += 1 return symbol[:-pos] def collapsed_callchains_generator(perf_stream, hide_other=False, hide_compiler=False, hide_jit=False, hide_gc=False, show_full_signatures=False): current_chain = [] skip_until_end_of_chain = False compiler_symbol_in_chain = False for line in perf_stream: # Lines starting with a "#" are comments, skip them. if line[0] == "#": continue line = line.strip() # Empty line signals the end of the callchain. if not line: if (not skip_until_end_of_chain and current_chain and not hide_other): current_chain.append("[other]") yield current_chain # Reset parser status. current_chain = [] skip_until_end_of_chain = False compiler_symbol_in_chain = False continue if skip_until_end_of_chain: continue # Trim the leading address and the trailing +offset, if present. symbol = line.split(" ", 1)[1].split("+", 1)[0] if not show_full_signatures: symbol = strip_function_parameters(symbol) # Avoid chains of [unknown] if (symbol == "[unknown]" and current_chain and current_chain[-1] == "[unknown]"): continue current_chain.append(symbol) if symbol.startswith("BytecodeHandler:"): current_chain.append("[interpreter]") yield current_chain skip_until_end_of_chain = True elif JIT_CODE_SYMBOLS_RE.match(symbol): if not hide_jit: current_chain.append("[jit]") yield current_chain skip_until_end_of_chain = True elif GC_SYMBOLS_RE.match(symbol): if not hide_gc: current_chain.append("[gc]") yield current_chain skip_until_end_of_chain = True elif symbol == "Stub:CEntryStub" and compiler_symbol_in_chain: if not hide_compiler: current_chain.append("[compiler]") yield current_chain skip_until_end_of_chain = True elif COMPILER_SYMBOLS_RE.match(symbol): compiler_symbol_in_chain = True elif symbol == "Builtin:InterpreterEntryTrampoline": if len(current_chain) == 1: yield ["[entry trampoline]"] else: # If we see an InterpreterEntryTrampoline which is not at the top of the # chain and doesn't have a BytecodeHandler above it, then we have # skipped the top BytecodeHandler due to the top-level stub not building # a frame. File the chain in the [misattributed] bucket. current_chain[-1] = "[misattributed]" yield current_chain skip_until_end_of_chain = True def calculate_samples_count_per_callchain(callchains): chain_counters = collections.defaultdict(int) for callchain in callchains: key = ";".join(reversed(callchain)) chain_counters[key] += 1 return chain_counters.items() def calculate_samples_count_per_handler(callchains): def strip_handler_prefix_if_any(handler): return handler if handler[0] == "[" else handler.split(":", 1)[1] handler_counters = collections.defaultdict(int) for callchain in callchains: handler = strip_handler_prefix_if_any(callchain[-1]) handler_counters[handler] += 1 return handler_counters.items() def write_flamegraph_input_file(output_stream, callchains): for callchain, count in calculate_samples_count_per_callchain(callchains): output_stream.write("{}; {}\n".format(callchain, count)) def write_handlers_report(output_stream, callchains): handler_counters = calculate_samples_count_per_handler(callchains) samples_num = sum(counter for _, counter in handler_counters) # Sort by decreasing number of samples handler_counters.sort(key=lambda entry: entry[1], reverse=True) for bytecode_name, count in handler_counters: output_stream.write( "{}\t{}\t{:.3f}%\n".format(bytecode_name, count, 100. * count / samples_num)) def parse_command_line(): command_line_parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, description=__DESCRIPTION, epilog=__HELP_EPILOGUE) command_line_parser.add_argument( "perf_filename", help="perf sample file to process (default: perf.data)", nargs="?", default="perf.data", metavar="<perf filename>" ) command_line_parser.add_argument( "--flamegraph", "-f", help="output an input file for flamegraph.pl, not a report", action="store_true", dest="output_flamegraph" ) command_line_parser.add_argument( "--hide-other", help="Hide other samples", action="store_true" ) command_line_parser.add_argument( "--hide-compiler", help="Hide samples during compilation", action="store_true" ) command_line_parser.add_argument( "--hide-jit", help="Hide samples from JIT code execution", action="store_true" ) command_line_parser.add_argument( "--hide-gc", help="Hide samples from garbage collection", action="store_true" ) command_line_parser.add_argument( "--show-full-signatures", "-s", help="show full signatures instead of function names", action="store_true" ) command_line_parser.add_argument( "--output", "-o", help="output file name (stdout if omitted)", type=argparse.FileType('wt'), default=sys.stdout, metavar="<output filename>", dest="output_stream" ) return command_line_parser.parse_args() def main(): program_options = parse_command_line() perf = subprocess.Popen(["perf", "script", "--fields", "ip,sym", "-i", program_options.perf_filename], stdout=subprocess.PIPE) callchains = collapsed_callchains_generator( perf.stdout, program_options.hide_other, program_options.hide_compiler, program_options.hide_jit, program_options.hide_gc, program_options.show_full_signatures) if program_options.output_flamegraph: write_flamegraph_input_file(program_options.output_stream, callchains) else: write_handlers_report(program_options.output_stream, callchains) if __name__ == "__main__": main()
hoho/dosido
nodejs/deps/v8/tools/ignition/linux_perf_report.py
Python
mit
8,176
/******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = "./app.ts"); /******/ }) /************************************************************************/ /******/ ({ /***/ "./app.ts": /*!****************!*\ !*** ./app.ts ***! \****************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; eval("\nexports.__esModule = true;\nconsole.log('do something');\n// The DEBUG constant will be inlined by webpack's DefinePlugin (see config)\n// The whole if-statement can then be removed by UglifyJS\nif (false) { var debug; }\nconsole.log('do something else');\n\n\n//# sourceURL=webpack:///./app.ts?"); /***/ }) /******/ });
jbrantly/ts-loader
test/comparison-tests/conditionalRequire/expectedOutput-2.8/bundle.js
JavaScript
mit
3,132
<?php namespace ApplicationInsights\Channel\Contracts; /** * Contains utilities for contract classes */ class Utils { /** * Removes NULL and empty collections * @param array $sourceArray * @return array */ public static function removeEmptyValues($sourceArray) { $newArray = array(); foreach ($sourceArray as $key => $value) { if ((is_array($value) && sizeof($value) == 0) || ($value == NULL && is_bool($value) == false)) { continue; } $newArray[$key] = $value; } return $newArray; } /** * Serialization helper. * @param array Items to serialize * @return array JSON serialized items, nested */ public static function getUnderlyingData($dataItems) { $queueToEncode = array(); foreach ($dataItems as $key => $dataItem) { if (method_exists($dataItem, 'jsonSerialize') == true) { $queueToEncode[$key] = Utils::getUnderlyingData($dataItem->jsonSerialize()); } else if (is_array($dataItem)) { $queueToEncode[$key] = Utils::getUnderlyingData($dataItem); } else { $queueToEncode[$key] = $dataItem; } } return $queueToEncode; } /** * Converts milliseconds to a timespan string as accepted by the backend * @param int $milliseconds * @return string */ public static function convertMillisecondsToTimeSpan($milliseconds) { if ($milliseconds == NULL || $milliseconds < 0) { $milliseconds = 0; } $ms = $milliseconds % 1000; $sec = floor($milliseconds / 1000) % 60; $min = floor($milliseconds / (1000 * 60)) % 60; $hour = floor($milliseconds / (1000 * 60 * 60)) % 24; $ms = strlen($ms) == 1 ? '00' . $ms : (strlen($ms) === 2 ? "0" . $ms : $ms); $sec = strlen($sec) < 2 ? '0' . $sec : $sec; $min = strlen($min) < 2 ? '0' . $min : $min; $hour = strlen($hour) < 2 ? '0' . $hour : $hour; return $hour . ":" . $min . ":" . $sec . "." . $ms; } /** * Returns the proper ISO string for Application Insights service to accept. * @param mixed $time * @return string */ public static function returnISOStringForTime($time = null) { if ($time == NULL) { return gmdate('c') . 'Z'; } else { return gmdate('c', $time) . 'Z'; } } /** * Returns a Guid on all flavors of PHP. Copied from the PHP manual: http://php.net/manual/en/function.com-create-guid.php * @return mixed */ public static function returnGuid() { if (function_exists('com_create_guid') === true) { return trim(com_create_guid(), '{}'); } return sprintf('%04X%04X-%04X-%04X-%04X-%04X%04X%04X', mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(16384, 20479), mt_rand(32768, 49151), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535)); } }
fidmor89/appInsights-Concrete
appinsights/vendor/microsoft/application-insights/ApplicationInsights/Channel/Contracts/Utils.php
PHP
mit
3,254
/* */ var cof = require("./_cof"), TAG = require("./_wks")('toStringTag'), ARG = cof(function() { return arguments; }()) == 'Arguments'; module.exports = function(it) { var O, T, B; return it === undefined ? 'Undefined' : it === null ? 'Null' : typeof(T = (O = Object(it))[TAG]) == 'string' ? T : ARG ? cof(O) : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B; };
jdanyow/aurelia-plunker
jspm_packages/npm/core-js@2.1.0/modules/_classof.js
JavaScript
mit
427
/*! * address.js - address object for decentraland * Copyright (c) 2014-2015, Fedor Indutny (MIT License) * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License). * Copyright (c) 2016-2017, Manuel Araoz (MIT License). * https://github.com/decentraland/decentraland-node */ 'use strict'; var networks = require('../protocol/networks'); var constants = require('../protocol/constants'); var util = require('../utils/util'); var crypto = require('../crypto/crypto'); var assert = require('assert'); var BufferReader = require('../utils/reader'); var StaticWriter = require('../utils/staticwriter'); var base58 = require('../utils/base58'); var scriptTypes = constants.scriptTypes; /** * Represents an address. * @exports Address * @constructor * @param {Object} options * @param {Buffer|Hash} options.hash - Address hash. * @param {AddressType} options.type - Address type * `{witness,}{pubkeyhash,scripthash}`. * @param {Number} [options.version=-1] - Witness program version. * @property {Buffer} hash * @property {AddressType} type * @property {Number} version */ function Address(options) { if (!(this instanceof Address)) return new Address(options); this.hash = constants.ZERO_HASH160; this.type = scriptTypes.PUBKEYHASH; this.version = -1; var Network = require('../protocol/network'); this.network = Network.primary; if (options) this.fromOptions(options); } /** * Address types. * @enum {Number} */ Address.types = scriptTypes; /** * Inject properties from options object. * @private * @param {Object} options */ Address.prototype.fromOptions = function fromOptions(options) { if (typeof options === 'string') return this.fromBase58(options); if (Buffer.isBuffer(options)) return this.fromRaw(options); return this.fromHash( options.hash, options.type, options.version, options.network ); }; /** * Insantiate address from options. * @param {Object} options * @returns {Address} */ Address.fromOptions = function fromOptions(options) { return new Address().fromOptions(options); }; /** * Get the address hash. * @param {String?} enc - Can be `"hex"` or `null`. * @returns {Hash|Buffer} */ Address.prototype.getHash = function getHash(enc) { if (enc === 'hex') return this.hash.toString(enc); return this.hash; }; /** * Get a network address prefix for the address. * @returns {Number} */ Address.prototype.getPrefix = function getPrefix(network) { if (!network) network = this.network; var Network = require('../protocol/network'); network = Network.get(network); return Address.getPrefix(this.type, network); }; /** * Verify an address network (compares prefixes). * @returns {Boolean} */ Address.prototype.verifyNetwork = function verifyNetwork(network) { assert(network); return this.getPrefix() === this.getPrefix(network); }; /** * Get the address type as a string. * @returns {AddressType} */ Address.prototype.getType = function getType() { return constants.scriptTypesByVal[this.type].toLowerCase(); }; /** * Calculate size of serialized address. * @returns {Number} */ Address.prototype.getSize = function getSize() { var size = 5 + this.hash.length; if (this.version !== -1) size += 2; return size; }; /** * Compile the address object to its raw serialization. * @returns {Buffer} * @throws Error on bad hash/prefix. */ Address.prototype.toRaw = function toRaw(network) { var size = this.getSize(); var bw = new StaticWriter(size); var prefix = this.getPrefix(network); assert(prefix !== -1, 'Not a valid address prefix.'); bw.writeU8(prefix); if (this.version !== -1) { bw.writeU8(this.version); bw.writeU8(0); } bw.writeBytes(this.hash); bw.writeChecksum(); return bw.render(); }; /** * Compile the address object to a base58 address. * @returns {Base58Address} * @throws Error on bad hash/prefix. */ Address.prototype.toBase58 = function toBase58(network) { return base58.encode(this.toRaw(network)); }; /** * Convert the Address to a string. * @returns {Base58Address} */ Address.prototype.toString = function toString() { return this.toBase58(); }; /** * Inspect the Address. * @returns {Object} */ Address.prototype.inspect = function inspect() { return '<Address:' + ' type=' + this.getType() + ' version=' + this.version + ' base58=' + this.toBase58() + '>'; }; /** * Inject properties from serialized data. * @private * @param {Buffer} data * @throws Parse error */ Address.prototype.fromRaw = function fromRaw(data) { var br = new BufferReader(data, true); var i, prefix, network, type, version, hash; prefix = br.readU8(); for (i = 0; i < networks.types.length; i++) { network = networks[networks.types[i]]; type = Address.getType(prefix, network); if (type !== -1) break; } assert(i < networks.types.length, 'Unknown address prefix.'); if (data.length > 25) { version = br.readU8(); assert(br.readU8() === 0, 'Address version padding is non-zero.'); } else { version = -1; } hash = br.readBytes(br.left() - 4); br.verifyChecksum(); return this.fromHash(hash, type, version, network.type); }; /** * Create an address object from a serialized address. * @param {Buffer} data * @returns {Address} * @throws Parse error. */ Address.fromRaw = function fromRaw(data) { return new Address().fromRaw(data); }; /** * Inject properties from base58 address. * @private * @param {Base58Address} data * @throws Parse error */ Address.prototype.fromBase58 = function fromBase58(data) { assert(typeof data === 'string'); return this.fromRaw(base58.decode(data)); }; /** * Create an address object from a base58 address. * @param {Base58Address} address * @returns {Address} * @throws Parse error. */ Address.fromBase58 = function fromBase58(address) { return new Address().fromBase58(address); }; /** * Inject properties from output script. * @private * @param {Script} script */ Address.prototype.fromScript = function fromScript(script) { if (script.isPubkey()) { this.hash = crypto.hash160(script.get(0)); this.type = scriptTypes.PUBKEYHASH; this.version = -1; return this; } if (script.isPubkeyhash()) { this.hash = script.get(2); this.type = scriptTypes.PUBKEYHASH; this.version = -1; return this; } if (script.isScripthash()) { this.hash = script.get(1); this.type = scriptTypes.SCRIPTHASH; this.version = -1; return this; } if (script.isWitnessPubkeyhash()) { this.hash = script.get(1); this.type = scriptTypes.WITNESSPUBKEYHASH; this.version = 0; return this; } if (script.isWitnessScripthash()) { this.hash = script.get(1); this.type = scriptTypes.WITNESSSCRIPTHASH; this.version = 0; return this; } if (script.isWitnessMasthash()) { this.hash = script.get(1); this.type = scriptTypes.WITNESSSCRIPTHASH; this.version = 1; return this; } // Put this last: it's the slowest to check. if (script.isMultisig()) { this.hash = script.hash160(); this.type = scriptTypes.SCRIPTHASH; this.version = -1; return this; } }; /** * Inject properties from witness. * @private * @param {Witness} witness */ Address.prototype.fromWitness = function fromWitness(witness) { // We're pretty much screwed here // since we can't get the version. if (witness.isPubkeyhashInput()) { this.hash = crypto.hash160(witness.get(1)); this.type = scriptTypes.WITNESSPUBKEYHASH; this.version = 0; return this; } if (witness.isScripthashInput()) { this.hash = crypto.sha256(witness.get(witness.length - 1)); this.type = scriptTypes.WITNESSSCRIPTHASH; this.version = 0; return this; } }; /** * Inject properties from input script. * @private * @param {Script} script */ Address.prototype.fromInputScript = function fromInputScript(script) { if (script.isPubkeyhashInput()) { this.hash = crypto.hash160(script.get(1)); this.type = scriptTypes.PUBKEYHASH; this.version = -1; return this; } if (script.isScripthashInput()) { this.hash = crypto.hash160(script.get(script.length - 1)); this.type = scriptTypes.SCRIPTHASH; this.version = -1; return this; } }; /** * Create an Address from a witness. * Attempt to extract address * properties from a witness. * @param {Witness} * @returns {Address|null} */ Address.fromWitness = function fromWitness(witness) { return new Address().fromWitness(witness); }; /** * Create an Address from an input script. * Attempt to extract address * properties from an input script. * @param {Script} * @returns {Address|null} */ Address.fromInputScript = function fromInputScript(script) { return new Address().fromInputScript(script); }; /** * Create an Address from an output script. * Parse an output script and extract address * properties. Converts pubkey and multisig * scripts to pubkeyhash and scripthash addresses. * @param {Script} * @returns {Address|null} */ Address.fromScript = function fromScript(script) { return new Address().fromScript(script); }; /** * Inject properties from a hash. * @private * @param {Buffer|Hash} hash * @param {AddressType} type * @param {Number} [version=-1] * @throws on bad hash size */ Address.prototype.fromHash = function fromHash(hash, type, version, network) { if (typeof hash === 'string') hash = new Buffer(hash, 'hex'); if (typeof type === 'string') type = scriptTypes[type.toUpperCase()]; if (type == null) type = scriptTypes.PUBKEYHASH; if (version == null) version = -1; var Network = require('../protocol/network'); network = Network.get(network); assert(Buffer.isBuffer(hash)); assert(util.isNumber(type)); assert(util.isNumber(version)); assert(Address.getPrefix(type, network) !== -1, 'Not a valid address type.'); if (version === -1) { assert(!Address.isWitness(type), 'Wrong version (witness)'); assert(hash.length === 20, 'Hash is the wrong size.'); } else { assert(Address.isWitness(type), 'Wrong version (non-witness).'); assert(version >= 0 && version <= 16, 'Bad program version.'); if (version === 0 && type === scriptTypes.WITNESSPUBKEYHASH) assert(hash.length === 20, 'Hash is the wrong size.'); else if (version === 0 && type === scriptTypes.WITNESSSCRIPTHASH) assert(hash.length === 32, 'Hash is the wrong size.'); else if (version === 1 && type === scriptTypes.WITNESSSCRIPTHASH) assert(hash.length === 32, 'Hash is the wrong size.'); } this.hash = hash; this.type = type; this.version = version; this.network = network; return this; }; /** * Create a naked address from hash/type/version. * @param {Buffer|Hash} hash * @param {AddressType} type * @param {Number} [version=-1] * @returns {Address} * @throws on bad hash size */ Address.fromHash = function fromHash(hash, type, version, network) { return new Address().fromHash(hash, type, version, network); }; /** * Inject properties from data. * @private * @param {Buffer|Buffer[]} data * @param {AddressType} type * @param {Number} [version=-1] */ Address.prototype.fromData = function fromData(data, type, version, network) { if (typeof type === 'string') type = scriptTypes[type.toUpperCase()]; if (type === scriptTypes.WITNESSSCRIPTHASH) { if (version === 0) { assert(Buffer.isBuffer(data)); data = crypto.sha256(data); } else if (version === 1) { assert(Array.isArray(data)); throw new Error('MASTv2 creation not implemented.'); } else { throw new Error('Cannot create from version=' + version); } } else if (type === scriptTypes.WITNESSPUBKEYHASH) { if (version !== 0) throw new Error('Cannot create from version=' + version); assert(Buffer.isBuffer(data)); data = crypto.hash160(data); } else { data = crypto.hash160(data); } return this.fromHash(data, type, version, network); }; /** * Create an Address from data/type/version. * @param {Buffer|Buffer[]} data - Data to be hashed. * Normally a buffer, but can also be an array of * buffers for MAST. * @param {AddressType} type * @param {Number} [version=-1] * @returns {Address} * @throws on bad hash size */ Address.fromData = function fromData(data, type, version, network) { return new Address().fromData(data, type, version, network); }; /** * Validate an address, optionally test against a type. * @param {Base58Address} address * @param {AddressType} * @returns {Boolean} */ Address.validate = function validate(address, type) { if (!address) return false; if (!Buffer.isBuffer(address) && typeof address !== 'string') return false; try { address = Address.fromBase58(address); } catch (e) { return false; } if (typeof type === 'string') type = scriptTypes[type.toUpperCase()]; if (type && address.type !== type) return false; return true; }; /** * Get the hex hash of a base58 * address or address object. * @param {Base58Address|Address} data * @returns {Hash|null} */ Address.getHash = function getHash(data, enc) { var hash; if (typeof data === 'string') { if (data.length === 40 || data.length === 64) return enc === 'hex' ? data : new Buffer(data, 'hex'); try { hash = Address.fromBase58(data).hash; } catch (e) { return; } } else if (Buffer.isBuffer(data)) { hash = data; } else if (data instanceof Address) { hash = data.hash; } else { return; } return enc === 'hex' ? hash.toString('hex') : hash; }; /** * Get a network address prefix for a specified address type. * @param {AddressType} type * @returns {Number} */ Address.getPrefix = function getPrefix(type, network) { var prefixes = network.addressPrefix; switch (type) { case scriptTypes.PUBKEYHASH: return prefixes.pubkeyhash; case scriptTypes.SCRIPTHASH: return prefixes.scripthash; case scriptTypes.WITNESSPUBKEYHASH: return prefixes.witnesspubkeyhash; case scriptTypes.WITNESSSCRIPTHASH: return prefixes.witnessscripthash; default: return -1; } }; /** * Get an address type for a specified network address prefix. * @param {Number} prefix * @returns {AddressType} */ Address.getType = function getType(prefix, network) { var prefixes = network.addressPrefix; switch (prefix) { case prefixes.pubkeyhash: return scriptTypes.PUBKEYHASH; case prefixes.scripthash: return scriptTypes.SCRIPTHASH; case prefixes.witnesspubkeyhash: return scriptTypes.WITNESSPUBKEYHASH; case prefixes.witnessscripthash: return scriptTypes.WITNESSSCRIPTHASH; default: return -1; } }; /** * Test whether an address type is a witness program. * @param {AddressType} type * @returns {Boolean} */ Address.isWitness = function isWitness(type) { switch (type) { case scriptTypes.WITNESSPUBKEYHASH: return true; case scriptTypes.WITNESSSCRIPTHASH: return true; default: return false; } }; /* * Expose */ module.exports = Address;
decentraland/bronzeage-node
lib/primitives/address.js
JavaScript
mit
15,225
using Microsoft.EntityFrameworkCore; namespace Sample.RabbitMQ.MySql { public class Person { public int Id { get; set; } public string Name { get; set; } public override string ToString() { return $"Name:{Name}, Id:{Id}"; } } public class AppDbContext : DbContext { public const string ConnectionString = ""; public DbSet<Person> Persons { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseMySql(ConnectionString, new MariaDbServerVersion(ServerVersion.AutoDetect(ConnectionString))); } } }
dotnetcore/CAP
samples/Sample.RabbitMQ.MySql/AppDbContext.cs
C#
mit
689
// Copyright (c) MarinAtanasov. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the project root for license information. using AppBrix.Cloning.Impl; using AppBrix.Container; using AppBrix.Lifecycle; using AppBrix.Modules; using System; using System.Collections.Generic; namespace AppBrix.Cloning; /// <summary> /// A module used for registering a default object cloner. /// The object cloner is used for creating deep and shallow copies of objects. /// </summary> public sealed class CloningModule : ModuleBase { #region Properties /// <summary> /// Gets the types of the modules which are direct dependencies for the current module. /// This is used to determine the order in which the modules are loaded. /// </summary> public override IEnumerable<Type> Dependencies => new[] { typeof(ContainerModule) }; #endregion #region Public and overriden methods /// <summary> /// Initializes the module. /// Automatically called by <see cref="ModuleBase.Initialize"/> /// </summary> /// <param name="context">The initialization context.</param> protected override void Initialize(IInitializeContext context) { this.App.Container.Register(this); this.App.Container.Register(this.cloner); } /// <summary> /// Uninitializes the module. /// Automatically called by <see cref="ModuleBase.Uninitialize"/> /// </summary> protected override void Uninitialize() { } #endregion #region Private fields and constants private readonly Cloner cloner = new Cloner(); #endregion }
MarinAtanasov/AppBrix
Modules/AppBrix.Cloning/CloningModule.cs
C#
mit
1,625
// @flow declare module '@reach/portal' { declare export default React$ComponentType<{| children: React$Node, type?: string, |}>; }
flowtype/flow-typed
definitions/npm/@reach/portal_v0.2.x/flow_v0.84.x-/portal_v0.2.x.js
JavaScript
mit
145
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.Runtime.InteropServices; using System.Globalization; using System.Linq.Expressions; using Mono.Linq.Expressions; namespace V { public enum Keyword : int { _TypesStart, // Types begin Void, Int, UInt, String, Float, Double, _TypesEnd, // Types end _KeywordsStart, // Keywords begin Null, Return, _KeywordsEnd, // Keywords end } public enum Symbol : int { _Null, LParen, RParen, LCurvy, RCurvy, Comma, Semicolon, Assign, } public static class KeywordExtensions { public static bool IsBetween(this Keyword K, Keyword Start, Keyword End) { return (int)K > (int)Start && (int)K < (int)End; } public static bool IsType(this Keyword K) { return K.IsBetween(Keyword._TypesStart, Keyword._TypesEnd); } } public static class TokenExtensions { public static bool IsType(this Token T) { return T.Type == TokenType.Keyword && ((Keyword)T.Id).IsType(); } public static Type ToType(this Token T) { if (!T.IsType()) throw new Exception("Token is not a type token"); Keyword K = (Keyword)T.Id; switch (K) { case Keyword.Void: return typeof(void); case Keyword.Int: return typeof(int); case Keyword.UInt: return typeof(uint); case Keyword.String: return typeof(string); case Keyword.Double: return typeof(double); case Keyword.Float: return typeof(float); default: throw new Exception("Unknown type keyword " + K); } } public static bool IsIdentifier(this Token T) { return T.Type == TokenType.Identifier; } public static bool IsSymbol(this Token T, Symbol S) { return T.Type == TokenType.Symbol && ((Symbol)T.Id) == S; } public static bool IsKeyword(this Token T, Keyword K) { return T.Type == TokenType.Keyword && ((Keyword)T.Id) == K; } } public class Parser { LexerBehavior LB; LexerSettings LS; Token[] Tokens; int Idx; public Parser() { LB = LexerBehavior.SkipComments | LexerBehavior.SkipWhiteSpaces | LexerBehavior.Default; LS = LexerSettings.Default; LS.Options = LexerOptions.StringDoubleQuote | LexerOptions.StringEscaping; LS.Keywords = new Dictionary<string, int>(); string[] KeywordNames = Enum.GetNames(typeof(Keyword)); for (int i = 0; i < KeywordNames.Length; i++) { if (KeywordNames[i].StartsWith("_")) continue; LS.Keywords.Add(KeywordNames[i].ToLower(), (int)(Keyword)Enum.Parse(typeof(Keyword), KeywordNames[i])); } LS.Symbols = new Dictionary<string, int>(); LS.Symbols.Add("(", (int)Symbol.LParen); LS.Symbols.Add(")", (int)Symbol.RParen); LS.Symbols.Add("{", (int)Symbol.LCurvy); LS.Symbols.Add("}", (int)Symbol.RCurvy); LS.Symbols.Add(",", (int)Symbol.Comma); LS.Symbols.Add(";", (int)Symbol.Semicolon); LS.Symbols.Add("=", (int)Symbol.Assign); } Token Peek(int N = 0) { if (Idx + N >= Tokens.Length) return Token.Null; return Tokens[Idx + N]; } Symbol PeekSymbol(int N = 0) { Token T = Peek(N); if (T.Type != TokenType.Symbol) return Symbol._Null; return (Symbol)T.Id; } Token Next() { Token N = Peek(); Console.WriteLine(N); Idx++; return N; } public void Parse(string Src) { Parse(new StringReader(Src)); } public void Parse(TextReader TR) { Lexer L = new Lexer(TR, LB, LS); Tokens = L.ToArray(); Idx = 0; while (Peek() != Token.Null) Next(); /*List<Expression> Program = new List<Expression>(); while (Peek() != Token.Null) Program.Add(ParseAny()); Console.WriteLine(); foreach (var E in Program) Console.WriteLine(E.ToCSharpCode());*/ } } }
cartman300/Vermin
V/Parser.cs
C#
mit
3,763
shared_context 'optoro_zookeeper' do before do Chef::Recipe.any_instance.stub(:query_role).and_return('kitchen_role') Chef::Recipe.any_instance.stub(:query_role_credentials).and_return('{ "Code" : "Success", "LastUpdated" : "2015-03-09T14:48:17Z", "Type" : "AWS-HMAC", "AccessKeyId" : "ACCESSKEY", "SecretAccessKey" : "SECRETKEY", "Token" : "TOKEN", "Expiration" : "2015-03-09T21:14:00Z" }') allow(Chef::EncryptedDataBagItem).to receive(:load).with('aws', 'aws_keys').and_return('id' => 'aws_keys', 'exhibitor_access_key_id' => 'ACCESS', 'exhibitor_secret_access_key' => 'SECRET') end end
smedefind/optoro_zookeeper
spec/helpers.rb
Ruby
mit
606
<?php /* * This file is part of the PHPExifTool package. * * (c) Alchemy <support@alchemy.fr> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPExiftool\Driver\Tag\Pentax; use JMS\Serializer\Annotation\ExclusionPolicy; use PHPExiftool\Driver\AbstractTag; /** * @ExclusionPolicy("all") */ class FlashStatus extends AbstractTag { protected $Id = 0; protected $Name = 'FlashStatus'; protected $FullName = 'Pentax::FlashInfo'; protected $GroupName = 'Pentax'; protected $g0 = 'MakerNotes'; protected $g1 = 'Pentax'; protected $g2 = 'Camera'; protected $Type = 'int8u'; protected $Writable = true; protected $Description = 'Flash Status'; protected $flag_Permanent = true; protected $Values = array( 0 => array( 'Id' => 0, 'Label' => 'Off', ), 1 => array( 'Id' => 1, 'Label' => 'Off (1)', ), 2 => array( 'Id' => 2, 'Label' => 'External, Did not fire', ), 6 => array( 'Id' => 6, 'Label' => 'External, Fired', ), 8 => array( 'Id' => 8, 'Label' => 'Internal, Did not fire (0x08)', ), 9 => array( 'Id' => 9, 'Label' => 'Internal, Did not fire', ), 13 => array( 'Id' => 13, 'Label' => 'Internal, Fired', ), ); }
bburnichon/PHPExiftool
lib/PHPExiftool/Driver/Tag/Pentax/FlashStatus.php
PHP
mit
1,553
package com.merakianalytics.orianna.types.core.searchable; public abstract interface SearchableObject { public boolean contains(final Object item); }
robrua/Orianna
orianna/src/main/java/com/merakianalytics/orianna/types/core/searchable/SearchableObject.java
Java
mit
155
version https://git-lfs.github.com/spec/v1 oid sha256:90773470146a0daefafb65539bea2a9c6537067655a435ffce48433658e3d73a size 943
yogeshsaroya/new-cdnjs
ajax/libs/highlight.js/7.5/languages/actionscript.min.js
JavaScript
mit
128
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.containerregistry.v2019_04_01; import java.util.Collection; import com.fasterxml.jackson.annotation.JsonCreator; import com.microsoft.rest.ExpandableStringEnum; /** * Defines values for OS. */ public final class OS extends ExpandableStringEnum<OS> { /** Static value Windows for OS. */ public static final OS WINDOWS = fromString("Windows"); /** Static value Linux for OS. */ public static final OS LINUX = fromString("Linux"); /** * Creates or finds a OS from its string representation. * @param name a name to look for * @return the corresponding OS */ @JsonCreator public static OS fromString(String name) { return fromString(name, OS.class); } /** * @return known OS values */ public static Collection<OS> values() { return values(OS.class); } }
selvasingh/azure-sdk-for-java
sdk/containerregistry/mgmt-v2019_04_01/src/main/java/com/microsoft/azure/management/containerregistry/v2019_04_01/OS.java
Java
mit
1,118
using System; using System.Diagnostics; using Aspose.Email.Mail; namespace Aspose.Email.Examples.CSharp.Email.SMTP { class SendingEMLFilesWithSMTP { public static void Run() { // The path to the File directory. string dataDir = RunExamples.GetDataDir_SMTP(); string dstEmail = dataDir + "Message.eml"; // Create an instance of the MailMessage class MailMessage message = new MailMessage(); // Import from EML format message = MailMessage.Load(dstEmail, new EmlLoadOptions()); // Create an instance of SmtpClient class SmtpClient client = new SmtpClient("smtp.gmail.com", 587, "your.email@gmail.com", "your.password"); client.SecurityOptions = SecurityOptions.Auto; try { // Client.Send will send this message client.Send(message); Console.WriteLine("Message sent"); } catch (Exception ex) { Trace.WriteLine(ex.ToString()); } Console.WriteLine(Environment.NewLine + "Email sent using EML file successfully. " + dstEmail); } } }
jawadaspose/Aspose.Email-for-.NET
Examples/CSharp/SMTP/SendingEMLFilesWithSMTP.cs
C#
mit
1,239
<?php /* * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * This software consists of voluntary contributions made by many individuals * and is licensed under the MIT license. */ declare(strict_types=1); namespace ProxyManager\ProxyGenerator\NullObject\MethodGenerator; use ProxyManager\Generator\MethodGenerator; use ProxyManager\ProxyGenerator\Util\Properties; use ReflectionClass; use ReflectionProperty; /** * The `staticProxyConstructor` implementation for null object proxies * * @author Marco Pivetta <ocramius@gmail.com> * @license MIT */ class StaticProxyConstructor extends MethodGenerator { /** * Constructor * * @param ReflectionClass $originalClass Reflection of the class to proxy * * @throws \Zend\Code\Generator\Exception\InvalidArgumentException */ public function __construct(ReflectionClass $originalClass) { parent::__construct('staticProxyConstructor', [], static::FLAG_PUBLIC | static::FLAG_STATIC); $nullableProperties = array_map( function (ReflectionProperty $publicProperty) : string { return '$instance->' . $publicProperty->getName() . ' = null;'; }, Properties::fromReflectionClass($originalClass)->getPublicProperties() ); $this->setDocBlock('Constructor for null object initialization'); $this->setBody( 'static $reflection;' . "\n\n" . '$reflection = $reflection ?: $reflection = new \ReflectionClass(__CLASS__);' . "\n" . '$instance = (new \ReflectionClass(get_class()))->newInstanceWithoutConstructor();' . "\n\n" . ($nullableProperties ? implode("\n", $nullableProperties) . "\n\n" : '') . 'return $instance;' ); } }
rainlike/justshop
vendor/ocramius/proxy-manager/src/ProxyManager/ProxyGenerator/NullObject/MethodGenerator/StaticProxyConstructor.php
PHP
mit
2,514
/** * Copyright (C) 2016 by Johan von Forstner under the MIT license: * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and * associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package de.geeksfactory.opacclient.objects; import org.joda.time.LocalDate; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.ISODateTimeFormat; /** * Represents a copy of a medium ({@link DetailedItem}) available in a library. */ public class Copy { private String barcode; private String location; private String department; private String branch; private String issue; private String status; private LocalDate returnDate; private String reservations; private String shelfmark; private String resInfo; private String url; /** * @return The barcode of a copy. Optional. */ public String getBarcode() { return barcode; } /** * @param barcode The barcode of a copy. Optional. */ public void setBarcode(String barcode) { this.barcode = barcode; } /** * @return The location (like "third floor") of a copy. Optional. */ public String getLocation() { return location; } /** * @param location The location (like "third floor") of a copy. Optional. */ public void setLocation(String location) { this.location = location; } /** * @return The department (like "music library") of a copy. Optional. */ public String getDepartment() { return department; } /** * @param department The department (like "music library") of a copy. Optional. */ public void setDepartment(String department) { this.department = department; } /** * @return The branch a copy is in. Should be set, if your library has more than one branch. */ public String getBranch() { return branch; } /** * @param branch The branch a copy is in. Should be set, if your library has more than one * branch. */ public void setBranch(String branch) { this.branch = branch; } /** * @return The issue, e.g. when the item represents a year of magazines, this is the magazine number. */ public String getIssue() { return issue; } /** * @param issue The issue, e.g. when the item represents a year of magazines, this is the magazine number. */ public void setIssue(String issue) { this.issue = issue; } /** * @return Current status of a copy ("lent", "free", ...). Should be set. */ public String getStatus() { return status; } /** * @param status Current status of a copy ("lent", "free", ...). Should be set. */ public void setStatus(String status) { this.status = status; } /** * @return Expected date of return if a copy is lent out. Optional. */ public LocalDate getReturnDate() { return returnDate; } /** * @param returndate Expected date of return if a copy is lent out. Optional. */ public void setReturnDate(LocalDate returndate) { this.returnDate = returndate; } /** * @return Number of pending reservations if a copy is currently lent out. Optional. */ public String getReservations() { return reservations; } /** * @param reservations Number of pending reservations if a copy is currently lent out. * Optional. */ public void setReservations(String reservations) { this.reservations = reservations; } /** * @return Identification in the libraries' shelf system. Optional. */ public String getShelfmark() { return shelfmark; } /** * @param shelfmark Identification in the libraries' shelf system. Optional. */ public void setShelfmark(String shelfmark) { this.shelfmark = shelfmark; } /** * @return Reservation information for copy-based reservations. Intended for use in your {@link * de.geeksfactory.opacclient.apis.OpacApi#reservation(DetailedItem, Account, int, String)} * implementation. */ public String getResInfo() { return resInfo; } /** * @param resInfo Reservation information for copy-based reservations. Intended for use in your * {@link de.geeksfactory.opacclient.apis.OpacApi#reservation (DetailedItem, * Account, int, String)} implementation. */ public void setResInfo(String resInfo) { this.resInfo = resInfo; } /** * @return URL to an online copy */ public String getUrl() { return url; } /** * @param url URL to an online copy */ public void setUrl(String url) { this.url = url; } /** * Set property using the following keys: barcode, location, department, branch, status, * returndate, reservations, signature, resinfo, url * * If you supply an invalid key, an {@link IllegalArgumentException} will be thrown. * * This method is used to simplify refactoring of old APIs from the Map&lt;String, String&gt; data * structure to this class. If you are creating a new API, you probably don't need to use it. * * @param key one of the keys mentioned above * @param value the value to set. Dates must be in ISO-8601 format (yyyy-MM-dd). */ public void set(String key, String value) { switch (key) { case "barcode": setBarcode(value); break; case "location": setLocation(value); break; case "department": setDepartment(value); break; case "branch": setBranch(value); break; case "status": setStatus(value); break; case "returndate": setReturnDate(new LocalDate(value)); break; case "reservations": setReservations(value); break; case "signature": setShelfmark(value); break; case "resinfo": setResInfo(value); break; case "url": setUrl(value); break; default: throw new IllegalArgumentException("key unknown"); } } /** * Set property using the following keys: barcode, location, department, branch, status, * returndate, reservations, signature, resinfo, url * * For "returndate", the given {@link DateTimeFormatter} will be used to parse the date. * * If you supply an invalid key, an {@link IllegalArgumentException} will be thrown. * * This method is used to simplify refactoring of old APIs from the Map&lt;String, String&gt; data * structure to this class. If you are creating a new API, you probably don't need to use it. * * @param key one of the keys mentioned above * @param value the value to set. Dates must be in a format parseable by the given {@link * DateTimeFormatter}, otherwise an {@link IllegalArgumentException} will be * thrown. * @param fmt the {@link DateTimeFormatter} to use for parsing dates */ public void set(String key, String value, DateTimeFormatter fmt) { if (key.equals("returndate")) { if (!value.isEmpty()) { setReturnDate(fmt.parseLocalDate(value)); } } else { set(key, value); } } /** * Get property using the following keys: barcode, location, department, branch, status, * returndate, reservations, signature, resinfo, url * * Dates will be returned in ISO-8601 format (yyyy-MM-dd). If you supply an invalid key, an * {@link IllegalArgumentException} will be thrown. * * This method is used to simplify refactoring of old APIs from the Map&lt;String, String&gt; data * structure to this class. If you are creating a new API, you probably don't need to use it. * * @param key one of the keys mentioned above */ public String get(String key) { switch (key) { case "barcode": return getBarcode(); case "location": return getLocation(); case "department": return getDepartment(); case "branch": return getBranch(); case "status": return getStatus(); case "returndate": return getReturnDate() != null ? ISODateTimeFormat.date().print(getReturnDate()) : null; case "reservations": return getReservations(); case "signature": return getShelfmark(); case "resinfo": return getResInfo(); case "url": return getUrl(); default: throw new IllegalArgumentException("key unknown"); } } /** * @return boolean value indicating if this copy contains any data or not. */ public boolean notEmpty() { return getBarcode() != null || getLocation() != null || getDepartment() != null || getBranch() != null || getStatus() != null || getReturnDate() != null || getReservations() != null || getShelfmark() != null || getResInfo() != null || getIssue() != null || getUrl() != null; } @Override public String toString() { return "Copy{" + "barcode='" + barcode + '\'' + ", location='" + location + '\'' + ", department='" + department + '\'' + ", branch='" + branch + '\'' + ", status='" + status + '\'' + ", returnDate=" + returnDate + ", reservations='" + reservations + '\'' + ", shelfmark='" + shelfmark + '\'' + ", issue='" + issue + '\'' + ", resInfo='" + resInfo + '\'' + ", url='" + url + '\'' + '}'; } }
johan12345/opacclient
opacclient/libopac/src/main/java/de/geeksfactory/opacclient/objects/Copy.java
Java
mit
11,432
package id.birokrazy.model; import com.fasterxml.jackson.annotation.JsonIgnore; import org.hibernate.annotations.Type; import org.hibernate.search.annotations.Field; import org.hibernate.search.annotations.Indexed; import javax.persistence.*; import java.util.List; /** * @author Arthur Purnama (arthur@purnama.de) */ @Entity @Indexed public class Department { @Id @GeneratedValue private Long id; @Version @Column(columnDefinition = "bigint default 0") private Long version; @Column(nullable = false, unique = true) private String uniqueName; @Column(nullable = false) @Field private String name; @Column private String description; @Column() @Type(type = "text") private String content; @Column(nullable = false) private Double rating; @Column(nullable = false) private Long reviews; @Column(nullable = false) private String address; @Column private String addressAdd; @Column private String district; @Column(nullable = false) private String zipCode; @Column(nullable = false) private String city; @Column(nullable = false) private String state; @Column private String telephone; @Column private String email; @Column private String openingHour; @Column private String longitude; @Column private String latitude; @OneToMany(mappedBy = "department") @OrderBy("id desc") @JsonIgnore private List<Review> reviewList; @ManyToMany(mappedBy = "departmentList") @OrderBy("id desc") @JsonIgnore private List<CivilService> civilServiceList; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getVersion() { return version; } public void setVersion(Long version) { this.version = version; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Double getRating() { return rating; } public void setRating(Double rating) { this.rating = rating; } public Long getReviews() { return reviews; } public void setReviews(Long reviews) { this.reviews = reviews; } public List<Review> getReviewList() { return reviewList; } public void setReviewList(List<Review> reviewList) { this.reviewList = reviewList; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getAddressAdd() { return addressAdd; } public void setAddressAdd(String addressAdd) { this.addressAdd = addressAdd; } public String getZipCode() { return zipCode; } public void setZipCode(String zipCode) { this.zipCode = zipCode; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getLongitude() { return longitude; } public void setLongitude(String longitude) { this.longitude = longitude; } public String getLatitude() { return latitude; } public void setLatitude(String latitude) { this.latitude = latitude; } public List<CivilService> getCivilServiceList() { return civilServiceList; } public void setCivilServiceList(List<CivilService> civilServiceList) { this.civilServiceList = civilServiceList; } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getOpeningHour() { return openingHour; } public void setOpeningHour(String openingHour) { this.openingHour = openingHour; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getUniqueName() { return uniqueName; } public void setUniqueName(String uniqueName) { this.uniqueName = uniqueName; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getDistrict() { return district; } public void setDistrict(String district) { this.district = district; } @Field public String getLocation() { return address + " " + addressAdd + " " + district + " " + city + " " + state + " " + zipCode; } @Field public String getLocationName() { return district + ", " + city + " (" + zipCode + "), " + state; } }
purnama/birokrazy
src/main/java/id/birokrazy/model/Department.java
Java
mit
5,175
/* The MIT License (MIT) Copyright (c) IIIT-DELHI authors: HEMANT JAIN "hjcooljohny75@gmail.com" ANIRUDH NAIN Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ //To define all the properties needed to make the rdf of the email package check.email; import com.hp.hpl.jena.rdf.model.*; public class EMAILRDF { //Create a default model private static Model m = ModelFactory.createDefaultModel(); //Subject of the mail public static final Property MSGID = m.createProperty("MESSAGEID:" ); public static final Property MAILID = m.createProperty("MAILID:" ); public static final Property SUBJECT = m.createProperty("SUB:" ); //Sender of the mail public static final Property FROM = m.createProperty("FROM:" ); public static final Property FROMFULL = m.createProperty("FROMFULL:" ); public static final Property TOFULL = m.createProperty("TOFULL:" ); public static final Property EMAILID = m.createProperty("EMAILID:" ); //Receiver of the mail public static final Property TO = m.createProperty("TO:" ); //Return path public static final Property RETURN_PATH = m.createProperty("RETURNPATH:" ); //main contents of the mail public static final Property CONTENT = m.createProperty("CONTENT:" ); //format of the mail public static final Property FORMAT = m.createProperty("FORMAT:" ); //content type like html etc public static final Property CONTENT_TYPE = m.createProperty("CONTENTTYPE:" ); //encoding in bits public static final Property ENCODING = m.createProperty("ENCODING:" ); //date of the email public static final Property DATE = m.createProperty("DATE:" ); //CC of email public static final Property CC = m.createProperty("CC:" ); //BCC of email public static final Property BCC = m.createProperty("BCC:" ); //NAME OF THE SENDER public static final Property ATTACHEMENT_NAME = m.createProperty("ATTACHEMENTNAME:" ); public static final Property ATTACHEMENT_NO = m.createProperty("ATTACHEMENTNO:" ); //SIZE OF MAIL public static final Property MAIL_SIZE = m.createProperty("MAILSIZE:" ); //SIZE OF THE ATTACHEMENT of email public static final Property ATTACHEMENT_SIZE = m.createProperty("ATTACHEMENTSIZE:" ); //MAIL TO WHICH PARTICULAR MAIL HAVE REPLIED public static final Property IN_REPLYTO = m.createProperty("REPLIEDTO:" ); public static final Property IN_REPLYTONAME = m.createProperty("REPLIEDTONAME:" ); //FOLDER IN WHICH email EXISTS public static final Property FOLDER_NAME = m.createProperty("FOLDERNAME:" ); //UID of email public static final Property UID = m.createProperty("UID:" ); //name os receiver of email public static final Property REC_NAME = m.createProperty("RECIEVERS_NAME:" ); //name of sender of email public static final Property SEND_NAME = m.createProperty("SENDERNAME:" ); }
COOLHEMANTJAIN/MAILDETECTIVE
maildetective1.0/src/check/email/EMAILRDF.java
Java
mit
3,829
import argparse import os import sys import numpy as np from PIL import Image import chainer from chainer import cuda import chainer.functions as F from chainer.functions import caffe from chainer import Variable, optimizers import pickle def subtract_mean(x0): x = x0.copy() x[0,0,:,:] -= 104 x[0,1,:,:] -= 117 x[0,2,:,:] -= 123 return x def add_mean(x0): x = x0.copy() x[0,0,:,:] += 104 x[0,1,:,:] += 117 x[0,2,:,:] += 123 return x def image_resize(img_file, width): gogh = Image.open(img_file) orig_w, orig_h = gogh.size[0], gogh.size[1] if orig_w>orig_h: new_w = width new_h = width*orig_h/orig_w gogh = np.asarray(gogh.resize((new_w,new_h)))[:,:,:3].transpose(2, 0, 1)[::-1].astype(np.float32) gogh = gogh.reshape((1,3,new_h,new_w)) print("image resized to: ", gogh.shape) hoge= np.zeros((1,3,width,width), dtype=np.float32) hoge[0,:,width-new_h:,:] = gogh[0,:,:,:] gogh = subtract_mean(hoge) else: new_w = width*orig_w/orig_h new_h = width gogh = np.asarray(gogh.resize((new_w,new_h)))[:,:,:3].transpose(2, 0, 1)[::-1].astype(np.float32) gogh = gogh.reshape((1,3,new_h,new_w)) print("image resized to: ", gogh.shape) hoge= np.zeros((1,3,width,width), dtype=np.float32) hoge[0,:,:,width-new_w:] = gogh[0,:,:,:] gogh = subtract_mean(hoge) return xp.asarray(gogh), new_w, new_h def save_image(img, width, new_w, new_h, it): def to_img(x): im = np.zeros((new_h,new_w,3)) im[:,:,0] = x[2,:,:] im[:,:,1] = x[1,:,:] im[:,:,2] = x[0,:,:] def clip(a): return 0 if a<0 else (255 if a>255 else a) im = np.vectorize(clip)(im).astype(np.uint8) Image.fromarray(im).save(args.out_dir+"/im_%05d.png"%it) if args.gpu>=0: img_cpu = add_mean(img.get()) else: img_cpu = add_mean(img) if width==new_w: to_img(img_cpu[0,:,width-new_h:,:]) else: to_img(img_cpu[0,:,:,width-new_w:]) def nin_forward(x): y0 = F.relu(model.conv1(x)) y1 = model.cccp2(F.relu(model.cccp1(y0))) x1 = F.relu(model.conv2(F.average_pooling_2d(F.relu(y1), 3, stride=2))) y2 = model.cccp4(F.relu(model.cccp3(x1))) x2 = F.relu(model.conv3(F.average_pooling_2d(F.relu(y2), 3, stride=2))) y3 = model.cccp6(F.relu(model.cccp5(x2))) x3 = F.relu(getattr(model,"conv4-1024")(F.dropout(F.average_pooling_2d(F.relu(y3), 3, stride=2), train=False))) return [y0,x1,x2,x3] def vgg_forward(x): y1 = model.conv1_2(F.relu(model.conv1_1(x))) x1 = F.average_pooling_2d(F.relu(y1), 2, stride=2) y2 = model.conv2_2(F.relu(model.conv2_1(x1))) x2 = F.average_pooling_2d(F.relu(y2), 2, stride=2) y3 = model.conv3_3(F.relu(model.conv3_2(F.relu(model.conv3_1(x2))))) x3 = F.average_pooling_2d(F.relu(y3), 2, stride=2) y4 = model.conv4_3(F.relu(model.conv4_2(F.relu(model.conv4_1(x3))))) # x4 = F.average_pooling_2d(F.relu(y4), 2, stride=2) # y5 = model.conv5_3(F.relu(model.conv5_2(F.relu(model.conv5_1(x4))))) return [y1,y2,y3,y4] def get_matrix(y): ch = y.data.shape[1] wd = y.data.shape[2] gogh_y = F.reshape(y, (ch,wd**2)) gogh_matrix = F.matmul(gogh_y, gogh_y, transb=True)/np.float32(ch*wd**2) return gogh_matrix class Clip(chainer.Function): def forward(self, x): x = x[0] ret = cuda.elementwise( 'T x','T ret', ''' ret = x<-100?-100:(x>100?100:x); ''','clip')(x) return ret def generate_image(img_orig, img_style, width, nw, nh, max_iter, lr, alpha, beta, img_gen=None): mid_orig = nin_forward(Variable(img_orig)) style_mats = [get_matrix(y) for y in nin_forward(Variable(img_style))] if img_gen is None: if args.gpu >= 0: img_gen = xp.random.uniform(-20,20,(1,3,width,width),dtype=np.float32) else: img_gen = np.random.uniform(-20,20,(1,3,width,width)).astype(np.float32) x = Variable(img_gen) xg = xp.zeros_like(x.data) optimizer = optimizers.Adam(alpha=lr) optimizer.setup((img_gen,xg)) for i in range(max_iter): x = Variable(img_gen) y = nin_forward(x) optimizer.zero_grads() L = Variable(xp.zeros((), dtype=np.float32)) for l in range(4): ch = y[l].data.shape[1] wd = y[l].data.shape[2] gogh_y = F.reshape(y[l], (ch,wd**2)) gogh_matrix = F.matmul(gogh_y, gogh_y, transb=True)/np.float32(ch*wd**2) L1 = np.float32(alpha[l])*F.mean_squared_error(y[l], Variable(mid_orig[l].data)) L2 = np.float32(beta[l])*F.mean_squared_error(gogh_matrix, Variable(style_mats[l].data))/np.float32(4) L += L1+L2 if i%100==0: print i,l,L1.data,L2.data L.backward() xg += x.grad optimizer.update() tmp_shape = img_gen.shape if args.gpu >= 0: img_gen += Clip().forward(img_gen).reshape(tmp_shape) - img_gen else: def clip(x): return -100 if x<-100 else (100 if x>100 else x) img_gen += np.vectorize(clip)(img_gen).reshape(tmp_shape) - img_gen if i%50==0: save_image(img_gen, W, nw, nh, i) parser = argparse.ArgumentParser( description='A Neural Algorithm of Artistic Style') parser.add_argument('--model', '-m', default='nin_imagenet.caffemodel', help='model file') parser.add_argument('--orig_img', '-i', default='orig.png', help='Original image') parser.add_argument('--style_img', '-s', default='style.png', help='Style image') parser.add_argument('--out_dir', '-o', default='output', help='Output directory') parser.add_argument('--gpu', '-g', default=-1, type=int, help='GPU ID (negative value indicates CPU)') parser.add_argument('--iter', default=5000, type=int, help='number of iteration') parser.add_argument('--lr', default=4.0, type=float, help='learning rate') parser.add_argument('--lam', default=0.005, type=float, help='original image weight / style weight ratio') parser.add_argument('--width', '-w', default=435, type=int, help='image width, height') args = parser.parse_args() try: os.mkdir(args.out_dir) except: pass if args.gpu >= 0: cuda.check_cuda_available() cuda.get_device(args.gpu).use() xp = cuda.cupy else: xp = np chainer.Function.type_check_enable = False print "load model... %s"%args.model func = caffe.CaffeFunction(args.model) model = func.fs if args.gpu>=0: model.to_gpu() W = args.width img_gogh,_,_ = image_resize(args.style_img, W) img_hongo,nw,nh = image_resize(args.orig_img, W) generate_image(img_hongo, img_gogh, W, nw, nh, img_gen=None, max_iter=args.iter, lr=args.lr, alpha=[args.lam * x for x in [0,0,1,1]], beta=[1,1,1,1])
wf9a5m75/chainer-gogh
chainer-gogh.py
Python
mit
7,054
App.SubmissionsResponseController = Ember.ObjectController.extend({ actions: { saveNotes: function() { var onSuccess = function(post) { $(".alert-box").remove(); $("textarea").before("<div data-alert class='alert-box'>Your notes were saved!<a class='close'>&times;</a></div>"); }; var onFail = function(post) { $(".alert-box").remove(); $("textarea").before("<div data-alert class='alert-box alert'>Uh oh! Something went wrong...<a class='close'>&times;</a></div>"); }; var model = this.get('model'); model.save().then(onSuccess, onFail); return model; } } });
andrewjadams3/Klassewerk
app/assets/javascripts/controllers/submissions_response_controller.js
JavaScript
mit
648