code
stringlengths
2
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
991
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
// MIT License // // Copyright( c ) 2017 Packt // // 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. // // Vulkan Cookbook // ISBN: 9781786468154 // © Packt Publishing Limited // // Author: Pawel Lapinski // LinkedIn: https://www.linkedin.com/in/pawel-lapinski-84522329 // // Chapter: 11 Lighting // Recipe: 01 Rendering a geometry with vertex diffuse lighting #include "CookbookSampleFramework.h" using namespace VulkanCookbook; class Sample : public VulkanCookbookSample { Mesh Model; VkDestroyer(VkBuffer) VertexBuffer; VkDestroyer(VkDeviceMemory) VertexBufferMemory; VkDestroyer(VkDescriptorSetLayout) DescriptorSetLayout; VkDestroyer(VkDescriptorPool) DescriptorPool; std::vector<VkDescriptorSet> DescriptorSets; VkDestroyer(VkRenderPass) RenderPass; VkDestroyer(VkPipelineLayout) PipelineLayout; VkDestroyer(VkPipeline) Pipeline; VkDestroyer(VkBuffer) StagingBuffer; VkDestroyer(VkDeviceMemory) StagingBufferMemory; bool UpdateUniformBuffer; VkDestroyer(VkBuffer) UniformBuffer; VkDestroyer(VkDeviceMemory) UniformBufferMemory; virtual bool Initialize( WindowParameters window_parameters ) override { if( !InitializeVulkan( window_parameters ) ) { return false; } // Vertex data if( !Load3DModelFromObjFile( "Data/Models/knot.obj", true, false, false, true, Model ) ) { return false; } InitVkDestroyer( LogicalDevice, VertexBuffer ); if( !CreateBuffer( *LogicalDevice, sizeof( Model.Data[0] ) * Model.Data.size(), VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, *VertexBuffer ) ) { return false; } InitVkDestroyer( LogicalDevice, VertexBufferMemory ); if( !AllocateAndBindMemoryObjectToBuffer( PhysicalDevice, *LogicalDevice, *VertexBuffer, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, *VertexBufferMemory ) ) { return false; } if( !UseStagingBufferToUpdateBufferWithDeviceLocalMemoryBound( PhysicalDevice, *LogicalDevice, sizeof( Model.Data[0] ) * Model.Data.size(), &Model.Data[0], *VertexBuffer, 0, 0, VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_VERTEX_INPUT_BIT, GraphicsQueue.Handle, FramesResources.front().CommandBuffer, {} ) ) { return false; } // Staging buffer InitVkDestroyer( LogicalDevice, StagingBuffer ); if( !CreateBuffer( *LogicalDevice, 2 * 16 * sizeof(float), VK_BUFFER_USAGE_TRANSFER_SRC_BIT, *StagingBuffer ) ) { return false; } InitVkDestroyer( LogicalDevice, StagingBufferMemory ); if( !AllocateAndBindMemoryObjectToBuffer( PhysicalDevice, *LogicalDevice, *StagingBuffer, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, *StagingBufferMemory ) ) { return false; } // Uniform buffer InitVkDestroyer( LogicalDevice, UniformBuffer ); InitVkDestroyer( LogicalDevice, UniformBufferMemory ); if( !CreateUniformBuffer( PhysicalDevice, *LogicalDevice, 2 * 16 * sizeof( float ), VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, *UniformBuffer, *UniformBufferMemory ) ) { return false; } if( !UpdateStagingBuffer( true ) ) { return false; } // Descriptor set with uniform buffer VkDescriptorSetLayoutBinding descriptor_set_layout_binding = { 0, // uint32_t binding VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, // VkDescriptorType descriptorType 1, // uint32_t descriptorCount VK_SHADER_STAGE_VERTEX_BIT, // VkShaderStageFlags stageFlags nullptr // const VkSampler * pImmutableSamplers }; InitVkDestroyer( LogicalDevice, DescriptorSetLayout ); if( !CreateDescriptorSetLayout( *LogicalDevice, { descriptor_set_layout_binding }, *DescriptorSetLayout ) ) { return false; } VkDescriptorPoolSize descriptor_pool_size = { VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, // VkDescriptorType type 1 // uint32_t descriptorCount }; InitVkDestroyer( LogicalDevice, DescriptorPool ); if( !CreateDescriptorPool( *LogicalDevice, false, 1, { descriptor_pool_size }, *DescriptorPool ) ) { return false; } if( !AllocateDescriptorSets( *LogicalDevice, *DescriptorPool, { *DescriptorSetLayout }, DescriptorSets ) ) { return false; } BufferDescriptorInfo buffer_descriptor_update = { DescriptorSets[0], // VkDescriptorSet TargetDescriptorSet 0, // uint32_t TargetDescriptorBinding 0, // uint32_t TargetArrayElement VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, // VkDescriptorType TargetDescriptorType { // std::vector<VkDescriptorBufferInfo> BufferInfos { *UniformBuffer, // VkBuffer buffer 0, // VkDeviceSize offset VK_WHOLE_SIZE // VkDeviceSize range } } }; UpdateDescriptorSets( *LogicalDevice, {}, { buffer_descriptor_update }, {}, {} ); // Render pass std::vector<VkAttachmentDescription> attachment_descriptions = { { 0, // VkAttachmentDescriptionFlags flags Swapchain.Format, // VkFormat format VK_SAMPLE_COUNT_1_BIT, // VkSampleCountFlagBits samples VK_ATTACHMENT_LOAD_OP_CLEAR, // VkAttachmentLoadOp loadOp VK_ATTACHMENT_STORE_OP_STORE, // VkAttachmentStoreOp storeOp VK_ATTACHMENT_LOAD_OP_DONT_CARE, // VkAttachmentLoadOp stencilLoadOp VK_ATTACHMENT_STORE_OP_DONT_CARE, // VkAttachmentStoreOp stencilStoreOp VK_IMAGE_LAYOUT_UNDEFINED, // VkImageLayout initialLayout VK_IMAGE_LAYOUT_PRESENT_SRC_KHR // VkImageLayout finalLayout }, { 0, // VkAttachmentDescriptionFlags flags DepthFormat, // VkFormat format VK_SAMPLE_COUNT_1_BIT, // VkSampleCountFlagBits samples VK_ATTACHMENT_LOAD_OP_CLEAR, // VkAttachmentLoadOp loadOp VK_ATTACHMENT_STORE_OP_DONT_CARE, // VkAttachmentStoreOp storeOp VK_ATTACHMENT_LOAD_OP_DONT_CARE, // VkAttachmentLoadOp stencilLoadOp VK_ATTACHMENT_STORE_OP_DONT_CARE, // VkAttachmentStoreOp stencilStoreOp VK_IMAGE_LAYOUT_UNDEFINED, // VkImageLayout initialLayout VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL // VkImageLayout finalLayout } }; VkAttachmentReference depth_attachment = { 1, // uint32_t attachment VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL // VkImageLayout layout }; std::vector<SubpassParameters> subpass_parameters = { { VK_PIPELINE_BIND_POINT_GRAPHICS, // VkPipelineBindPoint PipelineType {}, // std::vector<VkAttachmentReference> InputAttachments { // std::vector<VkAttachmentReference> ColorAttachments { 0, // uint32_t attachment VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, // VkImageLayout layout } }, {}, // std::vector<VkAttachmentReference> ResolveAttachments &depth_attachment, // VkAttachmentReference const * DepthStencilAttachment {} // std::vector<uint32_t> PreserveAttachments } }; std::vector<VkSubpassDependency> subpass_dependencies = { { VK_SUBPASS_EXTERNAL, // uint32_t srcSubpass 0, // uint32_t dstSubpass VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, // VkPipelineStageFlags srcStageMask VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, // VkPipelineStageFlags dstStageMask VK_ACCESS_MEMORY_READ_BIT, // VkAccessFlags srcAccessMask VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, // VkAccessFlags dstAccessMask VK_DEPENDENCY_BY_REGION_BIT // VkDependencyFlags dependencyFlags }, { 0, // uint32_t srcSubpass VK_SUBPASS_EXTERNAL, // uint32_t dstSubpass VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, // VkPipelineStageFlags srcStageMask VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, // VkPipelineStageFlags dstStageMask VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, // VkAccessFlags srcAccessMask VK_ACCESS_MEMORY_READ_BIT, // VkAccessFlags dstAccessMask VK_DEPENDENCY_BY_REGION_BIT // VkDependencyFlags dependencyFlags } }; InitVkDestroyer( LogicalDevice, RenderPass ); if( !CreateRenderPass( *LogicalDevice, attachment_descriptions, subpass_parameters, subpass_dependencies, *RenderPass ) ) { return false; } // Graphics pipeline InitVkDestroyer( LogicalDevice, PipelineLayout ); if( !CreatePipelineLayout( *LogicalDevice, { *DescriptorSetLayout }, {}, *PipelineLayout ) ) { return false; } std::vector<unsigned char> vertex_shader_spirv; if( !GetBinaryFileContents( "Data/Shaders/11 Lighting/01 Rendering a geometry with vertex diffuse lighting/shader.vert.spv", vertex_shader_spirv ) ) { return false; } VkDestroyer(VkShaderModule) vertex_shader_module; InitVkDestroyer( LogicalDevice, vertex_shader_module ); if( !CreateShaderModule( *LogicalDevice, vertex_shader_spirv, *vertex_shader_module ) ) { return false; } std::vector<unsigned char> fragment_shader_spirv; if( !GetBinaryFileContents( "Data/Shaders/11 Lighting/01 Rendering a geometry with vertex diffuse lighting/shader.frag.spv", fragment_shader_spirv ) ) { return false; } VkDestroyer(VkShaderModule) fragment_shader_module; InitVkDestroyer( LogicalDevice, fragment_shader_module ); if( !CreateShaderModule( *LogicalDevice, fragment_shader_spirv, *fragment_shader_module ) ) { return false; } std::vector<ShaderStageParameters> shader_stage_params = { { VK_SHADER_STAGE_VERTEX_BIT, // VkShaderStageFlagBits ShaderStage *vertex_shader_module, // VkShaderModule ShaderModule "main", // char const * EntryPointName nullptr // VkSpecializationInfo const * SpecializationInfo }, { VK_SHADER_STAGE_FRAGMENT_BIT, // VkShaderStageFlagBits ShaderStage *fragment_shader_module, // VkShaderModule ShaderModule "main", // char const * EntryPointName nullptr // VkSpecializationInfo const * SpecializationInfo } }; std::vector<VkPipelineShaderStageCreateInfo> shader_stage_create_infos; SpecifyPipelineShaderStages( shader_stage_params, shader_stage_create_infos ); std::vector<VkVertexInputBindingDescription> vertex_input_binding_descriptions = { { 0, // uint32_t binding 6 * sizeof( float ), // uint32_t stride VK_VERTEX_INPUT_RATE_VERTEX // VkVertexInputRate inputRate } }; std::vector<VkVertexInputAttributeDescription> vertex_attribute_descriptions = { { 0, // uint32_t location 0, // uint32_t binding VK_FORMAT_R32G32B32_SFLOAT, // VkFormat format 0 // uint32_t offset }, { 1, // uint32_t location 0, // uint32_t binding VK_FORMAT_R32G32B32_SFLOAT, // VkFormat format 3 * sizeof( float ) // uint32_t offset } }; VkPipelineVertexInputStateCreateInfo vertex_input_state_create_info; SpecifyPipelineVertexInputState( vertex_input_binding_descriptions, vertex_attribute_descriptions, vertex_input_state_create_info ); VkPipelineInputAssemblyStateCreateInfo input_assembly_state_create_info; SpecifyPipelineInputAssemblyState( VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, false, input_assembly_state_create_info ); ViewportInfo viewport_infos = { { // std::vector<VkViewport> Viewports { 0.0f, // float x 0.0f, // float y 500.0f, // float width 500.0f, // float height 0.0f, // float minDepth 1.0f // float maxDepth } }, { // std::vector<VkRect2D> Scissors { { // VkOffset2D offset 0, // int32_t x 0 // int32_t y }, { // VkExtent2D extent 500, // uint32_t width 500 // uint32_t height } } } }; VkPipelineViewportStateCreateInfo viewport_state_create_info; SpecifyPipelineViewportAndScissorTestState( viewport_infos, viewport_state_create_info ); VkPipelineRasterizationStateCreateInfo rasterization_state_create_info; SpecifyPipelineRasterizationState( false, false, VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_COUNTER_CLOCKWISE, false, 0.0f, 0.0f, 0.0f, 1.0f, rasterization_state_create_info ); VkPipelineMultisampleStateCreateInfo multisample_state_create_info; SpecifyPipelineMultisampleState( VK_SAMPLE_COUNT_1_BIT, false, 0.0f, nullptr, false, false, multisample_state_create_info ); VkPipelineDepthStencilStateCreateInfo depth_stencil_state_create_info; SpecifyPipelineDepthAndStencilState( true, true, VK_COMPARE_OP_LESS_OR_EQUAL, false, 0.0f, 1.0f, false, {}, {}, depth_stencil_state_create_info ); std::vector<VkPipelineColorBlendAttachmentState> attachment_blend_states = { { false, // VkBool32 blendEnable VK_BLEND_FACTOR_ONE, // VkBlendFactor srcColorBlendFactor VK_BLEND_FACTOR_ONE, // VkBlendFactor dstColorBlendFactor VK_BLEND_OP_ADD, // VkBlendOp colorBlendOp VK_BLEND_FACTOR_ONE, // VkBlendFactor srcAlphaBlendFactor VK_BLEND_FACTOR_ONE, // VkBlendFactor dstAlphaBlendFactor VK_BLEND_OP_ADD, // VkBlendOp alphaBlendOp VK_COLOR_COMPONENT_R_BIT | // VkColorComponentFlags colorWriteMask VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT } }; VkPipelineColorBlendStateCreateInfo blend_state_create_info; SpecifyPipelineBlendState( false, VK_LOGIC_OP_COPY, attachment_blend_states, { 1.0f, 1.0f, 1.0f, 1.0f }, blend_state_create_info ); std::vector<VkDynamicState> dynamic_states = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR }; VkPipelineDynamicStateCreateInfo dynamic_state_create_info; SpecifyPipelineDynamicStates( dynamic_states, dynamic_state_create_info ); VkGraphicsPipelineCreateInfo pipeline_create_info; SpecifyGraphicsPipelineCreationParameters( 0, shader_stage_create_infos, vertex_input_state_create_info, input_assembly_state_create_info, nullptr, &viewport_state_create_info, rasterization_state_create_info, &multisample_state_create_info, &depth_stencil_state_create_info, &blend_state_create_info, &dynamic_state_create_info, *PipelineLayout, *RenderPass, 0, VK_NULL_HANDLE, -1, pipeline_create_info ); std::vector<VkPipeline> pipeline; if( !CreateGraphicsPipelines( *LogicalDevice, { pipeline_create_info }, VK_NULL_HANDLE, pipeline ) ) { return false; } InitVkDestroyer( LogicalDevice, Pipeline ); *Pipeline = pipeline[0]; return true; } virtual bool Draw() override { auto prepare_frame = [&]( VkCommandBuffer command_buffer, uint32_t swapchain_image_index, VkFramebuffer framebuffer ) { if( !BeginCommandBufferRecordingOperation( command_buffer, VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT, nullptr ) ) { return false; } if( UpdateUniformBuffer ) { UpdateUniformBuffer = false; BufferTransition pre_transfer_transition = { *UniformBuffer, // VkBuffer Buffer VK_ACCESS_UNIFORM_READ_BIT, // VkAccessFlags CurrentAccess VK_ACCESS_TRANSFER_WRITE_BIT, // VkAccessFlags NewAccess VK_QUEUE_FAMILY_IGNORED, // uint32_t CurrentQueueFamily VK_QUEUE_FAMILY_IGNORED // uint32_t NewQueueFamily }; SetBufferMemoryBarrier( command_buffer, VK_PIPELINE_STAGE_VERTEX_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, { pre_transfer_transition } ); std::vector<VkBufferCopy> regions = { { 0, // VkDeviceSize srcOffset 0, // VkDeviceSize dstOffset 2 * 16 * sizeof( float ) // VkDeviceSize size } }; CopyDataBetweenBuffers( command_buffer, *StagingBuffer, *UniformBuffer, regions ); BufferTransition post_transfer_transition = { *UniformBuffer, // VkBuffer Buffer VK_ACCESS_TRANSFER_WRITE_BIT, // VkAccessFlags CurrentAccess VK_ACCESS_UNIFORM_READ_BIT, // VkAccessFlags NewAccess VK_QUEUE_FAMILY_IGNORED, // uint32_t CurrentQueueFamily VK_QUEUE_FAMILY_IGNORED // uint32_t NewQueueFamily }; SetBufferMemoryBarrier( command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_VERTEX_SHADER_BIT, { post_transfer_transition } ); } if( PresentQueue.FamilyIndex != GraphicsQueue.FamilyIndex ) { ImageTransition image_transition_before_drawing = { Swapchain.Images[swapchain_image_index], // VkImage Image VK_ACCESS_MEMORY_READ_BIT, // VkAccessFlags CurrentAccess VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, // VkAccessFlags NewAccess VK_IMAGE_LAYOUT_UNDEFINED, // VkImageLayout CurrentLayout VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, // VkImageLayout NewLayout PresentQueue.FamilyIndex, // uint32_t CurrentQueueFamily GraphicsQueue.FamilyIndex, // uint32_t NewQueueFamily VK_IMAGE_ASPECT_COLOR_BIT // VkImageAspectFlags Aspect }; SetImageMemoryBarrier( command_buffer, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, { image_transition_before_drawing } ); } // Drawing BeginRenderPass( command_buffer, *RenderPass, framebuffer, { { 0, 0 }, Swapchain.Size }, { { 0.1f, 0.2f, 0.3f, 1.0f }, { 1.0f, 0 } }, VK_SUBPASS_CONTENTS_INLINE ); VkViewport viewport = { 0.0f, // float x 0.0f, // float y static_cast<float>(Swapchain.Size.width), // float width static_cast<float>(Swapchain.Size.height), // float height 0.0f, // float minDepth 1.0f, // float maxDepth }; SetViewportStateDynamically( command_buffer, 0, { viewport } ); VkRect2D scissor = { { // VkOffset2D offset 0, // int32_t x 0 // int32_t y }, { // VkExtent2D extent Swapchain.Size.width, // uint32_t width Swapchain.Size.height // uint32_t height } }; SetScissorStateDynamically( command_buffer, 0, { scissor } ); BindVertexBuffers( command_buffer, 0, { { *VertexBuffer, 0 } } ); BindDescriptorSets( command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, *PipelineLayout, 0, DescriptorSets, {} ); BindPipelineObject( command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, *Pipeline ); for( size_t i = 0; i < Model.Parts.size(); ++i ) { DrawGeometry( command_buffer, Model.Parts[i].VertexCount, 1, Model.Parts[i].VertexOffset, 0 ); } EndRenderPass( command_buffer ); if( PresentQueue.FamilyIndex != GraphicsQueue.FamilyIndex ) { ImageTransition image_transition_before_present = { Swapchain.Images[swapchain_image_index], // VkImage Image VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, // VkAccessFlags CurrentAccess VK_ACCESS_MEMORY_READ_BIT, // VkAccessFlags NewAccess VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, // VkImageLayout CurrentLayout VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, // VkImageLayout NewLayout GraphicsQueue.FamilyIndex, // uint32_t CurrentQueueFamily PresentQueue.FamilyIndex, // uint32_t NewQueueFamily VK_IMAGE_ASPECT_COLOR_BIT // VkImageAspectFlags Aspect }; SetImageMemoryBarrier( command_buffer, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, { image_transition_before_present } ); } if( !EndCommandBufferRecordingOperation( command_buffer ) ) { return false; } return true; }; return IncreasePerformanceThroughIncreasingTheNumberOfSeparatelyRenderedFrames( *LogicalDevice, GraphicsQueue.Handle, PresentQueue.Handle, *Swapchain.Handle, Swapchain.Size, Swapchain.ImageViewsRaw, *RenderPass, {}, prepare_frame, FramesResources ); } void OnMouseEvent() { UpdateStagingBuffer( false ); } bool UpdateStagingBuffer( bool force ) { UpdateUniformBuffer = true; static float horizontal_angle = 0.0f; static float vertical_angle = 0.0f; if( MouseState.Buttons[0].IsPressed || force ) { horizontal_angle += 0.5f * MouseState.Position.Delta.X; vertical_angle -= 0.5f * MouseState.Position.Delta.Y; if( vertical_angle > 90.0f ) { vertical_angle = 90.0f; } if( vertical_angle < -90.0f ) { vertical_angle = -90.0f; } Matrix4x4 rotation_matrix = PrepareRotationMatrix( vertical_angle, { 1.0f, 0.0f, 0.0f } ) * PrepareRotationMatrix( horizontal_angle, { 0.0f, -1.0f, 0.0f } ); Matrix4x4 translation_matrix = PrepareTranslationMatrix( 0.0f, 0.0f, -4.0f ); Matrix4x4 model_view_matrix = translation_matrix * rotation_matrix; if( !MapUpdateAndUnmapHostVisibleMemory( *LogicalDevice, *StagingBufferMemory, 0, sizeof( model_view_matrix[0] ) * model_view_matrix.size(), &model_view_matrix[0], true, nullptr ) ) { return false; } Matrix4x4 perspective_matrix = PreparePerspectiveProjectionMatrix( static_cast<float>(Swapchain.Size.width) / static_cast<float>(Swapchain.Size.height), 50.0f, 0.5f, 10.0f ); if( !MapUpdateAndUnmapHostVisibleMemory( *LogicalDevice, *StagingBufferMemory, sizeof( model_view_matrix[0] ) * model_view_matrix.size(), sizeof( perspective_matrix[0] ) * perspective_matrix.size(), &perspective_matrix[0], true, nullptr ) ) { return false; } } return true; } virtual bool Resize() override { if( !CreateSwapchain() ) { return false; } if( IsReady() ) { if( !UpdateStagingBuffer( true ) ) { return false; } } return true; } }; VULKAN_COOKBOOK_SAMPLE_FRAMEWORK( "11/01 - Rendering a geometry with vertex diffuse lighting", 50, 25, 1280, 800, Sample )
PacktPublishing/Vulkan-Cookbook
Samples/Source Files/11 Lighting/01-Rendering_a_geometry_with_vertex_diffuse_lighting/main.cpp
C++
mit
27,469
# == Schema Information # # Table name: currencies # # id :integer not null, primary key # name :string # abbrev :string # created_at :datetime not null # updated_at :datetime not null # class Currency < ActiveRecord::Base validates :name, :abbrev, presence: true end
nevern02/bread_exchange
app/models/currency.rb
Ruby
mit
319
shared_examples 'collection::ansible' do include_examples 'python::toolchain' include_examples 'ansible::toolchain' end
webdevops/Dockerfile
tests/serverspec/spec/collection/ansible.rb
Ruby
mit
128
<div class="form-group fg-float"> <div class="fg-line"> {!! Form::text('name', null, array('class' => 'form-control fg-input')) !!} </div> {!! Form::label('name', 'Name', array('class' => 'fg-label')) !!} </div> <div class="form-group fg-float"> <div class="fg-line"> {!! Form::textarea('description', null, array('class' => 'form-control fg-input')) !!} </div> {!! Form::label('description', 'Description', array('class' => 'fg-label')) !!} </div> <div class="form-group fg-float"> <div class="fg-line"> {!! Form::text('count', null, array('class' => 'form-control fg-input')) !!} </div> {!! Form::label('count', 'Count', array('class' => 'fg-label')) !!} </div> <div class="form-group fg-float"> <div class="fg-line"> {!! Form::checkbox('sub_visible', 1, null, array('class' => 'form-control fg-input')) !!} </div> {!! Form::label('sub_visible', 'Visible', array('class' => 'fg-label')) !!} </div> <div class="form-group"> {!! Form::submit($submit_text, array('class' => 'btn btn-primary')) !!} </div>
freyr69/mh
resources/views/dom/count/partials/_form.blade.php
PHP
mit
1,108
package exercise.task5_kingsGambitExtended.utils; public class MessegeLogger { public static void log(String message){ System.out.println(message); } }
StoyanVitanov/SoftwareUniversity
Java Fundamentals/Java OOP Advanced/08.ObjectCommunication&Events/exercise/task5_kingsGambitExtended/utils/MessegeLogger.java
Java
mit
170
[![Build Status](https://travis-ci.org/artsy/Artsy-OSSUIFonts.svg?branch=master)](https://travis-ci.org/artsy/Artsy-OSSUIFonts) # Artsy+OSSUIFonts This project contains the fonts and UIFont categories required to make a project with standard artsy design. We cannot include the fonts that we would normally use in a public project, so these are the closest equivilents that are available and have open source-compatible licenses. You can find out more by checking out the websites for [EB Garamond](http://www.georgduffner.at/ebgaramond/index.html) and [TeX Gyre Adventor](http://www.gust.org.pl/projects/e-foundry/tex-gyre). To make it work you have to include in the Applications XX-Info.plist. See [here](https://github.com/artsy/Artsy-OSSUIFonts/blob/master/Example/FontApp/FontApp-Info.plist#L37-L45) for an example. ``` <array> <string>EBGaramond08-Italic.ttf</string> <string>EBGaramond08-Regular.ttf</string> <string>EBGaramond12-Italic.ttf</string> <string>EBGaramond12-Regular.ttf</string> <string>texgyreadventor-regular.ttf</string> </array> ``` ## Usage To run the example project; clone the repo, and run `pod install` from the Example directory first. ## Installation Artsy+OSSUIFonts is available through [CocoaPods](http://cocoapods.org), and the [Artsy Specs Repo](https://github.com/artsy/specs). To install the Specs repo run: pod repo add artsy https://github.com/artsy/Specs.git To install the pod, add following line to your Podfile: pod "Artsy+OSSUIFonts" ## Wrapper Orta, orta.therox@gmail.com ## License The Code itself is MIT. The font license for EB Garamonds is the [SIL Open Fonts License](http://scripts.sil.org/cms/scripts/page.php?site_id=nrsi&id=OFL) The font license for Text Gyre Adventor is the [GUST Font License](http://www.gust.org.pl/projects/e-foundry/index_html#GFL)
nealsun/Artsy-OSSUIFonts
README.md
Markdown
mit
1,856
<?php /** * Created by Khang Nguyen. * Email: khang.nguyen@banvien.com * Date: 10/3/2017 * Time: 9:33 AM */ ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Tin Đất Đai | Quản lý bài đăng</title> <?php $this->load->view('/admin/common/header-js') ?> <link rel="stylesheet" href="<?=base_url('/admin/css/bootstrap-datepicker.min.css')?>"> </head> <body class="hold-transition skin-blue sidebar-mini"> <div class="wrapper"> <!-- Main Header --> <?php $this->load->view('/admin/common/admin-header')?> <!-- Left side column. contains the logo and sidebar --> <?php $this->load->view('/admin/common/left-menu') ?> <!-- Content Wrapper. Contains page content --> <div class="content-wrapper"> <!-- Content Header (Page header) --> <section class="content-header"> <h1> Quản lý bài đăng <?=isset($user) ? 'của:<b> '.$user->FullName.' - '.$user->Phone.'</b>': ''?> </h1> <ol class="breadcrumb"> <li><a href="#"><i class="fa fa-dashboard"></i> Trang chủ</a></li> <li class="active">Quản lý bài đăng</li> </ol> </section> <!-- Main content --> <?php $attributes = array("id" => "frmPost"); echo form_open("admin/product/list", $attributes); ?> <section class="content container-fluid"> <?php if(!empty($message_response)){ echo '<div class="alert alert-success">'; echo '<a href="#" class="close" data-dismiss="alert" aria-label="close" title="close">&times;</a>'; echo $message_response; echo '</div>'; }?> <div class="box"> <div class="box-header"> <h3 class="box-title">Danh sách bài đăng</h3> </div> <!-- /.box-header --> <div class="box-body"> <div class="search-filter"> <div class="row"> <div class="col-sm-6"> <label>Tiêu đề</label> <div class="form-group"> <input type="text" name="searchFor" placeholder="Tìm tiêu đề" class="form-control" id="searchKey"> </div> </div> <div class="col-sm-2"> <label>Số điện thoại</label> <div class="form-group"> <input type="text" name="phoneNumber" class="form-control" id="phoneNumber"> </div> </div> <div class="col-sm-2"> <label>Từ ngày</label> <div class="form-group"> <input type="text" name="postFromDate" class="form-control datepicker" id="fromDate"> </div> </div> <div class="col-sm-2"> <label>Đến ngày</label> <div class="form-group"> <input type="text" name="postToDate" class="form-control datepicker" id="toDate"> </div> </div> <div class="col-sm-2"> <label>Mã tin(ID)</label> <div class="form-group"> <input type="text" name="code" class="form-control" id="code"> </div> </div> <div class="col-sm-3"> <label>Loại tin</label> <div class="form-group"> <label><input id="chb-0" checked="checked" type="radio" name="hasAuthor" value="-1"> Tất cả</label> <label><input id="chb-2" type="radio" name="hasAuthor" value="1"> Chính chủ</label> <label><input id="chb-1" type="radio" name="hasAuthor" value="0"> Crawler</label> </div> </div> <div class="col-sm-4"> <label>Tình trạng</label> <div class="form-group"> <label><input id="st_0" checked="checked" type="radio" name="status" value="-1"> Tất cả</label> <label><input id="st-1" type="radio" name="status" value="1"> Hoạt động</label> <label><input id="st-0" type="radio" name="status" value="0"> Tạm dừng</label> <label><input id="st-2" type="radio" name="status" value="2"> Chờ thanh toán</label> </div> </div> </div> <div class="text-center"> <a class="btn btn-primary" onclick="sendRequest()">Tìm kiếm</a> </div> </div> <div class="row no-margin"> <a class="btn btn-danger" id="deleteMulti">Xóa Nhiều</a> </div> <div class="table-responsive"> <table class="admin-table table table-bordered table-striped"> <thead> <tr> <th><input name="checkAll" value="1" type="checkbox" ></th> <th data-action="sort" data-title="Title" data-direction="ASC"><span>Tiêu đề</span><i class="glyphicon glyphicon-triangle-bottom"></i></th> <th data-action="sort" data-title="Status" data-direction="ASC"><span>Status</span><i class="glyphicon glyphicon-triangle-bottom"></i></th> <th data-action="sort" data-title="Vip" data-direction="ASC"><span>Loại tin</span><i class="glyphicon glyphicon-triangle-bottom"></i></th> <th data-action="sort" data-title="View" data-direction="ASC"><span>Lượt xem</span><i class="glyphicon glyphicon-triangle-bottom"></i></th> <th data-action="sort" data-title="PostDate" data-direction="ASC"><span>Ngày đăng</span><i class="glyphicon glyphicon-triangle-bottom"></i></th> <th data-action="sort" data-title="ExpireDate" data-direction="ASC"><span>Hết hạn</span><i class="glyphicon glyphicon-triangle-bottom"></i></th> <th data-action="sort" data-title="ModifiedDate" data-direction="ASC"><span>Cập nhật</span><i class="glyphicon glyphicon-triangle-bottom"></i></th> <th data-action="sort" data-title="CreatedByID" data-direction="ASC"><span>Người đăng</span><i class="glyphicon glyphicon-triangle-bottom"></i></th> <th data-action="sort" data-title="IpAddress" data-direction="ASC"><span>Ip Address</span><i class="glyphicon glyphicon-triangle-bottom"></i></th> <th></th> </tr> </thead> <tbody> <?php $counter = 1; foreach ($products as $product) { ?> <tr> <td><input name="checkList[]" type="checkbox" value="<?=$product->ProductID?>"></td> <td><a class="vip<?=$product->Vip?>" data-toggle="tooltip" title="<?=$product->Title?>" href="<?=base_url(seo_url($product->Title).'-p').$product->ProductID.'.html'?>"><?=substr_at_middle($product->Title, 60)?></a></td> <td> <?php if($product->Status == ACTIVE){ echo '<span class="label label-success">Show</span>'; }else if($product->Status == PAYMENT_DELAY){ echo '<span class="label label-info">Payment</span>'; } else{ echo '<span class="label label-danger">Hide</span>'; } ?> </td> <td> <select onchange="updateVip('<?=$product->ProductID?>', this.value);"> <option value="0" <?=$product->Vip == 0 ? ' selected' : ''?>>Vip 0</option> <option value="1" <?=$product->Vip == 1 ? ' selected' : ''?>>Vip 1</option> <option value="2" <?=$product->Vip == 2 ? ' selected' : ''?>>Vip 2</option> <option value="3" <?=$product->Vip == 3 ? ' selected' : ''?>>Vip 3</option> <option value="5" <?=$product->Vip == 5 ? ' selected' : ''?>>Thường</option> </select> </td> <td class="text-right"> <?php if(isset($product->FullName)) { ?> <input class="txtView" id="pr-<?=$product->ProductID?>" type="text" value="<?= $product->View?>" onchange="updateView('<?=$product->ProductID?>', this.value);"/> <?php }else{ echo $product->View; } ?> </td> <td><?=date('d/m/Y H:i', strtotime($product->PostDate))?></td> <td><?=date('d/m/Y', strtotime($product->ExpireDate))?></td> <td id="modifiedDate_<?=$product->ProductID?>"><?=date('d/m/Y H:i', strtotime($product->ModifiedDate))?></td> <td><a href="<?=base_url('/admin/product/list.html?createdById='.$product->CreatedByID)?>"><?=$product->FullName?></a> </td> <td><?=$product->IpAddress?></td> <td> <a href="<?=base_url('/admin/product/edit.html?postId='.$product->ProductID)?>" data-toggle="tooltip" title="Chỉnh sửa"><i class="glyphicon glyphicon-edit"></i></a>&nbsp;|&nbsp; <a onclick="pushPostUp('<?=$product->ProductID?>');" data-toggle="tooltip" title="Làm mới tin"><i class="glyphicon glyphicon-refresh"></i></a>&nbsp;|&nbsp; <a class="remove-post" data-post="<?=$product->ProductID?>" data-toggle="tooltip" title="Xóa tin đăng"><i class="glyphicon glyphicon-remove"></i></a> </td> </tr> <?php } ?> </tbody> </table> <div class="text-center"> <?php echo $pagination; ?> </div> </div> </div> </div> </section> <!-- /.content --> <input type="hidden" id="crudaction" name="crudaction"> <input type="hidden" id="productId" name="productId"> <?php echo form_close(); ?> </div> <!-- /.content-wrapper --> <!-- Main Footer --> <?php $this->load->view('/admin/common/admin-footer')?> </div> <!-- ./wrapper --> <!-- REQUIRED JS SCRIPTS --> <!-- jQuery 3 --> <script src="<?=base_url('/admin/js/jquery.min.js')?>"></script> <!-- Bootstrap 3.3.7 --> <script src="<?=base_url('/admin/js/bootstrap.min.js')?>"></script> <!-- AdminLTE App --> <script src="<?=base_url('/admin/js/adminlte.min.js')?>"></script> <script src="<?=base_url('/js/bootbox.min.js')?>"></script> <script src="<?=base_url('/admin/js/bootstrap-datepicker.min.js')?>"></script> <script src="<?=base_url('/admin/js/tindatdai_admin.js')?>"></script> <script type="text/javascript"> var sendRequest = function(){ var searchKey = $('#searchKey').val()||""; var fromDate = $('#fromDate').val()||""; var toDate = $('#toDate').val()||""; var code = $('#code').val()||""; var hasAuthor = $('input[name=hasAuthor]:checked').val(); var status = $('input[name=status]:checked').val(); var phoneNumber = $('#phoneNumber').val()||""; window.location.href = '<?=base_url('admin/product/list.html')?>?query='+searchKey + '&phoneNumber=' + phoneNumber + '&fromDate=' + fromDate + '&toDate=' + toDate + '&hasAuthor=' + hasAuthor + '&code=' + code + '&status=' + status + '&orderField='+curOrderField+'&orderDirection='+curOrderDirection; } var curOrderField, curOrderDirection; $('[data-action="sort"]').on('click', function(e){ curOrderField = $(this).data('title'); curOrderDirection = $(this).data('direction'); sendRequest(); }); $('#searchKey').val(decodeURIComponent(getNamedParameter('query')||"")); $('#fromDate').val(decodeURIComponent(getNamedParameter('fromDate')||"")); $('#toDate').val(decodeURIComponent(getNamedParameter('toDate')||"")); $('#code').val(decodeURIComponent(getNamedParameter('code')||"")); $('#phoneNumber').val(decodeURIComponent(getNamedParameter('phoneNumber')||"")); if(decodeURIComponent(getNamedParameter('hasAuthor')) != null){ $("#chb-" + (parseInt(decodeURIComponent(getNamedParameter('hasAuthor'))) + 1)).prop( "checked", true ); }else{ $("#chb-0").prop( "checked", true ); } if(decodeURIComponent(getNamedParameter('status')) != null){ $("#st-" + (parseInt(decodeURIComponent(getNamedParameter('status'))))).prop( "checked", true ); }else{ $("#st_0").prop( "checked", true ); } var curOrderField = getNamedParameter('orderField')||""; var curOrderDirection = getNamedParameter('orderDirection')||""; var currentSort = $('[data-action="sort"][data-title="'+getNamedParameter('orderField')+'"]'); if(curOrderDirection=="ASC"){ currentSort.attr('data-direction', "DESC").find('i.glyphicon').removeClass('glyphicon-triangle-bottom').addClass('glyphicon-triangle-top active'); }else{ currentSort.attr('data-direction', "ASC").find('i.glyphicon').removeClass('glyphicon-triangle-top').addClass('glyphicon-triangle-bottom active'); } function updateView(productId, val){ $("#pr-" + productId).addClass("process"); jQuery.ajax({ type: "POST", url: '<?=base_url("/Ajax_controller/updateViewForProductIdManual")?>', dataType: 'json', data: {productId: productId, view: val}, success: function(res){ if(res == 'success'){ /*bootbox.alert("Cập nhật thành công");*/ $("#pr-" + productId).addClass("success"); } } }); } function updateVip(productId, val){ jQuery.ajax({ type: "POST", url: '<?=base_url("/Ajax_controller/updateVipPackageForProductId")?>', dataType: 'json', data: {productId: productId, vip: val}, success: function(res){ if(res == 'success'){ bootbox.alert("Cập nhật thành công"); } } }); } function pushPostUp(productId){ jQuery.ajax({ type: "POST", url: '<?=base_url("/admin/ProductManagement_controller/pushPostUp")?>', dataType: 'json', data: {productId: productId}, success: function(res){ if(res == 'success'){ bootbox.alert("Cập nhật thành công"); } } }); } function deleteMultiplePostHandler(){ $("#deleteMulti").click(function(){ var selectedItems = $("input[name='checkList[]']:checked").length; if(selectedItems > 0) { bootbox.confirm("Bạn đã chắc chắn xóa những tin rao này chưa?", function (result) { if (result) { $("#crudaction").val("delete-multiple"); $("#frmPost").submit(); } }); }else{ bootbox.alert("Bạn chưa check chọn tin cần xóa!"); } }); } function deletePostHandler(){ $('.remove-post').click(function(){ var prId = $(this).data('post'); bootbox.confirm("Bạn đã chắc chắn xóa tin rao này chưa?", function(result){ if(result){ $("#productId").val(prId); $("#crudaction").val("delete"); $("#frmPost").submit(); } }); }); } $(document).ready(function(){ deletePostHandler(); deleteMultiplePostHandler(); }); </script> </body> </html>
jnguyen095/real-estate
application/views/admin/product/list.php
PHP
mit
13,824
import Form from 'cerebral-module-forms/Form' import submitForm from './chains/submitForm' import resetForm from './chains/resetForm' import validateForm from './chains/validateForm' export default (options = {}) => { return (module, controller) => { module.addState(Form({ name: { value: '', isRequired: true }, email: { value: '', validations: ['isEmail'], errorMessages: ['Not valid email'], isRequired: true }, password: { value: '', validations: ['equalsField:repeatPassword'], dependsOn: 'simple.repeatPassword', errorMessages: ['Not equal to repeated password'], isRequired: true }, repeatPassword: { value: '', validations: ['equalsField:password'], dependsOn: 'simple.password', errorMessages: ['Not equal to password'], isRequired: true }, address: Form({ street: { value: '' }, postalCode: { value: '', validations: ['isLength:4', 'isNumeric'], errorMessages: ['Has to be length 4', 'Can only contain numbers'] } }) })) module.addSignals({ formSubmitted: submitForm, resetClicked: resetForm, validateFormClicked: validateForm }) } }
cerebral/cerebral-module-forms
demo/modules/Simple/index.js
JavaScript
mit
1,344
namespace GarboDev { using System; using System.Collections.Generic; using System.Text; public partial class Renderer : IRenderer { private Memory memory; private uint[] scanline = new uint[240]; private byte[] blend = new byte[240]; private byte[] windowCover = new byte[240]; private uint[] back = new uint[240 * 160]; //private uint[] front = new uint[240 * 160]; private const uint pitch = 240; // Convenience variable as I use it everywhere, set once in RenderLine private ushort dispCnt; // Window helper variables private byte win0x1, win0x2, win0y1, win0y2; private byte win1x1, win1x2, win1y1, win1y2; private byte win0Enabled, win1Enabled, winObjEnabled, winOutEnabled; private bool winEnabled; private byte blendSource, blendTarget; private byte blendA, blendB, blendY; private int blendType; private int curLine = 0; private static uint[] colorLUT; static Renderer() { colorLUT = new uint[0x10000]; // Pre-calculate the color LUT for (uint i = 0; i <= 0xFFFF; i++) { uint r = (i & 0x1FU); uint g = (i & 0x3E0U) >> 5; uint b = (i & 0x7C00U) >> 10; r = (r << 3) | (r >> 2); g = (g << 3) | (g >> 2); b = (b << 3) | (b >> 2); colorLUT[i] = (r << 16) | (g << 8) | b; } } public Memory Memory { set { this.memory = value; } } public void Initialize(object data) { } public void Reset() { } public uint[] ShowFrame() { //Array.Copy(this.back, this.front, this.front.Length); //return this.front; return this.back; } public void RenderLine(int line) { this.curLine = line; // Render the line this.dispCnt = Memory.ReadU16(this.memory.IORam, Memory.DISPCNT); if ((this.dispCnt & (1 << 7)) != 0) { uint bgColor = Renderer.GbaTo32((ushort)0x7FFF); for (int i = 0; i < 240; i++) this.scanline[i] = bgColor; } else { this.winEnabled = false; if ((this.dispCnt & (1 << 13)) != 0) { // Calculate window 0 information ushort winy = Memory.ReadU16(this.memory.IORam, Memory.WIN0V); this.win0y1 = (byte)(winy >> 8); this.win0y2 = (byte)(winy & 0xff); ushort winx = Memory.ReadU16(this.memory.IORam, Memory.WIN0H); this.win0x1 = (byte)(winx >> 8); this.win0x2 = (byte)(winx & 0xff); if (this.win0x2 > 240 || this.win0x1 > this.win0x2) { this.win0x2 = 240; } if (this.win0y2 > 160 || this.win0y1 > this.win0y2) { this.win0y2 = 160; } this.win0Enabled = this.memory.IORam[Memory.WININ]; this.winEnabled = true; } if ((this.dispCnt & (1 << 14)) != 0) { // Calculate window 1 information ushort winy = Memory.ReadU16(this.memory.IORam, Memory.WIN1V); this.win1y1 = (byte)(winy >> 8); this.win1y2 = (byte)(winy & 0xff); ushort winx = Memory.ReadU16(this.memory.IORam, Memory.WIN1H); this.win1x1 = (byte)(winx >> 8); this.win1x2 = (byte)(winx & 0xff); if (this.win1x2 > 240 || this.win1x1 > this.win1x2) { this.win1x2 = 240; } if (this.win1y2 > 160 || this.win1y1 > this.win1y2) { this.win1y2 = 160; } this.win1Enabled = this.memory.IORam[Memory.WININ + 1]; this.winEnabled = true; } if ((this.dispCnt & (1 << 15)) != 0 && (this.dispCnt & (1 << 12)) != 0) { // Object windows are enabled this.winObjEnabled = this.memory.IORam[Memory.WINOUT + 1]; this.winEnabled = true; } if (this.winEnabled) { this.winOutEnabled = this.memory.IORam[Memory.WINOUT]; } // Calculate blending information ushort bldcnt = Memory.ReadU16(this.memory.IORam, Memory.BLDCNT); this.blendType = (bldcnt >> 6) & 0x3; this.blendSource = (byte)(bldcnt & 0x3F); this.blendTarget = (byte)((bldcnt >> 8) & 0x3F); ushort bldalpha = Memory.ReadU16(this.memory.IORam, Memory.BLDALPHA); this.blendA = (byte)(bldalpha & 0x1F); if (this.blendA > 0x10) this.blendA = 0x10; this.blendB = (byte)((bldalpha >> 8) & 0x1F); if (this.blendB > 0x10) this.blendB = 0x10; this.blendY = (byte)(this.memory.IORam[Memory.BLDY] & 0x1F); if (this.blendY > 0x10) this.blendY = 0x10; switch (this.dispCnt & 0x7) { case 0: this.RenderMode0Line(); break; case 1: this.RenderMode1Line(); break; case 2: this.RenderMode2Line(); break; case 3: this.RenderMode3Line(); break; case 4: this.RenderMode4Line(); break; case 5: this.RenderMode5Line(); break; } } Array.Copy(this.scanline, 0, this.back, this.curLine * Renderer.pitch, Renderer.pitch); } private void DrawBackdrop() { byte[] palette = this.memory.PaletteRam; // Initialize window coverage buffer if neccesary if (this.winEnabled) { for (int i = 0; i < 240; i++) { this.windowCover[i] = this.winOutEnabled; } if ((this.dispCnt & (1 << 15)) != 0) { // Sprite window this.DrawSpriteWindows(); } if ((this.dispCnt & (1 << 14)) != 0) { // Window 1 if (this.curLine >= this.win1y1 && this.curLine < this.win1y2) { for (int i = this.win1x1; i < this.win1x2; i++) { this.windowCover[i] = this.win1Enabled; } } } if ((this.dispCnt & (1 << 13)) != 0) { // Window 0 if (this.curLine >= this.win0y1 && this.curLine < this.win0y2) { for (int i = this.win0x1; i < this.win0x2; i++) { this.windowCover[i] = this.win0Enabled; } } } } // Draw backdrop first uint bgColor = Renderer.GbaTo32((ushort)(palette[0] | (palette[1] << 8))); uint modColor = bgColor; if (this.blendType == 2 && (this.blendSource & (1 << 5)) != 0) { // Brightness increase uint r = bgColor & 0xFF; uint g = (bgColor >> 8) & 0xFF; uint b = (bgColor >> 16) & 0xFF; r = r + (((0xFF - r) * this.blendY) >> 4); g = g + (((0xFF - g) * this.blendY) >> 4); b = b + (((0xFF - b) * this.blendY) >> 4); modColor = r | (g << 8) | (b << 16); } else if (this.blendType == 3 && (this.blendSource & (1 << 5)) != 0) { // Brightness decrease uint r = bgColor & 0xFF; uint g = (bgColor >> 8) & 0xFF; uint b = (bgColor >> 16) & 0xFF; r = r - ((r * this.blendY) >> 4); g = g - ((g * this.blendY) >> 4); b = b - ((b * this.blendY) >> 4); modColor = r | (g << 8) | (b << 16); } if (this.winEnabled) { for (int i = 0; i < 240; i++) { if ((this.windowCover[i] & (1 << 5)) != 0) { this.scanline[i] = modColor; } else { this.scanline[i] = bgColor; } this.blend[i] = 1 << 5; } } else { for (int i = 0; i < 240; i++) { this.scanline[i] = modColor; this.blend[i] = 1 << 5; } } } private void RenderTextBg(int bg) { if (this.winEnabled) { switch (this.blendType) { case 0: this.RenderTextBgWindow(bg); break; case 1: if ((this.blendSource & (1 << bg)) != 0) this.RenderTextBgWindowBlend(bg); else this.RenderTextBgWindow(bg); break; case 2: if ((this.blendSource & (1 << bg)) != 0) this.RenderTextBgWindowBrightInc(bg); else this.RenderTextBgWindow(bg); break; case 3: if ((this.blendSource & (1 << bg)) != 0) this.RenderTextBgWindowBrightDec(bg); else this.RenderTextBgWindow(bg); break; } } else { switch (this.blendType) { case 0: this.RenderTextBgNormal(bg); break; case 1: if ((this.blendSource & (1 << bg)) != 0) this.RenderTextBgBlend(bg); else this.RenderTextBgNormal(bg); break; case 2: if ((this.blendSource & (1 << bg)) != 0) this.RenderTextBgBrightInc(bg); else this.RenderTextBgNormal(bg); break; case 3: if ((this.blendSource & (1 << bg)) != 0) this.RenderTextBgBrightDec(bg); else this.RenderTextBgNormal(bg); break; } } } private void RenderRotScaleBg(int bg) { if (this.winEnabled) { switch (this.blendType) { case 0: this.RenderRotScaleBgWindow(bg); break; case 1: if ((this.blendSource & (1 << bg)) != 0) this.RenderRotScaleBgWindowBlend(bg); else this.RenderRotScaleBgWindow(bg); break; case 2: if ((this.blendSource & (1 << bg)) != 0) this.RenderRotScaleBgWindowBrightInc(bg); else this.RenderRotScaleBgWindow(bg); break; case 3: if ((this.blendSource & (1 << bg)) != 0) this.RenderRotScaleBgWindowBrightDec(bg); else this.RenderRotScaleBgWindow(bg); break; } } else { switch (this.blendType) { case 0: this.RenderRotScaleBgNormal(bg); break; case 1: if ((this.blendSource & (1 << bg)) != 0) this.RenderRotScaleBgBlend(bg); else this.RenderRotScaleBgNormal(bg); break; case 2: if ((this.blendSource & (1 << bg)) != 0) this.RenderRotScaleBgBrightInc(bg); else this.RenderRotScaleBgNormal(bg); break; case 3: if ((this.blendSource & (1 << bg)) != 0) this.RenderRotScaleBgBrightDec(bg); else this.RenderRotScaleBgNormal(bg); break; } } } private void DrawSprites(int pri) { if (this.winEnabled) { switch (this.blendType) { case 0: this.DrawSpritesWindow(pri); break; case 1: if ((this.blendSource & (1 << 4)) != 0) this.DrawSpritesWindowBlend(pri); else this.DrawSpritesWindow(pri); break; case 2: if ((this.blendSource & (1 << 4)) != 0) this.DrawSpritesWindowBrightInc(pri); else this.DrawSpritesWindow(pri); break; case 3: if ((this.blendSource & (1 << 4)) != 0) this.DrawSpritesWindowBrightDec(pri); else this.DrawSpritesWindow(pri); break; } } else { switch (this.blendType) { case 0: this.DrawSpritesNormal(pri); break; case 1: if ((this.blendSource & (1 << 4)) != 0) this.DrawSpritesBlend(pri); else this.DrawSpritesNormal(pri); break; case 2: if ((this.blendSource & (1 << 4)) != 0) this.DrawSpritesBrightInc(pri); else this.DrawSpritesNormal(pri); break; case 3: if ((this.blendSource & (1 << 4)) != 0) this.DrawSpritesBrightDec(pri); else this.DrawSpritesNormal(pri); break; } } } private void RenderMode0Line() { byte[] palette = this.memory.PaletteRam; byte[] vram = this.memory.VideoRam; this.DrawBackdrop(); for (int pri = 3; pri >= 0; pri--) { for (int i = 3; i >= 0; i--) { if ((this.dispCnt & (1 << (8 + i))) != 0) { ushort bgcnt = Memory.ReadU16(this.memory.IORam, Memory.BG0CNT + 0x2 * (uint)i); if ((bgcnt & 0x3) == pri) { this.RenderTextBg(i); } } } this.DrawSprites(pri); } } private void RenderMode1Line() { byte[] palette = this.memory.PaletteRam; byte[] vram = this.memory.VideoRam; this.DrawBackdrop(); for (int pri = 3; pri >= 0; pri--) { if ((this.dispCnt & (1 << (8 + 2))) != 0) { ushort bgcnt = Memory.ReadU16(this.memory.IORam, Memory.BG2CNT); if ((bgcnt & 0x3) == pri) { this.RenderRotScaleBg(2); } } for (int i = 1; i >= 0; i--) { if ((this.dispCnt & (1 << (8 + i))) != 0) { ushort bgcnt = Memory.ReadU16(this.memory.IORam, Memory.BG0CNT + 0x2 * (uint)i); if ((bgcnt & 0x3) == pri) { this.RenderTextBg(i); } } } this.DrawSprites(pri); } } private void RenderMode2Line() { byte[] palette = this.memory.PaletteRam; byte[] vram = this.memory.VideoRam; this.DrawBackdrop(); for (int pri = 3; pri >= 0; pri--) { for (int i = 3; i >= 2; i--) { if ((this.dispCnt & (1 << (8 + i))) != 0) { ushort bgcnt = Memory.ReadU16(this.memory.IORam, Memory.BG0CNT + 0x2 * (uint)i); if ((bgcnt & 0x3) == pri) { this.RenderRotScaleBg(i); } } } this.DrawSprites(pri); } } private void RenderMode3Line() { ushort bg2Cnt = Memory.ReadU16(this.memory.IORam, Memory.BG2CNT); byte[] palette = this.memory.PaletteRam; byte[] vram = this.memory.VideoRam; this.DrawBackdrop(); byte blendMaskType = (byte)(1 << 2); int bgPri = bg2Cnt & 0x3; for (int pri = 3; pri > bgPri; pri--) { this.DrawSprites(pri); } if ((this.dispCnt & (1 << 10)) != 0) { // Background enabled, render it int x = this.memory.Bgx[0]; int y = this.memory.Bgy[0]; short dx = (short)Memory.ReadU16(this.memory.IORam, Memory.BG2PA); short dy = (short)Memory.ReadU16(this.memory.IORam, Memory.BG2PC); for (int i = 0; i < 240; i++) { int ax = ((int)x) >> 8; int ay = ((int)y) >> 8; if (ax >= 0 && ax < 240 && ay >= 0 && ay < 160) { int curIdx = ((ay * 240) + ax) * 2; this.scanline[i] = Renderer.GbaTo32((ushort)(vram[curIdx] | (vram[curIdx + 1] << 8))); this.blend[i] = blendMaskType; } x += dx; y += dy; } } for (int pri = bgPri; pri >= 0; pri--) { this.DrawSprites(pri); } } private void RenderMode4Line() { ushort bg2Cnt = Memory.ReadU16(this.memory.IORam, Memory.BG2CNT); byte[] palette = this.memory.PaletteRam; byte[] vram = this.memory.VideoRam; this.DrawBackdrop(); byte blendMaskType = (byte)(1 << 2); int bgPri = bg2Cnt & 0x3; for (int pri = 3; pri > bgPri; pri--) { this.DrawSprites(pri); } if ((this.dispCnt & (1 << 10)) != 0) { // Background enabled, render it int baseIdx = 0; if ((this.dispCnt & (1 << 4)) == 1 << 4) baseIdx = 0xA000; int x = this.memory.Bgx[0]; int y = this.memory.Bgy[0]; short dx = (short)Memory.ReadU16(this.memory.IORam, Memory.BG2PA); short dy = (short)Memory.ReadU16(this.memory.IORam, Memory.BG2PC); for (int i = 0; i < 240; i++) { int ax = ((int)x) >> 8; int ay = ((int)y) >> 8; if (ax >= 0 && ax < 240 && ay >= 0 && ay < 160) { int lookup = vram[baseIdx + (ay * 240) + ax]; if (lookup != 0) { this.scanline[i] = Renderer.GbaTo32((ushort)(palette[lookup * 2] | (palette[lookup * 2 + 1] << 8))); this.blend[i] = blendMaskType; } } x += dx; y += dy; } } for (int pri = bgPri; pri >= 0; pri--) { this.DrawSprites(pri); } } private void RenderMode5Line() { ushort bg2Cnt = Memory.ReadU16(this.memory.IORam, Memory.BG2CNT); byte[] palette = this.memory.PaletteRam; byte[] vram = this.memory.VideoRam; this.DrawBackdrop(); byte blendMaskType = (byte)(1 << 2); int bgPri = bg2Cnt & 0x3; for (int pri = 3; pri > bgPri; pri--) { this.DrawSprites(pri); } if ((this.dispCnt & (1 << 10)) != 0) { // Background enabled, render it int baseIdx = 0; if ((this.dispCnt & (1 << 4)) == 1 << 4) baseIdx += 160 * 128 * 2; int x = this.memory.Bgx[0]; int y = this.memory.Bgy[0]; short dx = (short)Memory.ReadU16(this.memory.IORam, Memory.BG2PA); short dy = (short)Memory.ReadU16(this.memory.IORam, Memory.BG2PC); for (int i = 0; i < 240; i++) { int ax = ((int)x) >> 8; int ay = ((int)y) >> 8; if (ax >= 0 && ax < 160 && ay >= 0 && ay < 128) { int curIdx = (int)(ay * 160 + ax) * 2; this.scanline[i] = Renderer.GbaTo32((ushort)(vram[baseIdx + curIdx] | (vram[baseIdx + curIdx + 1] << 8))); this.blend[i] = blendMaskType; } x += dx; y += dy; } } for (int pri = bgPri; pri >= 0; pri--) { this.DrawSprites(pri); } } private void DrawSpriteWindows() { byte[] palette = this.memory.PaletteRam; byte[] vram = this.memory.VideoRam; // OBJ must be enabled in this.dispCnt if ((this.dispCnt & (1 << 12)) == 0) return; for (int oamNum = 127; oamNum >= 0; oamNum--) { ushort attr0 = this.memory.ReadU16Debug(Memory.OAM_BASE + (uint)(oamNum * 8) + 0); // Not an object window, so continue if (((attr0 >> 10) & 3) != 2) continue; ushort attr1 = this.memory.ReadU16Debug(Memory.OAM_BASE + (uint)(oamNum * 8) + 2); ushort attr2 = this.memory.ReadU16Debug(Memory.OAM_BASE + (uint)(oamNum * 8) + 4); int x = attr1 & 0x1FF; int y = attr0 & 0xFF; int width = -1, height = -1; switch ((attr0 >> 14) & 3) { case 0: // Square switch ((attr1 >> 14) & 3) { case 0: width = 8; height = 8; break; case 1: width = 16; height = 16; break; case 2: width = 32; height = 32; break; case 3: width = 64; height = 64; break; } break; case 1: // Horizontal Rectangle switch ((attr1 >> 14) & 3) { case 0: width = 16; height = 8; break; case 1: width = 32; height = 8; break; case 2: width = 32; height = 16; break; case 3: width = 64; height = 32; break; } break; case 2: // Vertical Rectangle switch ((attr1 >> 14) & 3) { case 0: width = 8; height = 16; break; case 1: width = 8; height = 32; break; case 2: width = 16; height = 32; break; case 3: width = 32; height = 64; break; } break; } // Check double size flag here int rwidth = width, rheight = height; if ((attr0 & (1 << 8)) != 0) { // Rot-scale on if ((attr0 & (1 << 9)) != 0) { rwidth *= 2; rheight *= 2; } } else { // Invalid sprite if ((attr0 & (1 << 9)) != 0) width = -1; } if (width == -1) { // Invalid sprite continue; } // Y clipping if (y > ((y + rheight) & 0xff)) { if (this.curLine >= ((y + rheight) & 0xff) && !(y < this.curLine)) continue; } else { if (this.curLine < y || this.curLine >= ((y + rheight) & 0xff)) continue; } int scale = 1; if ((attr0 & (1 << 13)) != 0) scale = 2; int spritey = this.curLine - y; if (spritey < 0) spritey += 256; if ((attr0 & (1 << 8)) == 0) { if ((attr1 & (1 << 13)) != 0) spritey = (height - 1) - spritey; int baseSprite; if ((this.dispCnt & (1 << 6)) != 0) { // 1 dimensional baseSprite = (attr2 & 0x3FF) + ((spritey / 8) * (width / 8)) * scale; } else { // 2 dimensional baseSprite = (attr2 & 0x3FF) + ((spritey / 8) * 0x20); } int baseInc = scale; if ((attr1 & (1 << 12)) != 0) { baseSprite += ((width / 8) * scale) - scale; baseInc = -baseInc; } if ((attr0 & (1 << 13)) != 0) { // 256 colors for (int i = x; i < x + width; i++) { if ((i & 0x1ff) < 240) { int tx = (i - x) & 7; if ((attr1 & (1 << 12)) != 0) tx = 7 - tx; int curIdx = baseSprite * 32 + ((spritey & 7) * 8) + tx; int lookup = vram[0x10000 + curIdx]; if (lookup != 0) { this.windowCover[i & 0x1ff] = this.winObjEnabled; } } if (((i - x) & 7) == 7) baseSprite += baseInc; } } else { // 16 colors int palIdx = 0x200 + (((attr2 >> 12) & 0xF) * 16 * 2); for (int i = x; i < x + width; i++) { if ((i & 0x1ff) < 240) { int tx = (i - x) & 7; if ((attr1 & (1 << 12)) != 0) tx = 7 - tx; int curIdx = baseSprite * 32 + ((spritey & 7) * 4) + (tx / 2); int lookup = vram[0x10000 + curIdx]; if ((tx & 1) == 0) { lookup &= 0xf; } else { lookup >>= 4; } if (lookup != 0) { this.windowCover[i & 0x1ff] = this.winObjEnabled; } } if (((i - x) & 7) == 7) baseSprite += baseInc; } } } else { int rotScaleParam = (attr1 >> 9) & 0x1F; short dx = (short)this.memory.ReadU16Debug(Memory.OAM_BASE + (uint)(rotScaleParam * 8 * 4) + 0x6); short dmx = (short)this.memory.ReadU16Debug(Memory.OAM_BASE + (uint)(rotScaleParam * 8 * 4) + 0xE); short dy = (short)this.memory.ReadU16Debug(Memory.OAM_BASE + (uint)(rotScaleParam * 8 * 4) + 0x16); short dmy = (short)this.memory.ReadU16Debug(Memory.OAM_BASE + (uint)(rotScaleParam * 8 * 4) + 0x1E); int cx = rwidth / 2; int cy = rheight / 2; int baseSprite = attr2 & 0x3FF; int pitch; if ((this.dispCnt & (1 << 6)) != 0) { // 1 dimensional pitch = (width / 8) * scale; } else { // 2 dimensional pitch = 0x20; } short rx = (short)((dmx * (spritey - cy)) - (cx * dx) + (width << 7)); short ry = (short)((dmy * (spritey - cy)) - (cx * dy) + (height << 7)); // Draw a rot/scale sprite if ((attr0 & (1 << 13)) != 0) { // 256 colors for (int i = x; i < x + rwidth; i++) { int tx = rx >> 8; int ty = ry >> 8; if ((i & 0x1ff) < 240 && tx >= 0 && tx < width && ty >= 0 && ty < height) { int curIdx = (baseSprite + ((ty / 8) * pitch) + ((tx / 8) * scale)) * 32 + ((ty & 7) * 8) + (tx & 7); int lookup = vram[0x10000 + curIdx]; if (lookup != 0) { this.windowCover[i & 0x1ff] = this.winObjEnabled; } } rx += dx; ry += dy; } } else { // 16 colors int palIdx = 0x200 + (((attr2 >> 12) & 0xF) * 16 * 2); for (int i = x; i < x + rwidth; i++) { int tx = rx >> 8; int ty = ry >> 8; if ((i & 0x1ff) < 240 && tx >= 0 && tx < width && ty >= 0 && ty < height) { int curIdx = (baseSprite + ((ty / 8) * pitch) + ((tx / 8) * scale)) * 32 + ((ty & 7) * 4) + ((tx & 7) / 2); int lookup = vram[0x10000 + curIdx]; if ((tx & 1) == 0) { lookup &= 0xf; } else { lookup >>= 4; } if (lookup != 0) { this.windowCover[i & 0x1ff] = this.winObjEnabled; } } rx += dx; ry += dy; } } } } } public static uint GbaTo32(ushort color) { // more accurate, but slower :( // return colorLUT[color]; return ((color & 0x1FU) << 19) | ((color & 0x3E0U) << 6) | ((color & 0x7C00U) >> 7); } } }
superusercode/RTC3
Real-Time Corruptor/BizHawk_RTC/attic/GarboDev/Renderer.cs
C#
mit
34,326
--- layout: page title: Green Storm Tech Executive Retreat date: 2016-05-24 author: Austin Dixon tags: weekly links, java status: published summary: Class aptent taciti sociosqu ad litora torquent per. banner: images/banner/leisure-04.jpg booking: startDate: 11/11/2019 endDate: 11/13/2019 ctyhocn: GXYCOHX groupCode: GSTER published: true --- Donec fringilla libero sit amet arcu ullamcorper, a tincidunt turpis facilisis. Morbi blandit justo eget elit rutrum, faucibus dapibus nunc vulputate. Sed placerat vel diam eget suscipit. Nulla tempus turpis nec nulla gravida, at porta quam tempus. Cras efficitur pretium rutrum. Phasellus tellus lectus, blandit ut purus vel, egestas vulputate lectus. Suspendisse mi odio, volutpat sit amet libero eu, gravida maximus diam. Vestibulum vulputate elit id lacus porttitor semper. Maecenas libero velit, faucibus et convallis quis, dignissim at neque. Donec eget gravida risus. Sed odio enim, maximus ac sagittis vitae, ornare nec nisl. Vivamus non augue eget sapien aliquam fermentum. Praesent dictum tellus a metus tristique, a feugiat libero semper. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; * Sed ut sem non nibh venenatis aliquam sit amet non mauris * Etiam sed purus tempor, vestibulum felis ultrices, malesuada nisl * Nullam eget lorem mattis, condimentum mauris quis, interdum nisl. Cras non odio et tellus consequat faucibus. Nulla id porttitor dui. Nulla sed turpis quis sem elementum pharetra et sed diam. Nam nec turpis nec dolor convallis scelerisque quis in metus. Quisque a elementum elit. Phasellus sit amet ornare justo. Nulla eget ex ac eros blandit bibendum. Nulla sed tincidunt velit. Pellentesque et ligula odio. Aenean a orci quis tortor tristique egestas. Integer ac venenatis nulla, eget pulvinar mi. Vestibulum erat turpis, efficitur sed ligula eu, iaculis tincidunt lacus. Aliquam id massa sit amet enim porttitor auctor.
KlishGroup/prose-pogs
pogs/G/GXYCOHX/GSTER/index.md
Markdown
mit
1,945
package models import java.util.UUID import play.api.db.slick.Config.driver.simple._ import org.joda.time.DateTime import com.github.tototoshi.slick.HsqldbJodaSupport._ case class ClientGrantType( clientId: String, grantTypeId: Int ) extends Model class ClientGrantTypes(tag: Tag) extends Table[ClientGrantType](tag, "CLIENT_GRANT_TYPES") { def clientId = column[String]("CLIENT_ID") def grantTypeId = column[Int]("GRANT_TYPE_ID") def * = (clientId, grantTypeId) <> (ClientGrantType.tupled, ClientGrantType.unapply) val pk = primaryKey("PK_CLIENT_GRANT_TYPE", (clientId, grantTypeId)) } object ClientGrantTypes extends BaseSlickTrait[ClientGrantType] { override protected def model = TableQueries.clientGrantTypes }
maximx1/roma_quantum
app/models/ClientGrantType.scala
Scala
mit
738
<?php $data = array ( 0 => array ( 'id' => '3', 'name' => '三国杀', 'desc' => '三国演义', 'parent_id' => '0', 'has_child' => '0', 'is_show' => '0', 'level' => '1', 'type' => '0', 'sort' => '0', ), ); ?>
Bingle-labake/coollive.com.cn
public/data/static/prototype_cate_releate.php
PHP
mit
254
<?php namespace AppBundle\Controller; use AppBundle\Entity\BillingAddress; use AppBundle\Entity\ShippingAddress; use AppBundle\Form\BillingAddressFormType; use AppBundle\Form\ShippingAddressFormType; use AppBundle\Form\ShippingMethodFormType; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; class CheckoutController extends Controller { /** * @Route("/checkout/billing",name="billing-address") * */ public function billingAddressAction(Request $request) { $user = $this->get('security.token_storage')->getToken()->getUser(); $em = $this->getDoctrine()->getManager(); $cart = $em->getRepository('AppBundle:Cart') ->findMyCart($user); $billingAddress = new BillingAddress(); $billingAddress->setUser($user); $billingAddress->setFirstName($user->getFirstName()); $billingAddress->setLastName($user->getLastName()); $billingAddress->setEmailAddress($user->getUserName()); $form = $this->createForm(BillingAddressFormType::class, $billingAddress); //only handles data on POST $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $billingAddress = $form->getData(); $em = $this->getDoctrine()->getManager(); $em->persist($billingAddress); $em->flush(); return $this->redirectToRoute('shipping-address'); } return $this->render(':partials:checkout-billing.htm.twig', [ 'billingAddressForm' => $form->createView(), 'cart' => $cart[0] ]); } /** * @Route("/checkout/shipping",name="shipping-address") * */ public function shippingAddressAction(Request $request) { $user = $this->get('security.token_storage')->getToken()->getUser(); $em = $this->getDoctrine()->getManager(); $cart = $em->getRepository('AppBundle:Cart') ->findMyCart($user); $shippingAddress = new ShippingAddress(); $shippingAddress->setUser($user); $shippingAddress->setFirstName($user->getFirstName()); $shippingAddress->setLastName($user->getLastName()); $shippingAddress->setEmailAddress($user->getUserName()); $form = $this->createForm(ShippingAddressFormType::class, $shippingAddress); //only handles data on POST $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $shippingAddress = $form->getData(); $em = $this->getDoctrine()->getManager(); $em->persist($shippingAddress); $em->flush(); return $this->redirectToRoute('shipping-method'); } return $this->render(':partials:checkout-shipping-address.htm.twig', [ 'shippingAddressForm' => $form->createView(), 'cart' => $cart[0] ]); } /** * @Route("/checkout/shipping-method",name="shipping-method") * */ public function shippingMethodAction(Request $request) { $user = $this->get('security.token_storage')->getToken()->getUser(); $em = $this->getDoctrine()->getManager(); $cart = $em->getRepository('AppBundle:Cart') ->findMyCart($user); $shippingAddress = new ShippingAddress(); $shippingAddress->setUser($user); $form = $this->createForm(ShippingMethodFormType::class); //only handles data on POST $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $category = $form->getData(); $em = $this->getDoctrine()->getManager(); $em->persist($category); $em->flush(); return $this->redirectToRoute('shipping-method'); } return $this->render(':partials:checkout-shipping-method.htm.twig', [ 'shippingMethodForm' => $form->createView(), 'cart' => $cart[0] ]); } /** * @Route("/checkout/payment",name="payment") * */ public function paymentAction(Request $request) { $user = $this->get('security.token_storage')->getToken()->getUser(); $em = $this->getDoctrine()->getManager(); $cart = $em->getRepository('AppBundle:Cart') ->findMyCart($user); $form = $this->createForm(ShippingAddressFormType::class); //only handles data on POST $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $category = $form->getData(); $em = $this->getDoctrine()->getManager(); $em->persist($category); $em->flush(); return $this->redirectToRoute('shipping-method'); } return $this->render(':partials:checkout-pay.htm.twig', [ 'paymentForm' => $form->createView(), 'cart' => $cart[0] ]); } }
creative-junk/Webshop
src/AppBundle/Controller/CheckoutController.php
PHP
mit
5,055
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("MVCAngularJS.Aplicacao")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("MVCAngularJS.Aplicacao")] [assembly: AssemblyCopyright("Copyright © Microsoft 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("99fa9143-c9b1-4f28-ab07-79cb1b49c950")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
gabrielsimas/SistemasExemplo
DDD/SPAAngularJSMVC/Solucao/MVCAngularJS.Aplicacao/Properties/AssemblyInfo.cs
C#
mit
1,438
"use strict"; define("ace/snippets/scala", ["require", "exports", "module"], function (require, exports, module) { "use strict"; exports.snippetText = undefined; exports.scope = "scala"; });
IonicaBizau/arc-assembler
clients/ace-builds/src/snippets/scala.js
JavaScript
mit
198
<?php /** * Helper. * * @copyright Ralf Koester (RK) * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License * @author Ralf Koester <ralf@familie-koester.de>. * @link http://k62.de * @link http://zikula.org * @version Generated by ModuleStudio (https://modulestudio.de). */ namespace RK\HelperModule\Controller\Base; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Security\Core\Exception\AccessDeniedException; use Zikula\Core\Controller\AbstractController; use Zikula\Core\Response\PlainResponse; /** * Controller for external calls base class. */ abstract class AbstractExternalController extends AbstractController { /** * Displays one item of a certain object type using a separate template for external usages. * * @param Request $request The current request * @param string $objectType The currently treated object type * @param int $id Identifier of the entity to be shown * @param string $source Source of this call (contentType or scribite) * @param string $displayMode Display mode (link or embed) * * @return string Desired data output */ public function displayAction(Request $request, $objectType, $id, $source, $displayMode) { $controllerHelper = $this->get('rk_helper_module.controller_helper'); $contextArgs = ['controller' => 'external', 'action' => 'display']; if (!in_array($objectType, $controllerHelper->getObjectTypes('controllerAction', $contextArgs))) { $objectType = $controllerHelper->getDefaultObjectType('controllerAction', $contextArgs); } $component = 'RKHelperModule:' . ucfirst($objectType) . ':'; if (!$this->hasPermission($component, $id . '::', ACCESS_READ)) { return ''; } $entityFactory = $this->get('rk_helper_module.entity_factory'); $repository = $entityFactory->getRepository($objectType); // assign object data fetched from the database $entity = $repository->selectById($id); if (null === $entity) { return new Response($this->__('No such item.')); } $template = $request->query->has('template') ? $request->query->get('template', null) : null; if (null === $template || $template == '') { $template = 'display.html.twig'; } $templateParameters = [ 'objectType' => $objectType, 'source' => $source, $objectType => $entity, 'displayMode' => $displayMode ]; $contextArgs = ['controller' => 'external', 'action' => 'display']; $templateParameters = $this->get('rk_helper_module.controller_helper')->addTemplateParameters($objectType, $templateParameters, 'controllerAction', $contextArgs); return $this->render('@RKHelperModule/External/' . ucfirst($objectType) . '/' . $template, $templateParameters); } /** * Popup selector for Scribite plugins. * Finds items of a certain object type. * * @param Request $request The current request * @param string $objectType The object type * @param string $editor Name of used Scribite editor * @param string $sort Sorting field * @param string $sortdir Sorting direction * @param int $pos Current pager position * @param int $num Amount of entries to display * * @return output The external item finder page * * @throws AccessDeniedException Thrown if the user doesn't have required permissions */ public function finderAction(Request $request, $objectType, $editor, $sort, $sortdir, $pos = 1, $num = 0) { $assetHelper = $this->get('zikula_core.common.theme.asset_helper'); $cssAssetBag = $this->get('zikula_core.common.theme.assets_css'); $cssAssetBag->add($assetHelper->resolve('@RKHelperModule:css/style.css')); $activatedObjectTypes = $this->getVar('enabledFinderTypes', []); if (!in_array($objectType, $activatedObjectTypes)) { if (!count($activatedObjectTypes)) { throw new AccessDeniedException(); } // redirect to first valid object type $redirectUrl = $this->get('router')->generate('rkhelpermodule_external_finder', ['objectType' => array_shift($activatedObjectTypes), 'editor' => $editor]); return new RedirectResponse($redirectUrl); } if (!$this->hasPermission('RKHelperModule:' . ucfirst($objectType) . ':', '::', ACCESS_COMMENT)) { throw new AccessDeniedException(); } if (empty($editor) || !in_array($editor, ['ckeditor', 'quill', 'summernote', 'tinymce'])) { return new Response($this->__('Error: Invalid editor context given for external controller action.')); } $repository = $this->get('rk_helper_module.entity_factory')->getRepository($objectType); if (empty($sort) || !in_array($sort, $repository->getAllowedSortingFields())) { $sort = $repository->getDefaultSortingField(); } $sdir = strtolower($sortdir); if ($sdir != 'asc' && $sdir != 'desc') { $sdir = 'asc'; } // the current offset which is used to calculate the pagination $currentPage = (int) $pos; // the number of items displayed on a page for pagination $resultsPerPage = (int) $num; if ($resultsPerPage == 0) { $resultsPerPage = $this->getVar('pageSize', 20); } $templateParameters = [ 'editorName' => $editor, 'objectType' => $objectType, 'sort' => $sort, 'sortdir' => $sdir, 'currentPage' => $currentPage, 'onlyImages' => false, 'imageField' => '' ]; $searchTerm = ''; $formOptions = [ 'object_type' => $objectType, 'editor_name' => $editor ]; $form = $this->createForm('RK\HelperModule\Form\Type\Finder\\' . ucfirst($objectType) . 'FinderType', $templateParameters, $formOptions); if ($form->handleRequest($request)->isValid()) { $formData = $form->getData(); $templateParameters = array_merge($templateParameters, $formData); $currentPage = $formData['currentPage']; $resultsPerPage = $formData['num']; $sort = $formData['sort']; $sdir = $formData['sortdir']; $searchTerm = $formData['q']; $templateParameters['onlyImages'] = isset($formData['onlyImages']) ? (bool)$formData['onlyImages'] : false; $templateParameters['imageField'] = isset($formData['imageField']) ? $formData['imageField'] : ''; } $where = ''; $orderBy = $sort . ' ' . $sdir; $qb = $repository->getListQueryBuilder($where, $orderBy); if (true === $templateParameters['onlyImages'] && $templateParameters['imageField'] != '') { $imageField = $templateParameters['imageField']; $orX = $qb->expr()->orX(); foreach (['gif', 'jpg', 'jpeg', 'jpe', 'png', 'bmp'] as $imageExtension) { $orX->add($qb->expr()->like('tbl.' . $imageField, $qb->expr()->literal('%.' . $imageExtension))); } $qb->andWhere($orX); } if ($searchTerm != '') { $qb = $this->get('rk_helper_module.collection_filter_helper')->addSearchFilter($objectType, $qb, $searchTerm); } $query = $repository->getQueryFromBuilder($qb); list($entities, $objectCount) = $repository->retrieveCollectionResult($query, true); $templateParameters['items'] = $entities; $templateParameters['finderForm'] = $form->createView(); $contextArgs = ['controller' => 'external', 'action' => 'display']; $templateParameters = $this->get('rk_helper_module.controller_helper')->addTemplateParameters($objectType, $templateParameters, 'controllerAction', $contextArgs); $templateParameters['pager'] = [ 'numitems' => $objectCount, 'itemsperpage' => $resultsPerPage ]; $output = $this->renderView('@RKHelperModule/External/' . ucfirst($objectType) . '/find.html.twig', $templateParameters); return new PlainResponse($output); } }
rallek/helper
src/modules/RK/HelperModule/Controller/Base/AbstractExternalController.php
PHP
mit
8,824
// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main import ( "errors" "go/build" "testing" "github.com/golang/dep/internal/gps" "github.com/golang/dep/internal/gps/pkgtree" ) func TestInvalidEnsureFlagCombinations(t *testing.T) { ec := &ensureCommand{ update: true, add: true, } if err := ec.validateFlags(); err == nil { t.Error("-add and -update together should fail validation") } ec.vendorOnly, ec.add = true, false if err := ec.validateFlags(); err == nil { t.Error("-vendor-only with -update should fail validation") } ec.add, ec.update = true, false if err := ec.validateFlags(); err == nil { t.Error("-vendor-only with -add should fail validation") } ec.noVendor, ec.add = true, false if err := ec.validateFlags(); err == nil { t.Error("-vendor-only with -no-vendor should fail validation") } ec.noVendor = false // Also verify that the plain ensure path takes no args. This is a shady // test, as lots of other things COULD return errors, and we don't check // anything other than the error being non-nil. For now, it works well // because a panic will quickly result if the initial arg length validation // checks are incorrectly handled. if err := ec.runDefault(nil, []string{"foo"}, nil, nil, gps.SolveParameters{}); err == nil { t.Errorf("no args to plain ensure with -vendor-only") } ec.vendorOnly = false if err := ec.runDefault(nil, []string{"foo"}, nil, nil, gps.SolveParameters{}); err == nil { t.Errorf("no args to plain ensure") } } func TestCheckErrors(t *testing.T) { tt := []struct { name string fatal bool pkgOrErrMap map[string]pkgtree.PackageOrErr }{ { name: "noErrors", fatal: false, pkgOrErrMap: map[string]pkgtree.PackageOrErr{ "mypkg": { P: pkgtree.Package{}, }, }, }, { name: "hasErrors", fatal: true, pkgOrErrMap: map[string]pkgtree.PackageOrErr{ "github.com/me/pkg": { Err: &build.NoGoError{}, }, "github.com/someone/pkg": { Err: errors.New("code is busted"), }, }, }, { name: "onlyGoErrors", fatal: false, pkgOrErrMap: map[string]pkgtree.PackageOrErr{ "github.com/me/pkg": { Err: &build.NoGoError{}, }, "github.com/someone/pkg": { P: pkgtree.Package{}, }, }, }, { name: "onlyBuildErrors", fatal: false, pkgOrErrMap: map[string]pkgtree.PackageOrErr{ "github.com/me/pkg": { Err: &build.NoGoError{}, }, "github.com/someone/pkg": { P: pkgtree.Package{}, }, }, }, { name: "allGoErrors", fatal: true, pkgOrErrMap: map[string]pkgtree.PackageOrErr{ "github.com/me/pkg": { Err: &build.NoGoError{}, }, }, }, { name: "allMixedErrors", fatal: true, pkgOrErrMap: map[string]pkgtree.PackageOrErr{ "github.com/me/pkg": { Err: &build.NoGoError{}, }, "github.com/someone/pkg": { Err: errors.New("code is busted"), }, }, }, } for _, tc := range tt { t.Run(tc.name, func(t *testing.T) { fatal, err := checkErrors(tc.pkgOrErrMap) if tc.fatal != fatal { t.Fatalf("expected fatal flag to be %T, got %T", tc.fatal, fatal) } if err == nil && fatal { t.Fatal("unexpected fatal flag value while err is nil") } }) } }
variadico/etercli
vendor/github.com/golang/dep/cmd/dep/ensure_test.go
GO
mit
3,387
'use strict'; module.exports = { set: function (v) { this.setProperty('src', v); }, get: function () { return this.getPropertyValue('src'); }, enumerable: true };
robashton/zombify
src/node_modules/zombie/node_modules/jsdom/node_modules/cssstyle/lib/properties/src.js
JavaScript
mit
211
<?php namespace App\Modules\OAuth\Controllers; use App\Http\Controllers\Controller; use App\Modules\Users\Controllers\UserController; use App\Modules\Users\Models\User; use App\Modules\Users\Supports\MailCheckSupport; use Laravel\Socialite\Facades\Socialite as Socialite; use Illuminate\Http\Request; use Tymon\JWTAuth\JWTAuth; use Tymon\JWTAuth\Exceptions\JWTException; use Tymon\JWTAuth\Exceptions\TokenExpiredException; use Tymon\JWTAuth\Exceptions\TokenInvalidException; /** * Class LoginController * @package App\Modules\OAuth\Controllers */ class LoginController extends Controller { /** * @var JWTAuth */ protected $jwt; /** * @var UserController */ public $userController; /** * LoginController constructor. * @param JWTAuth $jwt * @param UserController $userController */ public function __construct(JWTAuth $jwt, UserController $userController) { $this->jwt = $jwt; $this->userController = $userController; } /** * @param $provider * @return mixed */ public function redirectToProvider($provider) { return Socialite::driver($provider) ->stateless() ->redirect(); } /** * @param $provider * @return \Illuminate\Http\Response|\Laravel\Lumen\Http\ResponseFactory */ public function handleProviderCallback($provider) { try { /** * get user infos with callback provider token */ $user = Socialite::driver($provider) ->stateless() ->user(); /** * check if user email exists in database */ if(!MailCheckSupport::userEmailCheck($user->email)) { /** * create user array infos to save in database */ $userInfos = [ 'name' => $user->name, 'email' => $user->email, 'password' => null, 'remember_token' => str_random(10), 'provider' => $provider, 'provider_id' => $user->id, 'avatar_url' => $user->avatar ]; /** * generate a personal token access from this new user */ $token = $this->userController->createUserFromProvider($userInfos); } else { /** * search existent user in database and generate your personal token access */ $existsUser = User::where('email',$user->email)->first(); $token = $this->jwt->fromUser($existsUser); } if ( env('REDIR_URL') ) { if (env('REDIR_TOKEN_AS_PARAM')) { $redirWithToken = env('REDIR_URL') . "/token:{$token}"; } else { $redirWithToken = env('REDIR_URL') . "?token={$token}"; } return redirect($redirWithToken); } return response()->json(compact('token')); } catch (\Exception $ex) { return response($ex->getMessage(),500); } } /** * @param Request $request * @return \Illuminate\Http\JsonResponse */ public function authenticate(Request $request) { $this->validate($request, [ 'email' => 'required|email|max:255', 'password' => 'required', ]); try { if (! $token = $this->jwt->attempt($request->only('email', 'password'))) { return response()->json(['user_not_found'], 404); } } catch (TokenExpiredException $e) { return response()->json(['token_expired'], $e->getStatusCode()); } catch (TokenInvalidException $e) { return response()->json(['token_invalid'], $e->getStatusCode()); } catch (JWTException $e) { return response()->json(['token_absent' => $e->getMessage()], $e->getStatusCode()); } return response()->json(compact('token')); } }
alissonphp/lumen-api-skeleton
app/Modules/OAuth/Controllers/LoginController.php
PHP
mit
4,190
body { font: 10px sans-serif; } .axis path, .axis line { fill: none; stroke: #000; shape-rendering: crispEdges; } .bar { fill: steelblue; } g.orbit, g.main { cursor: pointer; pointer-events: all; }
maharlikans/titanic_visualization
css/style.css
CSS
mit
215
#!/bin/sh # Compile script to compile against Elysion library # Works for Mac OS X and Linux FPC_BIN=`which fpc` BIN_FOLDER="../bin" LIB_FOLDER="../lib" RES_FOLDER="../resources" SRC_FOLDER="../source" # Info.plist constants BUNDLE_REGION="English" BUNDLE_ICON="logo.icns" BUNDLE_IDENT="com.mycompanyname" BUNDLE_SIGNATURE="????" BUNDLE_VERSION="1.0" SRC_MAIN="main.lpr" BIN_MAIN=`basename ${SRC_MAIN} .lpr` CONFIG_FILE="@config.cfg" EXEC_NAME="myapp" APP_NAME="My App Title" cd ${SRC_FOLDER} if [ -f /System/Library/Frameworks/Cocoa.framework/Cocoa ] then SDL_PATH= SDL_MIXER_PATH= SDL_TTF_PATH= SDL_NET_PATH= DEV_LINK_PPC= DEV_LINK_INTEL32= DEV_LINK_INTEL64= MIN_PPC= MIN_INTEL32= MIN_INTEL64= if [ -d /Library/Frameworks/SDL.framework ] then SDL_PATH="/Library/Frameworks/SDL.framework" elif [ -d ~/Library/Frameworks/SDL.framework ] then SDL_PATH="~/Library/Frameworks/SDL.framework" else echo "SDL not detected. Please check: https://github.com/freezedev/elysion/wiki/Setting-up-our-development-environment" exit 1 fi if [ -d /Library/Frameworks/SDL_mixer.framework ] then SDL_MIXER_PATH="/Library/Frameworks/SDL_mixer.framework" elif [ -d ~/Library/Frameworks/SDL_mixer.framework ] then SDL_MIXER_PATH="~/Library/Frameworks/SDL_mixer.framework" fi if [ -d /Library/Frameworks/SDL_ttf.framework ] then SDL_TTF_PATH="/Library/Frameworks/SDL_ttf.framework" elif [ -d ~/Library/Frameworks/SDL_ttf.framework ] then SDL_TTF_PATH="~/Library/Frameworks/SDL_ttf.framework" fi if [ -d /Library/Frameworks/SDL_net.framework ] then SDL_NET_PATH="/Library/Frameworks/SDL_net.framework" elif [ -d ~/Library/Frameworks/SDL_net.framework ] then SDL_NET_PATH="~/Library/Frameworks/SDL_net.framework" fi if [ [ -d /Developer/SDKs/MacOSX10.7.sdk ] || [ -d /Developer/SDKs/MacOSX10.6.sdk ] || [ -d /Developer/SDKs/MacOSX10.5.sdk ] || [ -d /Developer/SDKs/MacOSX10.4u.sdk ] ] then echo "At least one Mac OS X SDK found" else echo "XCode does not seem be installed. Please install XCode." exit 1 fi if [ -d "/Developer/SDKs/MacOSX10.7.sdk" ] then DEV_LINK_PPC= DEV_LINK_INTEL32="/Developer/SDKs/MacOSX10.7.sdk" DEV_LINK_INTEL64="/Developer/SDKs/MacOSX10.7.sdk" MIN_INTEL32="10.7.0" MIN_INTEL64="10.7.0" fi if [ -d "/Developer/SDKs/MacOSX10.6.sdk" ] then DEV_LINK_PPC= DEV_LINK_INTEL32="/Developer/SDKs/MacOSX10.6.sdk" DEV_LINK_INTEL64="/Developer/SDKs/MacOSX10.6.sdk" MIN_INTEL32="10.6.0" MIN_INTEL64="10.6.0" fi if [ -d "/Developer/SDKs/MacOSX10.5.sdk" ] then DEV_LINK_PPC="/Developer/SDKs/MacOSX10.5.sdk" DEV_LINK_INTEL32="/Developer/SDKs/MacOSX10.5.sdk" MIN_INTEL32="10.5.0" fi if [ -d "/Developer/SDKs/MacOSX10.4u.sdk" ] then DEV_LINK_PPC="/Developer/SDKs/MacOSX10.4u.sdk" DEV_LINK_INTEL32="/Developer/SDKs/MacOSX10.4u.sdk" MIN_PPC="10.4.0" MIN_INTEL32="10.4.0" fi FPC_BIN=`which ppc386` # Compiling Intel x86 binary ${FPC_BIN} ${CONFIG_FILE} -XR${DEV_LINK_INTEL32} -k"-L${LIB_FOLDER}/MacOSX -L/usr/X11R6/lib" ${SRC_MAIN} mv "${BIN_FOLDER}/${BIN_MAIN}" "${BIN_FOLDER}/${BIN_MAIN}-intel_x86" rm ${BIN_FOLDER}/*.o ${BIN_FOLDER}/*.ppu FPC_BIN=`which ppcx64` # Compiling Intel x64 binary ${FPC_BIN} ${CONFIG_FILE} -XR${DEV_LINK_INTEL64} -k"-L${LIB_FOLDER}/MacOSX -L/usr/X11R6/lib" ${SRC_MAIN} mv "${BIN_FOLDER}/${BIN_MAIN}" "${BIN_FOLDER}/${BIN_MAIN}-intel_x64" rm ${BIN_FOLDER}/*.o ${BIN_FOLDER}/*.ppu FPC_BIN=`which ppcppc` # Compiling PowerPC binary ${FPC_BIN} ${CONFIG_FILE} -XR${DEV_LINK_PPC} -k"-L${LIB_FOLDER}/MacOSX -L/usr/X11R6/lib" ${SRC_MAIN} mv "${BIN_FOLDER}/${BIN_MAIN}" "${BIN_FOLDER}/${BIN_MAIN}-ppc" rm ${BIN_FOLDER}/*.o ${BIN_FOLDER}/*.ppu # Creating universal binary # Strip executables if [ -f "${BIN_FOLDER}/${BIN_MAIN}-intel_x86" ] then strip "${BIN_FOLDER}/${BIN_MAIN}-intel_x86" fi if [ -f "${BIN_FOLDER}/${BIN_MAIN}-intel_x64" ] then strip "${BIN_FOLDER}/${BIN_MAIN}-intel_x64" fi if [ -f "${BIN_FOLDER}/${BIN_MAIN}-ppc" ] then strip "${BIN_FOLDER}/${BIN_MAIN}-ppc" fi # All three compilers are here... yeah, universal binary de luxe (Intel 32, Intel 64 + PowerPC 32) if [ -f "${BIN_FOLDER}/${BIN_MAIN}-intel_x86" ] && [ -f "${BIN_FOLDER}/${BIN_MAIN}-intel_x64" ] && [ -f "${BIN_FOLDER}/${BIN_MAIN}-ppc" ] then lipo -create "${BIN_FOLDER}/${BIN_MAIN}-intel_x86" "${BIN_FOLDER}/${BIN_MAIN}-intel_x64" "${BIN_FOLDER}/${BIN_MAIN}-ppc" -output "${BIN_FOLDER}/${EXEC_NAME}" rm -rf "${BIN_FOLDER}/${BIN_MAIN}-intel_x86" rm -rf "${BIN_FOLDER}/${BIN_MAIN}-intel_x64" rm -rf "${BIN_FOLDER}/${BIN_MAIN}-ppc" # PowerPC 32 + Intel 32 elif [ -f "${BIN_FOLDER}/${BIN_MAIN}-intel_x86" ] && [ -f "${BIN_FOLDER}/${BIN_MAIN}-ppc" ] then lipo -create "${BIN_FOLDER}/${BIN_MAIN}-intel_x86" "${BIN_FOLDER}/${BIN_MAIN}-ppc" -output "${BIN_FOLDER}/${EXEC_NAME}" rm -rf "${BIN_FOLDER}/${BIN_MAIN}-intel_x86" rm -rf "${BIN_FOLDER}/${BIN_MAIN}-ppc" # Intel 32 + Intel 64 elif [ -f "${BIN_FOLDER}/${BIN_MAIN}-intel_x86" ] && [ -f "${BIN_FOLDER}/${BIN_MAIN}-intel_x64" ] then lipo -create "${BIN_FOLDER}/${BIN_MAIN}-intel_x86" "${BIN_FOLDER}/${BIN_MAIN}-intel_x64" -output "${BIN_FOLDER}/${EXEC_NAME}" rm -rf "${BIN_FOLDER}/${BIN_MAIN}-intel_x86" rm -rf "${BIN_FOLDER}/${BIN_MAIN}-intel_x64" else strip "${BIN_FOLDER}/${BIN_MAIN}-intel_x86" mv "${BIN_FOLDER}/${BIN_MAIN}-intel_x86" "${BIN_FOLDER}/${EXEC_NAME}" fi if [ -d "${BIN_FOLDER}/${APP_NAME}.app" ] then echo " ... Removing old application" rm -rf "${BIN_FOLDER}/${APP_NAME}.app" fi echo " ... Creating Application Bundle" mkdir "${BIN_FOLDER}/${APP_NAME}.app" mkdir "${BIN_FOLDER}/${APP_NAME}.app/Contents" mkdir "${BIN_FOLDER}/${APP_NAME}.app/Contents/MacOS" mkdir "${BIN_FOLDER}/${APP_NAME}.app/Contents/Resources" mkdir "${BIN_FOLDER}/${APP_NAME}.app/Contents/Frameworks" cp -R "${RES_FOLDER}/" "${BIN_FOLDER}/${APP_NAME}.app/Contents/Resources/" # Copy frameworks from System cp -R "${SDL_PATH}" "${BIN_FOLDER}/${APP_NAME}.app/Contents/Frameworks/" cp -R "${SDL_MIXER_PATH}" "${BIN_FOLDER}/${APP_NAME}.app/Contents/Frameworks/" cp -R "${SDL_TTF_PATH}" "${BIN_FOLDER}/${APP_NAME}.app/Contents/Frameworks/" cp -R "${SDL_NET_PATH}" "${BIN_FOLDER}/${APP_NAME}.app/Contents/Frameworks/" mv "${BIN_FOLDER}/${EXEC_NAME}" "${BIN_FOLDER}/${APP_NAME}.app/Contents/MacOS/" echo "<?xml version='1.0' encoding='UTF-8'?>\ <!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\ <plist version=\"1.0\">\ <dict>\ <key>CFBundleDevelopmentRegion</key>\ <string>${BUNDLE_REGION}</string>\ <key>CFBundleExecutable</key>\ <string>${EXEC_NAME}</string>\ <key>CFBundleIconFile</key>\ <string>${BUNDLE_ICON}</string>\ <key>CFBundleIdentifier</key>\ <string>${BUNDLE_IDENT}</string>\ <key>CFBundleInfoDictionaryVersion</key>\ <string>6.0</string>\ <key>CFBundleName</key>\ <string>${APP_NAME}</string>\ <key>CFBundlePackageType</key>\ <string>APPL</string>\ <key>CFBundleSignature</key>\ <string>${BUNDLE_SIGNATURE}</string>\ <key>CFBundleVersion</key>\ <string>${BUNDLE_VERSION}</string>\ <key>CSResourcesFileMapped</key>\ <true/>\ <key>LSMinimumSystemVersionByArchitecture</key>\ <dict>\ <key>x86_64</key>\ <string>${MIN_INTEL64}</string>\ <key>i386</key>\ <string>${MIN_INTEL32}</string>\ <key>ppc</key>\ <string>${MIN_PPC}</string>\ </dict>\ </dict>\ </plist>" >> "${BIN_FOLDER}/${APP_NAME}.app/Contents/Info.plist" echo "APPL${BUNDLE_SIGNATURE}" >> "${BIN_FOLDER}/${APP_NAME}.app/Contents/PkgInfo" else ${FPC_BIN} ${CONFIG_FILE} ${SRC_MAIN} if [ -f "${BIN_FOLDER}/${BIN_MAIN}" ] then mv "${BIN_FOLDER}/${BIN_MAIN}" "${BIN_FOLDER}/${EXEC_NAME}" fi fi
freezedev/survival-guide-for-pirates
scripts/build.sh
Shell
mit
8,208
// Copyright (c) 2011-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <QApplication> #include "bitcoingui.h" #include "clientmodel.h" #include "walletmodel.h" #include "optionsmodel.h" #include "guiutil.h" #include "guiconstants.h" #include "init.h" #include "util.h" #include "ui_interface.h" #include "paymentserver.h" #include "splashscreen.h" #include <QMessageBox> #if QT_VERSION < 0x050000 #include <QTextCodec> #endif #include <QLocale> #include <QTimer> #include <QTranslator> #include <QLibraryInfo> #ifdef Q_OS_MAC #include "macdockiconhandler.h" #endif #if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED) #define _BITCOIN_QT_PLUGINS_INCLUDED #define __INSURE__ #include <QtPlugin> Q_IMPORT_PLUGIN(qcncodecs) Q_IMPORT_PLUGIN(qjpcodecs) Q_IMPORT_PLUGIN(qtwcodecs) Q_IMPORT_PLUGIN(qkrcodecs) Q_IMPORT_PLUGIN(qtaccessiblewidgets) #endif // Declare meta types used for QMetaObject::invokeMethod Q_DECLARE_METATYPE(bool*) // Need a global reference for the notifications to find the GUI static BitcoinGUI *guiref; static SplashScreen *splashref; static bool ThreadSafeMessageBox(const std::string& message, const std::string& caption, unsigned int style) { // Message from network thread if(guiref) { bool modal = (style & CClientUIInterface::MODAL); bool ret = false; // In case of modal message, use blocking connection to wait for user to click a button QMetaObject::invokeMethod(guiref, "message", modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(caption)), Q_ARG(QString, QString::fromStdString(message)), Q_ARG(unsigned int, style), Q_ARG(bool*, &ret)); return ret; } else { printf("%s: %s\n", caption.c_str(), message.c_str()); fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str()); return false; } } static bool ThreadSafeAskFee(int64 nFeeRequired) { if(!guiref) return false; if(nFeeRequired < CTransaction::nMinTxFee || nFeeRequired <= nTransactionFee || fDaemon) return true; bool payFee = false; QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(), Q_ARG(qint64, nFeeRequired), Q_ARG(bool*, &payFee)); return payFee; } static void InitMessage(const std::string &message) { if(splashref) { splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(55,55,55)); qApp->processEvents(); } printf("init message: %s\n", message.c_str()); } /* Translate string to current locale using Qt. */ static std::string Translate(const char* psz) { return QCoreApplication::translate("bitcoin-core", psz).toStdString(); } /* Handle runaway exceptions. Shows a message box with the problem and quits the program. */ static void handleRunawayException(std::exception *e) { PrintExceptionContinue(e, "Runaway exception"); QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. Amerios can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning)); exit(1); } #ifndef BITCOIN_QT_TEST int main(int argc, char *argv[]) { // Command-line options take precedence: ParseParameters(argc, argv); #if QT_VERSION < 0x050000 // Internal string conversion is all UTF-8 QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8")); QTextCodec::setCodecForCStrings(QTextCodec::codecForTr()); #endif Q_INIT_RESOURCE(bitcoin); QApplication app(argc, argv); // Register meta types used for QMetaObject::invokeMethod qRegisterMetaType< bool* >(); // Do this early as we don't want to bother initializing if we are just calling IPC // ... but do it after creating app, so QCoreApplication::arguments is initialized: if (PaymentServer::ipcSendCommandLine()) exit(0); PaymentServer* paymentServer = new PaymentServer(&app); // Install global event filter that makes sure that long tooltips can be word-wrapped app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app)); // ... then bitcoin.conf: if (!boost::filesystem::is_directory(GetDataDir(false))) { // This message can not be translated, as translation is not initialized yet // (which not yet possible because lang=XX can be overridden in bitcoin.conf in the data directory) QMessageBox::critical(0, "Amerios", QString("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"]))); return 1; } ReadConfigFile(mapArgs, mapMultiArgs); // Application identification (must be set before OptionsModel is initialized, // as it is used to locate QSettings) QApplication::setOrganizationName("Amerios"); QApplication::setOrganizationDomain("amerios.org"); if(GetBoolArg("-testnet")) // Separate UI settings for testnet QApplication::setApplicationName("Amerios-Qt-testnet"); else QApplication::setApplicationName("Amerios-Qt"); // ... then GUI settings: OptionsModel optionsModel; // Get desired locale (e.g. "de_DE") from command line or use system locale QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString())); QString lang = lang_territory; // Convert to "de" only by truncating "_DE" lang.truncate(lang_territory.lastIndexOf('_')); QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator; // Load language files for configured locale: // - First load the translator for the base language, without territory // - Then load the more specific locale translator // Load e.g. qt_de.qm if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) app.installTranslator(&qtTranslatorBase); // Load e.g. qt_de_DE.qm if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) app.installTranslator(&qtTranslator); // Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc) if (translatorBase.load(lang, ":/translations/")) app.installTranslator(&translatorBase); // Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc) if (translator.load(lang_territory, ":/translations/")) app.installTranslator(&translator); // Subscribe to global signals from core uiInterface.ThreadSafeMessageBox.connect(ThreadSafeMessageBox); uiInterface.ThreadSafeAskFee.connect(ThreadSafeAskFee); uiInterface.InitMessage.connect(InitMessage); uiInterface.Translate.connect(Translate); // Show help message immediately after parsing command-line options (for "-lang") and setting locale, // but before showing splash screen. if (mapArgs.count("-?") || mapArgs.count("--help")) { GUIUtil::HelpMessageBox help; help.showOrPrint(); return 1; } #ifdef Q_OS_MAC // on mac, also change the icon now because it would look strange to have a testnet splash (green) and a std app icon (orange) if(GetBoolArg("-testnet")) { MacDockIconHandler::instance()->setIcon(QIcon(":icons/bitcoin_testnet")); } #endif SplashScreen splash(QPixmap(), 0); if (GetBoolArg("-splash", true) && !GetBoolArg("-min")) { splash.show(); splash.setAutoFillBackground(true); splashref = &splash; } app.processEvents(); app.setQuitOnLastWindowClosed(false); try { #ifndef Q_OS_MAC // Regenerate startup link, to fix links to old versions // OSX: makes no sense on mac and might also scan/mount external (and sleeping) volumes (can take up some secs) if (GUIUtil::GetStartOnSystemStartup()) GUIUtil::SetStartOnSystemStartup(true); #endif boost::thread_group threadGroup; BitcoinGUI window; guiref = &window; QTimer* pollShutdownTimer = new QTimer(guiref); QObject::connect(pollShutdownTimer, SIGNAL(timeout()), guiref, SLOT(detectShutdown())); pollShutdownTimer->start(200); if(AppInit2(threadGroup)) { { // Put this in a block, so that the Model objects are cleaned up before // calling Shutdown(). optionsModel.Upgrade(); // Must be done after AppInit2 if (splashref) splash.finish(&window); ClientModel clientModel(&optionsModel); WalletModel *walletModel = 0; if(pwalletMain) walletModel = new WalletModel(pwalletMain, &optionsModel); window.setClientModel(&clientModel); if(walletModel) { window.addWallet("~Default", walletModel); window.setCurrentWallet("~Default"); } // If -min option passed, start window minimized. if(GetBoolArg("-min")) { window.showMinimized(); } else { window.show(); } // Now that initialization/startup is done, process any command-line // bitcoin: URIs QObject::connect(paymentServer, SIGNAL(receivedURI(QString)), &window, SLOT(handleURI(QString))); QTimer::singleShot(100, paymentServer, SLOT(uiReady())); app.exec(); window.hide(); window.setClientModel(0); window.removeAllWallets(); guiref = 0; delete walletModel; } // Shutdown the core and its threads, but don't exit Bitcoin-Qt here threadGroup.interrupt_all(); threadGroup.join_all(); Shutdown(); } else { threadGroup.interrupt_all(); threadGroup.join_all(); Shutdown(); return 1; } } catch (std::exception& e) { handleRunawayException(&e); } catch (...) { handleRunawayException(NULL); } return 0; } #endif // BITCOIN_QT_TEST
codecvlc/amerios
src/qt/bitcoin.cpp
C++
mit
10,776
.letra-ciudad { color: #fff; font-weight: 100; cursor: pointer; font-family: 'Moonbeam' !important; font-size: 43px; padding-left: 15px; } .letra-placer { color: #fff; font-weight: 100; cursor: pointer; font-size: 44px; font-family: 'QaskinBlack'; } #cabecera_sup_buscar { text-align: center; } #header { z-index: 1000; } #cabecera .cabecera_sup { height: 50px; position: relative; background: linear-gradient(to bottom, #da0000, #a60000); }
crianbluff-programming/ciudadplacer
dist/css/header.css
CSS
mit
478
#3.4 Chrome Dev Tools 1. Change in Colors ![Change in Colors](imgs/1-Colours.png "Colors") 2. Column ![Column](imgs/2-column.png "Column") 3. Row ![Row](imgs/3-row.png "Row") 4. Make Equidistant ![Equidistant](imgs/4-equidistant.png "Equidistant") 5. Squares ![Squares](imgs/5-squares.png "Square") 6. Footer ![Footer](imgs/6-footer.png "Footer") 7. Header ![Header](imgs/7-header.png "Header") 8. Sidebar ![Sidebar](imgs/8-sidebar.png "sidebar") 9. Get Creative ![Creative](imgs/9-creative.png "creative") * **Reflection** * **How can you use Chrome's DevTools inspector to help you format or position elements?** Chrome DevTools allows you to update the HTML and CSS on the fly with real time updates, meaning you can see the results instantly once the change has been made. You can play around with the values to position the elements on the page to see how it would appear on the page. * **How can you resize elements on the DOM using CSS?** You can resize the elements on the DOM by setting the property of width and height. You select any of the elements whether they are tags, classes, or ids. * **What are the differences between Absolute, Fixed, Static, and Relative Positioning? Which did you find easiest to use? Which was most difficult?** Absolute positioning is positioning of elements referenced to the parent node that the node being styled is contained in. Absolute positioning also is not affected and does not affect other elements in the same node, meaning other elements will either appear over top of or in behind the other elements that are in the same container. Fixed position is when elements are fixed to the viewport of the browser. When a user scrolls down the page the element remains in the view constantly. Again the elements that are fixed are not affected by the other elements on the page. Static position is the default position used by the browsers. Elements that are set to static flow in accordance to its position in the structure of the HTML tree. Relative positioning is the position of an element relative to where it would have been in the normal flow of elements. * **What are the differences between Margin, Border, and Padding?** The margin is the space between the outside of the element the margin is being applied to and the element that it is contained within. The border is the outer edge of the element, inside of the margin. The padding is the space between the border and the content contained within the element. * **What was your impression of this challenge overall? (love, hate, and why?)** My impression of this challenge was that it was pretty easy but good to know. Being able to make quick changes on the fly and seeing the results is much quicker than editing a file in the text editor, committing the changes, pushing them, going to the browser and refreshing the view. You are able to iterate over your ideas much quicker.
peterwiebe/phase-0
week-3/chrome-devtools/positioning-reflection.md
Markdown
mit
2,911
# redmine project summary Now work in progress.
momibun926/redmine_project_summary
README.md
Markdown
mit
48
Android ================================================================================ Requirements: Android SDK (version 12 or later) http://developer.android.com/sdk/index.html Android NDK r7 or later http://developer.android.com/tools/sdk/ndk/index.html Minimum API level supported by SDL: 10 (Android 2.3.3) Joystick support is available for API level >=12 devices. ================================================================================ How the port works ================================================================================ - Android applications are Java-based, optionally with parts written in C - As SDL apps are C-based, we use a small Java shim that uses JNI to talk to the SDL library - This means that your application C code must be placed inside an Android Java project, along with some C support code that communicates with Java - This eventually produces a standard Android .apk package The Android Java code implements an "Activity" and can be found in: android-project/src/org/libsdl/app/SDLActivity.java The Java code loads your game code, the SDL shared library, and dispatches to native functions implemented in the SDL library: src/core/android/SDL_android.c Your project must include some glue code that starts your main() routine: src/main/android/SDL_android_main.c ================================================================================ Building an app ================================================================================ For simple projects you can use the script located at build-scripts/androidbuild.sh There's two ways of using it: androidbuild.sh com.yourcompany.yourapp < sources.list androidbuild.sh com.yourcompany.yourapp source1.c source2.c ...sourceN.c sources.list should be a text file with a source file name in each line Filenames should be specified relative to the current directory, for example if you are in the build-scripts directory and want to create the testgles.c test, you'll run: ./androidbuild.sh org.libsdl.testgles ../test/testgles.c One limitation of this script is that all sources provided will be aggregated into a single directory, thus all your source files should have a unique name. Once the project is complete the script will tell you where the debug APK is located. If you want to create a signed release APK, you can use the project created by this utility to generate it. Finally, a word of caution: re running androidbuild.sh wipes any changes you may have done in the build directory for the app! For more complex projects, follow these instructions: 1. Copy the android-project directory wherever you want to keep your projects and rename it to the name of your project. 2. Move or symlink this SDL directory into the "<project>/jni" directory 3. Edit "<project>/jni/src/Android.mk" to include your source files 4. Run 'ndk-build' (a script provided by the NDK). This compiles the C source If you want to use the Eclipse IDE, skip to the Eclipse section below. 5. Create "<project>/local.properties" and use that to point to the Android SDK directory, by writing a line with the following form: sdk.dir=PATH_TO_ANDROID_SDK 6. Run 'ant debug' in android/project. This compiles the .java and eventually creates a .apk with the native code embedded 7. 'ant debug install' will push the apk to the device or emulator (if connected) Here's an explanation of the files in the Android project, so you can customize them: android-project/ AndroidManifest.xml - package manifest. Among others, it contains the class name of the main Activity and the package name of the application. build.properties - empty build.xml - build description file, used by ant. The actual application name is specified here. default.properties - holds the target ABI for the application, android-10 and up project.properties - holds the target ABI for the application, android-10 and up local.properties - holds the SDK path, you should change this to the path to your SDK jni/ - directory holding native code jni/Android.mk - Android makefile that can call recursively the Android.mk files in all subdirectories jni/SDL/ - (symlink to) directory holding the SDL library files jni/SDL/Android.mk - Android makefile for creating the SDL shared library jni/src/ - directory holding your C/C++ source jni/src/Android.mk - Android makefile that you should customize to include your source code and any library references res/ - directory holding resources for your application res/drawable-* - directories holding icons for different phone hardware. Could be one dir called "drawable". res/layout/main.xml - Usually contains a file main.xml, which declares the screen layout. We don't need it because we use the SDL video output. res/values/strings.xml - strings used in your application, including the application name shown on the phone. src/org/libsdl/app/SDLActivity.java - the Java class handling the initialization and binding to SDL. Be very careful changing this, as the SDL library relies on this implementation. ================================================================================ Build an app with static linking of libSDL ================================================================================ This build uses the Android NDK module system. Instructions: 1. Copy the android-project directory wherever you want to keep your projects and rename it to the name of your project. 2. Rename "<project>/jni/src/Android_static.mk" to "<project>/jni/src/Android.mk" (overwrite the existing one) 3. Edit "<project>/jni/src/Android.mk" to include your source files 4. create and export an environment variable named NDK_MODULE_PATH that points to the parent directory of this SDL directory. e.g.: export NDK_MODULE_PATH="$PWD"/.. 5. Edit "<project>/src/org/libsdl/app/SDLActivity.java" and remove the call to System.loadLibrary("SDL2"). 6. Run 'ndk-build' (a script provided by the NDK). This compiles the C source ================================================================================ Customizing your application name ================================================================================ To customize your application name, edit AndroidManifest.xml and replace "org.libsdl.app" with an identifier for your product package. Then create a Java class extending SDLActivity and place it in a directory under src matching your package, e.g. src/com/gamemaker/game/MyGame.java Here's an example of a minimal class file: --- MyGame.java -------------------------- package com.gamemaker.game; import org.libsdl.app.SDLActivity; /** * A sample wrapper class that just calls SDLActivity */ public class MyGame extends SDLActivity { } ------------------------------------------ Then replace "SDLActivity" in AndroidManifest.xml with the name of your class, .e.g. "MyGame" ================================================================================ Customizing your application icon ================================================================================ Conceptually changing your icon is just replacing the "ic_launcher.png" files in the drawable directories under the res directory. There are four directories for different screen sizes. These can be replaced with one dir called "drawable", containing an icon file "ic_launcher.png" with dimensions 48x48 or 72x72. You may need to change the name of your icon in AndroidManifest.xml to match this icon filename. ================================================================================ Loading assets ================================================================================ Any files you put in the "assets" directory of your android-project directory will get bundled into the application package and you can load them using the standard functions in SDL_rwops.h. There are also a few Android specific functions that allow you to get other useful paths for saving and loading data: * SDL_AndroidGetInternalStoragePath() * SDL_AndroidGetExternalStorageState() * SDL_AndroidGetExternalStoragePath() See SDL_system.h for more details on these functions. The asset packaging system will, by default, compress certain file extensions. SDL includes two asset file access mechanisms, the preferred one is the so called "File Descriptor" method, which is faster and doesn't involve the Dalvik GC, but given this method does not work on compressed assets, there is also the "Input Stream" method, which is automatically used as a fall back by SDL. You may want to keep this fact in mind when building your APK, specially when large files are involved. For more information on which extensions get compressed by default and how to disable this behaviour, see for example: http://ponystyle.com/blog/2010/03/26/dealing-with-asset-compression-in-android-apps/ ================================================================================ Pause / Resume behaviour ================================================================================ If SDL is compiled with SDL_ANDROID_BLOCK_ON_PAUSE defined (the default), the event loop will block itself when the app is paused (ie, when the user returns to the main Android dashboard). Blocking is better in terms of battery use, and it allows your app to spring back to life instantaneously after resume (versus polling for a resume message). Upon resume, SDL will attempt to restore the GL context automatically. In modern devices (Android 3.0 and up) this will most likely succeed and your app can continue to operate as it was. However, there's a chance (on older hardware, or on systems under heavy load), where the GL context can not be restored. In that case you have to listen for a specific message, (which is not yet implemented!) and restore your textures manually or quit the app (which is actually the kind of behaviour you'll see under iOS, if the OS can not restore your GL context it will just kill your app) ================================================================================ Threads and the Java VM ================================================================================ For a quick tour on how Linux native threads interoperate with the Java VM, take a look here: http://developer.android.com/guide/practices/jni.html If you want to use threads in your SDL app, it's strongly recommended that you do so by creating them using SDL functions. This way, the required attach/detach handling is managed by SDL automagically. If you have threads created by other means and they make calls to SDL functions, make sure that you call Android_JNI_SetupThread() before doing anything else otherwise SDL will attach your thread automatically anyway (when you make an SDL call), but it'll never detach it. ================================================================================ Using STL ================================================================================ You can use STL in your project by creating an Application.mk file in the jni folder and adding the following line: APP_STL := stlport_static For more information check out CPLUSPLUS-SUPPORT.html in the NDK documentation. ================================================================================ Additional documentation ================================================================================ The documentation in the NDK docs directory is very helpful in understanding the build process and how to work with native code on the Android platform. The best place to start is with docs/OVERVIEW.TXT ================================================================================ Using Eclipse ================================================================================ First make sure that you've installed Eclipse and the Android extensions as described here: http://developer.android.com/tools/sdk/eclipse-adt.html Once you've copied the SDL android project and customized it, you can create an Eclipse project from it: * File -> New -> Other * Select the Android -> Android Project wizard and click Next * Enter the name you'd like your project to have * Select "Create project from existing source" and browse for your project directory * Make sure the Build Target is set to Android 3.1 (API 12) * Click Finish ================================================================================ Using the emulator ================================================================================ There are some good tips and tricks for getting the most out of the emulator here: http://developer.android.com/tools/devices/emulator.html Especially useful is the info on setting up OpenGL ES 2.0 emulation. Notice that this software emulator is incredibly slow and needs a lot of disk space. Using a real device works better. ================================================================================ Troubleshooting ================================================================================ You can create and run an emulator from the Eclipse IDE: * Window -> Android SDK and AVD Manager You can see if adb can see any devices with the following command: adb devices You can see the output of log messages on the default device with: adb logcat You can push files to the device with: adb push local_file remote_path_and_file You can push files to the SD Card at /sdcard, for example: adb push moose.dat /sdcard/moose.dat You can see the files on the SD card with a shell command: adb shell ls /sdcard/ You can start a command shell on the default device with: adb shell You can remove the library files of your project (and not the SDL lib files) with: ndk-build clean You can do a build with the following command: ndk-build You can see the complete command line that ndk-build is using by passing V=1 on the command line: ndk-build V=1 If your application crashes in native code, you can use addr2line to convert the addresses in the stack trace to lines in your code. For example, if your crash looks like this: I/DEBUG ( 31): signal 11 (SIGSEGV), code 2 (SEGV_ACCERR), fault addr 400085d0 I/DEBUG ( 31): r0 00000000 r1 00001000 r2 00000003 r3 400085d4 I/DEBUG ( 31): r4 400085d0 r5 40008000 r6 afd41504 r7 436c6a7c I/DEBUG ( 31): r8 436c6b30 r9 435c6fb0 10 435c6f9c fp 4168d82c I/DEBUG ( 31): ip 8346aff0 sp 436c6a60 lr afd1c8ff pc afd1c902 cpsr 60000030 I/DEBUG ( 31): #00 pc 0001c902 /system/lib/libc.so I/DEBUG ( 31): #01 pc 0001ccf6 /system/lib/libc.so I/DEBUG ( 31): #02 pc 000014bc /data/data/org.libsdl.app/lib/libmain.so I/DEBUG ( 31): #03 pc 00001506 /data/data/org.libsdl.app/lib/libmain.so You can see that there's a crash in the C library being called from the main code. I run addr2line with the debug version of my code: arm-eabi-addr2line -C -f -e obj/local/armeabi/libmain.so and then paste in the number after "pc" in the call stack, from the line that I care about: 000014bc I get output from addr2line showing that it's in the quit function, in testspriteminimal.c, on line 23. You can add logging to your code to help show what's happening: #include <android/log.h> __android_log_print(ANDROID_LOG_INFO, "foo", "Something happened! x = %d", x); If you need to build without optimization turned on, you can create a file called "Application.mk" in the jni directory, with the following line in it: APP_OPTIM := debug ================================================================================ Memory debugging ================================================================================ The best (and slowest) way to debug memory issues on Android is valgrind. Valgrind has support for Android out of the box, just grab code using: svn co svn://svn.valgrind.org/valgrind/trunk valgrind ... and follow the instructions in the file README.android to build it. One thing I needed to do on Mac OS X was change the path to the toolchain, and add ranlib to the environment variables: export RANLIB=$NDKROOT/toolchains/arm-linux-androideabi-4.4.3/prebuilt/darwin-x86/bin/arm-linux-androideabi-ranlib Once valgrind is built, you can create a wrapper script to launch your application with it, changing org.libsdl.app to your package identifier: --- start_valgrind_app ------------------- #!/system/bin/sh export TMPDIR=/data/data/org.libsdl.app exec /data/local/Inst/bin/valgrind --log-file=/sdcard/valgrind.log --error-limit=no $* ------------------------------------------ Then push it to the device: adb push start_valgrind_app /data/local and make it executable: adb shell chmod 755 /data/local/start_valgrind_app and tell Android to use the script to launch your application: adb shell setprop wrap.org.libsdl.app "logwrapper /data/local/start_valgrind_app" If the setprop command says "could not set property", it's likely that your package name is too long and you should make it shorter by changing AndroidManifest.xml and the path to your class file in android-project/src You can then launch your application normally and waaaaaaaiiittt for it. You can monitor the startup process with the logcat command above, and when it's done (or even while it's running) you can grab the valgrind output file: adb pull /sdcard/valgrind.log When you're done instrumenting with valgrind, you can disable the wrapper: adb shell setprop wrap.org.libsdl.app "" ================================================================================ Graphics debugging ================================================================================ If you are developing on a compatible Tegra-based tablet, NVidia provides Tegra Graphics Debugger at their website. Because SDL2 dynamically loads EGL and GLES libraries, you must follow their instructions for installing the interposer library on a rooted device. The non-rooted instructions are not compatible with applications that use SDL2 for video. The Tegra Graphics Debugger is available from NVidia here: https://developer.nvidia.com/tegra-graphics-debugger ================================================================================ Why is API level 10 the minimum required? ================================================================================ API level 10 is the minimum required level at runtime (that is, on the device) because SDL requires some functionality for running not available on older devices. Since the incorporation of joystick support into SDL, the minimum SDK required to *build* SDL is version 12. Devices running API levels 10-11 are still supported, only with the joystick functionality disabled. Support for native OpenGL ES and ES2 applications was introduced in the NDK for API level 4 and 8. EGL was made a stable API in the NDK for API level 9, which has since then been obsoleted, with the recommendation to developers to bump the required API level to 10. As of this writing, according to http://developer.android.com/about/dashboards/index.html about 90% of the Android devices accessing Google Play support API level 10 or higher (March 2013). ================================================================================ A note regarding the use of the "dirty rectangles" rendering technique ================================================================================ If your app uses a variation of the "dirty rectangles" rendering technique, where you only update a portion of the screen on each frame, you may notice a variety of visual glitches on Android, that are not present on other platforms. This is caused by SDL's use of EGL as the support system to handle OpenGL ES/ES2 contexts, in particular the use of the eglSwapBuffers function. As stated in the documentation for the function "The contents of ancillary buffers are always undefined after calling eglSwapBuffers". Setting the EGL_SWAP_BEHAVIOR attribute of the surface to EGL_BUFFER_PRESERVED is not possible for SDL as it requires EGL 1.4, available only on the API level 17+, so the only workaround available on this platform is to redraw the entire screen each frame. Reference: http://www.khronos.org/registry/egl/specs/EGLTechNote0001.html ================================================================================ Known issues ================================================================================ - The number of buttons reported for each joystick is hardcoded to be 36, which is the current maximum number of buttons Android can report.
incinirate/Riko4
libs/include/SDL2/docs/README-android.md
Markdown
mit
21,191
#!/usr/bin/env python """ Manage and display experimental results. """ __license__ = 'MIT License <http://www.opensource.org/licenses/mit-license.php>' __author__ = 'Lucas Theis <lucas@theis.io>' __docformat__ = 'epytext' __version__ = '0.4.3' import sys import os import numpy import random import scipy import socket sys.path.append('./code') from argparse import ArgumentParser from pickle import Unpickler, dump from subprocess import Popen, PIPE from os import path from warnings import warn from time import time, strftime, localtime from numpy import ceil, argsort from numpy.random import rand, randint from distutils.version import StrictVersion from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler from httplib import HTTPConnection from getopt import getopt class Experiment: """ @type time: float @ivar time: time at initialization of experiment @type duration: float @ivar duration: time in seconds between initialization and saving @type script: string @ivar script: stores the content of the main Python script @type platform: string @ivar platform: information about operating system @type processors: string @ivar processors: some information about the processors @type environ: string @ivar environ: environment variables at point of initialization @type hostname: string @ivar hostname: hostname of server running the experiment @type cwd: string @ivar cwd: working directory at execution time @type comment: string @ivar comment: a comment describing the experiment @type results: dictionary @ivar results: container to store experimental results @type commit: string @ivar commit: git commit hash @type modified: boolean @ivar modified: indicates uncommited changes @type filename: string @ivar filename: path to stored results @type seed: int @ivar seed: random seed used through the experiment @type versions: dictionary @ivar versions: versions of Python, numpy and scipy """ def __str__(self): """ Summarize information about the experiment. @rtype: string @return: summary of the experiment """ strl = [] # date and duration of experiment strl.append(strftime('date \t\t %a, %d %b %Y %H:%M:%S', localtime(self.time))) strl.append('duration \t ' + str(int(self.duration)) + 's') strl.append('hostname \t ' + self.hostname) # commit hash if self.commit: if self.modified: strl.append('commit \t\t ' + self.commit + ' (modified)') else: strl.append('commit \t\t ' + self.commit) # results strl.append('results \t {' + ', '.join(map(str, self.results.keys())) + '}') # comment if self.comment: strl.append('\n' + self.comment) return '\n'.join(strl) def __del__(self): self.status(None) def __init__(self, filename='', comment='', seed=None, server=None, port=8000): """ If the filename is given and points to an existing experiment, load it. Otherwise store the current timestamp and try to get commit information from the repository in the current directory. @type filename: string @param filename: path to where the experiment will be stored @type comment: string @param comment: a comment describing the experiment @type seed: integer @param seed: random seed used in the experiment """ self.id = 0 self.time = time() self.comment = comment self.filename = filename self.results = {} self.seed = seed self.script = '' self.cwd = '' self.platform = '' self.processors = '' self.environ = '' self.duration = 0 self.versions = {} self.server = '' if self.seed is None: self.seed = int((time() + 1e6 * rand()) * 1e3) % 4294967295 # set random seed random.seed(self.seed) numpy.random.seed(self.seed) if self.filename: # load given experiment self.load() else: # identifies the experiment self.id = randint(1E8) # check if a comment was passed via the command line parser = ArgumentParser(add_help=False) parser.add_argument('--comment') optlist, argv = parser.parse_known_args(sys.argv[1:]) optlist = vars(optlist) # remove comment command line argument from argument list sys.argv[1:] = argv # comment given as command line argument self.comment = optlist.get('comment', '') # get OS information self.platform = sys.platform # arguments to the program self.argv = sys.argv self.script_path = sys.argv[0] try: with open(sys.argv[0]) as handle: # store python script self.script = handle.read() except: warn('Unable to read Python script.') # environment variables self.environ = os.environ self.cwd = os.getcwd() self.hostname = socket.gethostname() # store some information about the processor(s) if self.platform == 'linux2': cmd = 'egrep "processor|model name|cpu MHz|cache size" /proc/cpuinfo' with os.popen(cmd) as handle: self.processors = handle.read() elif self.platform == 'darwin': cmd = 'system_profiler SPHardwareDataType | egrep "Processor|Cores|L2|Bus"' with os.popen(cmd) as handle: self.processors = handle.read() # version information self.versions['python'] = sys.version self.versions['numpy'] = numpy.__version__ self.versions['scipy'] = scipy.__version__ # store information about git repository if path.isdir('.git'): # get commit hash pr1 = Popen(['git', 'log', '-1'], stdout=PIPE) pr2 = Popen(['head', '-1'], stdin=pr1.stdout, stdout=PIPE) pr3 = Popen(['cut', '-d', ' ', '-f', '2'], stdin=pr2.stdout, stdout=PIPE) self.commit = pr3.communicate()[0][:-1] # check if project contains uncommitted changes pr1 = Popen(['git', 'status', '--porcelain'], stdout=PIPE) pr2 = Popen(['egrep', '^.M'], stdin=pr1.stdout, stdout=PIPE) self.modified = pr2.communicate()[0] if self.modified: warn('Uncommitted changes.') else: # no git repository self.commit = None self.modified = False # server managing experiments self.server = server self.port = port self.status('running') def status(self, status, **kwargs): if self.server: try: conn = HTTPConnection(self.server, self.port) conn.request('GET', '/version/') resp = conn.getresponse() if not resp.read().startswith('Experiment'): raise RuntimeError() HTTPConnection(self.server, self.port).request('POST', '', str(dict({ 'id': self.id, 'version': __version__, 'status': status, 'hostname': self.hostname, 'cwd': self.cwd, 'script_path': self.script_path, 'script': self.script, 'comment': self.comment, 'time': self.time, }, **kwargs))) except: warn('Unable to connect to \'{0}:{1}\'.'.format(self.server, self.port)) def progress(self, progress): self.status('PROGRESS', progress=progress) def save(self, filename=None, overwrite=False): """ Store results. If a filename is given, the default is overwritten. @type filename: string @param filename: path to where the experiment will be stored @type overwrite: boolean @param overwrite: overwrite existing files """ self.duration = time() - self.time if filename is None: filename = self.filename else: # replace {0} and {1} by date and time tmp1 = strftime('%d%m%Y', localtime(time())) tmp2 = strftime('%H%M%S', localtime(time())) filename = filename.format(tmp1, tmp2) self.filename = filename # make sure directory exists try: os.makedirs(path.dirname(filename)) except OSError: pass # make sure filename is unique counter = 0 pieces = path.splitext(filename) if not overwrite: while path.exists(filename): counter += 1 filename = pieces[0] + '.' + str(counter) + pieces[1] if counter: warn(''.join(pieces) + ' already exists. Saving to ' + filename + '.') # store experiment with open(filename, 'wb') as handle: dump({ 'version': __version__, 'id': self.id, 'time': self.time, 'seed': self.seed, 'duration': self.duration, 'environ': self.environ, 'hostname': self.hostname, 'cwd': self.cwd, 'argv': self.argv, 'script': self.script, 'script_path': self.script_path, 'processors': self.processors, 'platform': self.platform, 'comment': self.comment, 'commit': self.commit, 'modified': self.modified, 'versions': self.versions, 'results': self.results}, handle, 1) self.status('SAVE', filename=filename, duration=self.duration) def load(self, filename=None): """ Loads experimental results from the specified file. @type filename: string @param filename: path to where the experiment is stored """ if filename: self.filename = filename with open(self.filename, 'rb') as handle: res = load(handle) self.time = res['time'] self.seed = res['seed'] self.duration = res['duration'] self.processors = res['processors'] self.environ = res['environ'] self.platform = res['platform'] self.comment = res['comment'] self.commit = res['commit'] self.modified = res['modified'] self.versions = res['versions'] self.results = res['results'] self.argv = res['argv'] \ if StrictVersion(res['version']) >= '0.3.1' else None self.script = res['script'] \ if StrictVersion(res['version']) >= '0.4.0' else None self.script_path = res['script_path'] \ if StrictVersion(res['version']) >= '0.4.0' else None self.cwd = res['cwd'] \ if StrictVersion(res['version']) >= '0.4.0' else None self.hostname = res['hostname'] \ if StrictVersion(res['version']) >= '0.4.0' else None self.id = res['id'] \ if StrictVersion(res['version']) >= '0.4.0' else None def __getitem__(self, key): return self.results[key] def __setitem__(self, key, value): self.results[key] = value def __delitem__(self, key): del self.results[key] class ExperimentRequestHandler(BaseHTTPRequestHandler): """ Renders HTML showing running and finished experiments. """ xpck_path = '' running = {} finished = {} def do_GET(self): """ Renders HTML displaying running and saved experiments. """ # number of bars representing progress max_bars = 20 if self.path == '/version/': self.send_response(200) self.send_header('Content-type', 'text/plain') self.end_headers() self.wfile.write('Experiment {0}'.format(__version__)) elif self.path.startswith('/running/'): id = int([s for s in self.path.split('/') if s != ''][-1]) # display running experiment if id in ExperimentRequestHandler.running: self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(HTML_HEADER) self.wfile.write('<h2>Experiment</h2>') instance = ExperimentRequestHandler.running[id] num_bars = int(instance['progress']) * max_bars / 100 self.wfile.write('<table>') self.wfile.write('<tr><th>Experiment:</th><td>{0}</td></tr>'.format( os.path.join(instance['cwd'], instance['script_path']))) self.wfile.write('<tr><th>Hostname:</th><td>{0}</td></tr>'.format(instance['hostname'])) self.wfile.write('<tr><th>Status:</th><td class="running">{0}</td></tr>'.format(instance['status'])) self.wfile.write('<tr><th>Progress:</th><td class="progress"><span class="bars">{0}</span>{1}</td></tr>'.format( '|' * num_bars, '|' * (max_bars - num_bars))) self.wfile.write('<tr><th>Start:</th><td>{0}</td></tr>'.format( strftime('%a, %d %b %Y %H:%M:%S', localtime(instance['time'])))) self.wfile.write('<tr><th>Comment:</th><td>{0}</td></tr>'.format( instance['comment'] if instance['comment'] else '-')) self.wfile.write('</table>') self.wfile.write('<h2>Script</h2>') self.wfile.write('<pre>{0}</pre>'.format(instance['script'])) self.wfile.write(HTML_FOOTER) elif id in ExperimentRequestHandler.finished: self.send_response(302) self.send_header('Location', '/finished/{0}/'.format(id)) self.end_headers() else: self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(HTML_HEADER) self.wfile.write('<h2>404</h2>') self.wfile.write('Requested experiment not found.') self.wfile.write(HTML_FOOTER) elif self.path.startswith('/finished/'): self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(HTML_HEADER) id = int([s for s in self.path.split('/') if s != ''][-1]) # display finished experiment if id in ExperimentRequestHandler.finished: instance = ExperimentRequestHandler.finished[id] if id in ExperimentRequestHandler.running: progress = ExperimentRequestHandler.running[id]['progress'] else: progress = 100 num_bars = int(progress) * max_bars / 100 self.wfile.write('<h2>Experiment</h2>') self.wfile.write('<table>') self.wfile.write('<tr><th>Experiment:</th><td>{0}</td></tr>'.format( os.path.join(instance['cwd'], instance['script_path']))) self.wfile.write('<tr><th>Results:</th><td>{0}</td></tr>'.format( os.path.join(instance['cwd'], instance['filename']))) self.wfile.write('<tr><th>Status:</th><td class="finished">{0}</td></tr>'.format(instance['status'])) self.wfile.write('<tr><th>Progress:</th><td class="progress"><span class="bars">{0}</span>{1}</td></tr>'.format( '|' * num_bars, '|' * (max_bars - num_bars))) self.wfile.write('<tr><th>Start:</th><td>{0}</td></tr>'.format( strftime('%a, %d %b %Y %H:%M:%S', localtime(instance['time'])))) self.wfile.write('<tr><th>End:</th><td>{0}</td></tr>'.format( strftime('%a, %d %b %Y %H:%M:%S', localtime(instance['duration'])))) self.wfile.write('<tr><th>Comment:</th><td>{0}</td></tr>'.format( instance['comment'] if instance['comment'] else '-')) self.wfile.write('</table>') self.wfile.write('<h2>Results</h2>') try: experiment = Experiment(os.path.join(instance['cwd'], instance['filename'])) except: self.wfile.write('Could not open file.') else: self.wfile.write('<table>') for key, value in experiment.results.items(): self.wfile.write('<tr><th>{0}</th><td>{1}</td></tr>'.format(key, value)) self.wfile.write('</table>') self.wfile.write('<h2>Script</h2>') self.wfile.write('<pre>{0}</pre>'.format(instance['script'])) else: self.wfile.write('<h2>404</h2>') self.wfile.write('Requested experiment not found.') self.wfile.write(HTML_FOOTER) else: files = [] if 'xpck_path' in ExperimentRequestHandler.__dict__: if ExperimentRequestHandler.xpck_path != '': for path in ExperimentRequestHandler.xpck_path.split(':'): files += [os.path.join(path, f) for f in os.listdir(path) if f.endswith('.xpck')] if 'XPCK_PATH' in os.environ: for path in os.environ['XPCK_PATH'].split(':'): files += [os.path.join(path, f) for f in os.listdir(path) if f.endswith('.xpck')] self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(HTML_HEADER) self.wfile.write('<h2>Running</h2>') # display running experiments if ExperimentRequestHandler.running: self.wfile.write('<table>') self.wfile.write('<tr>') self.wfile.write('<th>Experiment</th>') self.wfile.write('<th>Hostname</th>') self.wfile.write('<th>Status</th>') self.wfile.write('<th>Progress</th>') self.wfile.write('<th>Start</th>') self.wfile.write('<th>Comment</th>') self.wfile.write('</tr>') # sort ids by start time of experiment times = [instance['time'] for instance in ExperimentRequestHandler.running.values()] ids = ExperimentRequestHandler.running.keys() ids = [ids[i] for i in argsort(times)][::-1] for id in ids: instance = ExperimentRequestHandler.running[id] num_bars = int(instance['progress']) * max_bars / 100 self.wfile.write('<tr>') self.wfile.write('<td class="filepath"><a href="/running/{1}/">{0}</a></td>'.format( instance['script_path'], instance['id'])) self.wfile.write('<td>{0}</td>'.format(instance['hostname'])) self.wfile.write('<td class="running">{0}</td>'.format(instance['status'])) self.wfile.write('<td class="progress"><span class="bars">{0}</span>{1}</td>'.format( '|' * num_bars, '|' * (max_bars - num_bars))) self.wfile.write('<td>{0}</td>'.format(strftime('%a, %d %b %Y %H:%M:%S', localtime(instance['time'])))) self.wfile.write('<td class="comment">{0}</td>'.format( instance['comment'] if instance['comment'] else '-')) self.wfile.write('</tr>') self.wfile.write('</table>') else: self.wfile.write('No running experiments.') self.wfile.write('<h2>Saved</h2>') # display saved experiments if ExperimentRequestHandler.finished: self.wfile.write('<table>') self.wfile.write('<tr>') self.wfile.write('<th>Results</th>') self.wfile.write('<th>Status</th>') self.wfile.write('<th>Progress</th>') self.wfile.write('<th>Start</th>') self.wfile.write('<th>End</th>') self.wfile.write('<th>Comment</th>') self.wfile.write('</tr>') # sort ids by start time of experiment times = [instance['time'] + instance['duration'] for instance in ExperimentRequestHandler.finished.values()] ids = ExperimentRequestHandler.finished.keys() ids = [ids[i] for i in argsort(times)][::-1] for id in ids: instance = ExperimentRequestHandler.finished[id] if id in ExperimentRequestHandler.running: progress = ExperimentRequestHandler.running[id]['progress'] else: progress = 100 num_bars = int(progress) * max_bars / 100 self.wfile.write('<tr>') self.wfile.write('<td class="filepath"><a href="/finished/{1}/">{0}</a></td>'.format( instance['filename'], instance['id'])) self.wfile.write('<td class="finished">saved</td>') self.wfile.write('<td class="progress"><span class="bars">{0}</span>{1}</td>'.format( '|' * num_bars, '|' * (max_bars - num_bars))) self.wfile.write('<td>{0}</td>'.format(strftime('%a, %d %b %Y %H:%M:%S', localtime(instance['time'])))) self.wfile.write('<td>{0}</td>'.format(strftime('%a, %d %b %Y %H:%M:%S', localtime(instance['time'] + instance['duration'])))) self.wfile.write('<td class="comment">{0}</td>'.format( instance['comment'] if instance['comment'] else '-')) self.wfile.write('</tr>') self.wfile.write('</table>') else: self.wfile.write('No saved experiments.') self.wfile.write(HTML_FOOTER) def do_POST(self): instances = ExperimentRequestHandler.running instance = eval(self.rfile.read(int(self.headers['Content-Length']))) if instance['status'] is 'PROGRESS': if instance['id'] not in instances: instances[instance['id']] = instance instances[instance['id']]['status'] = 'running' instances[instance['id']]['progress'] = instance['progress'] elif instance['status'] is 'SAVE': ExperimentRequestHandler.finished[instance['id']] = instance ExperimentRequestHandler.finished[instance['id']]['status'] = 'saved' else: if instance['id'] in instances: progress = instances[instance['id']]['progress'] else: progress = 0 instances[instance['id']] = instance instances[instance['id']]['progress'] = progress if instance['status'] is None: try: del instances[instance['id']] except: pass class XUnpickler(Unpickler): """ An extension of the Unpickler class which resolves some backwards compatibility issues of Numpy. """ def find_class(self, module, name): """ Helps Unpickler to find certain Numpy modules. """ try: numpy_version = StrictVersion(numpy.__version__) if numpy_version >= '1.5.0': if module == 'numpy.core.defmatrix': module = 'numpy.matrixlib.defmatrix' except ValueError: pass return Unpickler.find_class(self, module, name) def load(file): return XUnpickler(file).load() def main(argv): """ Load and display experiment information. """ if len(argv) < 2: print 'Usage:', argv[0], '[--server] [--port=<port>] [--path=<path>] [filename]' return 0 optlist, argv = getopt(argv[1:], '', ['server', 'port=', 'path=']) optlist = dict(optlist) if '--server' in optlist: try: ExperimentRequestHandler.xpck_path = optlist.get('--path', '') port = optlist.get('--port', 8000) # start server server = HTTPServer(('', port), ExperimentRequestHandler) server.serve_forever() except KeyboardInterrupt: server.socket.close() return 0 # load experiment experiment = Experiment(sys.argv[1]) if len(argv) > 1: # print arguments for arg in argv[1:]: try: print experiment[arg] except: print experiment[int(arg)] return 0 # print summary of experiment print experiment return 0 HTML_HEADER = '''<html> <head> <title>Experiments</title> <style type="text/css"> body { font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; font-size: 11pt; color: black; background: white; padding: 0pt 20pt; } h2 { margin-top: 20pt; font-size: 16pt; } table { border-collapse: collapse; } tr:nth-child(even) { background: #f4f4f4; } th { font-size: 12pt; text-align: left; padding: 2pt 10pt 3pt 0pt; } td { font-size: 10pt; padding: 3pt 10pt 2pt 0pt; } pre { font-size: 10pt; background: #f4f4f4; padding: 5pt; } a { text-decoration: none; color: #04a; } .running { color: #08b; } .finished { color: #390; } .comment { min-width: 200pt; font-style: italic; } .progress { color: #ccc; } .progress .bars { color: black; } </style> </head> <body>''' HTML_FOOTER = ''' </body> </html>''' if __name__ == '__main__': sys.exit(main(sys.argv))
jonasrauber/c2s
c2s/experiment.py
Python
mit
21,962
#entity-manager-container { margin-bottom: 20px; text-align: center; } #tag { margin-left: auto; margin-right: auto; } #inbox { margin-top: 20px; } #entity-manager-heading { margin-bottom: 20px; } #graphs-container { margin-bottom: 20px; } #selectors-container { text-align: center; margin-bottom: 20px; } #graph-container { text-align: center; }
vincentfung13/TwitterRepManagement
user_handle/static/user_handle/css/user_index.css
CSS
mit
392
package ir.abforce.dinorunner.custom; import com.makersf.andengine.extension.collisions.entity.sprite.PixelPerfectSprite; import com.makersf.andengine.extension.collisions.opengl.texture.region.PixelPerfectTextureRegion; import ir.abforce.dinorunner.managers.RM; /** * Created by Ali Reza on 9/4/15. */ public class SPixelPerfectSprite extends PixelPerfectSprite { public SPixelPerfectSprite(float pX, float pY, PixelPerfectTextureRegion pTextureRegion) { super(pX, pY, pTextureRegion, RM.VBO); setScale(RM.S); } }
abforce/Dino-Runner
app/src/main/java/ir/abforce/dinorunner/custom/SPixelPerfectSprite.java
Java
mit
544
SET DEFINE OFF; CREATE SEQUENCE AFW_25_VERSN_PUBLC_SEQ START WITH 1 MAXVALUE 9999999999999999999999999999 MINVALUE 1 NOCYCLE CACHE 20 NOORDER /
lgcarrier/APEXFramework
5.2.3/Database/Sequences/AFW_25_VERSN_PUBLC_SEQ.sql
SQL
mit
156
// Castor : Logic Programming Library // Copyright © 2007-2010 Roshan Naik (roshan@mpprogramming.com). // This software is governed by the MIT license (http://www.opensource.org/licenses/mit-license.php). #ifndef CASTOR_PREDICATE_H #define CASTOR_PREDICATE_H 1 #include "relation.h" #include "helpers.h" #include "workaround.h" namespace castor { //---------------------------------------------------------------------------- // predicate : Adaptor relation for treating predicate functions as relations //---------------------------------------------------------------------------- template<typename Pred> struct Predicate0_r : public detail::TestOnlyRelation<Predicate0_r<Pred> > { Pred pred; Predicate0_r (const Pred& pred) : pred(pred) { } bool apply() { return pred(); } }; template<typename Pred, typename A1> struct Predicate1_r : public detail::TestOnlyRelation<Predicate1_r<Pred,A1> > { Pred pred; A1 a1; Predicate1_r (const Pred& pred, const A1& a1) : pred(pred), a1(a1) { } bool apply() { return pred(effective_value(a1)); } }; template<typename Pred, typename A1, typename A2> struct Predicate2_r : public detail::TestOnlyRelation<Predicate2_r<Pred,A1,A2> > { Pred pred; A1 a1; A2 a2; Predicate2_r (const Pred& pred, const A1& a1, const A2& a2) : pred(pred), a1(a1), a2(a2) { } bool apply() { return pred(effective_value(a1),effective_value(a2)); } }; template<typename Pred, typename A1, typename A2, typename A3> struct Predicate3_r : public detail::TestOnlyRelation<Predicate3_r<Pred,A1,A2,A3> > { Pred pred; A1 a1; A2 a2; A3 a3; Predicate3_r (const Pred& pred, const A1& a1, const A2& a2, const A3& a3) : pred(pred), a1(a1), a2(a2), a3(a3) { } bool apply() { return pred(effective_value(a1),effective_value(a2),effective_value(a3)); } }; template<typename Pred, typename A1, typename A2, typename A3, typename A4> struct Predicate4_r : public detail::TestOnlyRelation<Predicate4_r<Pred,A1,A2,A3,A4> > { Pred pred; A1 a1; A2 a2; A3 a3; A4 a4; Predicate4_r (const Pred& pred, const A1& a1, const A2& a2, const A3& a3, const A4& a4) : pred(pred), a1(a1), a2(a2), a3(a3), a4(a4) { } bool apply() { return pred(effective_value(a1),effective_value(a2),effective_value(a3),effective_value(a4)); } }; template<typename Pred, typename A1, typename A2, typename A3, typename A4, typename A5> struct Predicate5_r : public detail::TestOnlyRelation<Predicate5_r<Pred,A1,A2,A3,A4,A5> > { Pred pred; A1 a1; A2 a2; A3 a3; A4 a4; A5 a5; Predicate5_r (const Pred& pred, const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5) : pred(pred), a1(a1), a2(a2), a3(a3), a4(a4), a5(a5) { } bool apply() { return pred(effective_value(a1),effective_value(a2),effective_value(a3),effective_value(a4),effective_value(a5)); } }; template<typename Pred, typename A1, typename A2, typename A3, typename A4, typename A5, typename A6> struct Predicate6_r : public detail::TestOnlyRelation<Predicate6_r<Pred,A1,A2,A3,A4,A5,A6> > { Pred pred; A1 a1; A2 a2; A3 a3; A4 a4; A5 a5; A6 a6; Predicate6_r (const Pred& pred, const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5, const A6& a6) : pred(pred), a1(a1), a2(a2), a3(a3), a4(a4), a5(a5), a6(a6) { } bool apply() { return pred(effective_value(a1),effective_value(a2),effective_value(a3),effective_value(a4),effective_value(a5),effective_value(a6)); } }; // support for function objects template<typename Pred> inline Predicate0_r<Pred> predicate(Pred pred) { return Predicate0_r<Pred>(pred); } template<typename Pred, typename A1> inline Predicate1_r<Pred,A1> predicate(Pred pred, const A1& a1_) { return Predicate1_r<Pred,A1>(pred,a1_); } template<typename Pred, typename A1, typename A2> inline Predicate2_r<Pred,A1,A2> predicate(Pred pred, const A1& a1_, const A2& a2_) { return Predicate2_r<Pred,A1,A2>(pred,a1_,a2_); } template<typename Pred, typename A1, typename A2, typename A3> inline Predicate3_r<Pred,A1,A2,A3> predicate(Pred pred, const A1& a1_, const A2& a2_, const A3& a3_) { return Predicate3_r<Pred,A1,A2,A3>(pred,a1_,a2_,a3_); } template<typename Pred, typename A1, typename A2, typename A3, typename A4> inline Predicate4_r<Pred,A1,A2,A3,A4> predicate(Pred pred, const A1& a1_, const A2& a2_, const A3& a3_, const A4& a4_) { return Predicate4_r<Pred,A1,A2,A3,A4>(pred,a1_,a2_,a3_,a4_); } template<typename Pred, typename A1, typename A2, typename A3, typename A4 ,typename A5> inline Predicate5_r<Pred,A1,A2,A3,A4,A5> predicate(Pred pred, const A1& a1_, const A2& a2_, const A3& a3_, const A4& a4_, const A5& a5_) { return Predicate5_r<Pred,A1,A2,A3,A4,A5>(pred,a1_,a2_,a3_,a4_,a5_); } template<typename Pred, typename A1, typename A2, typename A3, typename A4 ,typename A5, typename A6> inline Predicate6_r<Pred,A1,A2,A3,A4,A5,A6> predicate(Pred pred, const A1& a1_, const A2& a2_, const A3& a3_, const A4& a4_, const A5& a5_, const A6& a6_) { return Predicate6_r<Pred,A1,A2,A3,A4,A5,A6>(pred,a1_,a2_,a3_,a4_,a5_,a6_); } // support for function pointers template<typename R> inline Predicate0_r<R(*)(void)> predicate(R(* pred)(void)) { return Predicate0_r<R(*)(void)>(pred); } template<typename R, typename P1, typename A1> inline Predicate1_r<R(*)(P1),A1> predicate(R(* pred)(P1), const A1& a1_) { return Predicate1_r<R(*)(P1),A1>(pred,a1_); } template<typename R, typename P1, typename P2, typename A1, typename A2> inline Predicate2_r<R(*)(P1,P2),A1,A2> predicate(R(* pred)(P1,P2), const A1& a1_, const A2& a2_) { return Predicate2_r<R(*)(P1,P2),A1,A2>(pred,a1_,a2_); } template<typename R, typename P1, typename P2, typename P3, typename A1, typename A2, typename A3> inline Predicate3_r<R(*)(P1,P2,P3),A1,A2,A3> predicate(R(* pred)(P1,P2,P3), const A1& a1_, const A2& a2_, const A3& a3_) { return Predicate3_r<R(*)(P1,P2,P3),A1,A2,A3>(pred,a1_,a2_,a3_); } template<typename R, typename P1, typename P2, typename P3, typename P4, typename A1, typename A2, typename A3, typename A4> inline Predicate4_r<R(*)(P1,P2,P3,P4),A1,A2,A3,A4> predicate(R(* pred)(P1,P2,P3,P4), const A1& a1_, const A2& a2_, const A3& a3_, const A4& a4_) { return Predicate4_r<R(*)(P1,P2,P3,P4),A1,A2,A3,A4>(pred,a1_,a2_,a3_,a4_); } template<typename R, typename P1, typename P2, typename P3, typename P4, typename P5, typename A1, typename A2, typename A3, typename A4, typename A5> inline Predicate5_r<R(*)(P1,P2,P3,P4,P5),A1,A2,A3,A4,A5> predicate(R(* pred)(P1,P2,P3,P4,P5), const A1& a1_, const A2& a2_, const A3& a3_, const A4& a4_, const A5& a5_) { return Predicate5_r<R(*)(P1,P2,P3,P4,P5),A1,A2,A3,A4,A5>(pred,a1_,a2_,a3_,a4_,a5_); } template<typename R, typename P1, typename P2, typename P3, typename P4, typename P5, typename P6, typename A1, typename A2, typename A3, typename A4, typename A5, typename A6> inline Predicate6_r<R(*)(P1,P2,P3,P4,P5,P6),A1,A2,A3,A4,A5,A6> predicate(R(* pred)(P1,P2,P3,P4,P5,P6), const A1& a1_, const A2& a2_, const A3& a3_, const A4& a4_, const A5& a5_, const A6& a6_) { return Predicate6_r<R(*)(P1,P2,P3,P4,P5,P6),A1,A2,A3,A4,A5,A6>(pred,a1_,a2_,a3_,a4_,a5_,a6_); } //---------------------------------------------------------------------------- // predicate_mf : Adaptor relation for treating predicate methods as relations //---------------------------------------------------------------------------- template<typename Obj, typename MemPred> class MemPredicate0_r : public detail::TestOnlyRelation<MemPredicate0_r<Obj,MemPred> > { lref<Obj> obj_; MemPred pred; public: MemPredicate0_r (lref<Obj> obj_, MemPred pred) : obj_(obj_), pred(pred) { } bool apply() { return ((*obj_).*pred)(); } }; template<typename Obj, typename MemPred, typename A1> class MemPredicate1_r : public detail::TestOnlyRelation<MemPredicate1_r<Obj,MemPred,A1> > { lref<Obj> obj_; MemPred pred; A1 arg1; public: MemPredicate1_r (lref<Obj> obj_, MemPred pred, const A1& arg1) : obj_(obj_), pred(pred), arg1(arg1) { } bool apply() { return ((*obj_).*pred)(effective_value(arg1)); } }; template<typename Obj, typename MemPred, typename A1, typename A2> class MemPredicate2_r : public detail::TestOnlyRelation<MemPredicate2_r<Obj,MemPred,A1,A2> > { lref<Obj> obj_; MemPred pred; A1 arg1; A2 arg2; public: MemPredicate2_r (lref<Obj> obj_, MemPred pred, const A1& arg1, const A2& arg2) : obj_(obj_), pred(pred), arg1(arg1), arg2(arg2) { } bool apply() { return ((*obj_).*pred)( effective_value(arg1), effective_value(arg2) ); } }; template<typename Obj, typename MemPred, typename A1, typename A2, typename A3> class MemPredicate3_r : public detail::TestOnlyRelation<MemPredicate3_r<Obj,MemPred,A1,A2,A3> > { lref<Obj> obj_; MemPred pred; A1 arg1; A2 arg2; A3 arg3; public: MemPredicate3_r (lref<Obj> obj_, MemPred pred, const A1& arg1, const A2& arg2, const A2& arg3) : obj_(obj_), pred(pred), arg1(arg1), arg2(arg2), arg3(arg3) { } bool apply() { return ((*obj_).*pred)(effective_value(arg1), effective_value(arg2), effective_value(arg3)); } }; template<typename Obj, typename MemPred, typename A1, typename A2, typename A3, typename A4> class MemPredicate4_r : public detail::TestOnlyRelation<MemPredicate4_r<Obj,MemPred,A1,A2,A3,A4> > { lref<Obj> obj_; MemPred pred; A1 arg1; A2 arg2; A3 arg3; A4 arg4; public: MemPredicate4_r (lref<Obj> obj_, MemPred pred, const A1& arg1, const A2& arg2, const A3& arg3, const A4& arg4) :obj_(obj_), pred(pred), arg1(arg1), arg2(arg2), arg3(arg3), arg4(arg4) { } bool apply() { return ((*obj_).*pred)(effective_value(arg1), effective_value(arg2), effective_value(arg3), effective_value(arg4) ); } }; template<typename Obj, typename MemPred, typename A1, typename A2, typename A3, typename A4, typename A5> class MemPredicate5_r : public detail::TestOnlyRelation<MemPredicate5_r<Obj,MemPred,A1,A2,A3,A4,A5> > { lref<Obj> obj_; MemPred pred; A1 arg1; A2 arg2; A3 arg3; A4 arg4; A5 arg5; public: MemPredicate5_r (lref<Obj> obj_, MemPred pred, const A1& arg1, const A2& arg2, const A3& arg3, const A4& arg4, const A5& arg5) : obj_(obj_), pred(pred), arg1(arg1), arg2(arg2), arg3(arg3), arg4(arg4), arg5(arg5) { } bool apply() { return ((*obj_).*pred)(effective_value(arg1), effective_value(arg2), effective_value(arg3), effective_value(arg4), effective_value(arg5) ); } }; template<typename Obj, typename MemPred, typename A1, typename A2, typename A3, typename A4, typename A5, typename A6> class MemPredicate6_r : public detail::TestOnlyRelation<MemPredicate6_r<Obj,MemPred,A1,A2,A3,A4,A5,A6> > { lref<Obj> obj_; MemPred pred; A1 arg1; A2 arg2; A3 arg3; A4 arg4; A5 arg5; A6 arg6; public: MemPredicate6_r (const lref<Obj>& obj_, MemPred pred, const A1& arg1, const A2& arg2, const A3& arg3, const A4& arg4, const A5& arg5, const A6& arg6) : obj_(obj_), pred(pred), arg1(arg1), arg2(arg2), arg3(arg3), arg4(arg4), arg5(arg5), arg6(arg6) { } bool apply() { return ((*obj_).*pred)(effective_value(arg1), effective_value(arg2), effective_value(arg3), effective_value(arg4), effective_value(arg5), effective_value(arg6)); } }; // 0 template<typename R, typename Obj, typename Obj2> inline MemPredicate0_r<Obj,R(Obj::*)(void)> predicate_mf(lref<Obj>& obj_, R(Obj2::* mempred)(void) ) { return MemPredicate0_r<Obj,R(Obj::*)(void)>(obj_, mempred); } template<typename R, typename Obj, typename Obj2> inline MemPredicate0_r<Obj,R(Obj::*)(void) const> predicate_mf(lref<Obj>& obj_, R(Obj2::* mempred)(void) const) { return MemPredicate0_r<Obj,R(Obj::*)(void) const>(obj_, mempred); } // 1 template<typename R, typename P1, typename Obj, typename Obj2, typename A1> inline MemPredicate1_r<Obj,R(Obj::*)(P1),A1> predicate_mf(lref<Obj>& obj_, R(Obj2::* mempred)(P1), const A1& arg1) { return MemPredicate1_r<Obj,R(Obj::*)(P1),A1>(obj_, mempred, arg1); } template<typename R, typename P1, typename Obj, typename Obj2, typename A1> inline MemPredicate1_r<Obj,R(Obj::*)(P1) const,A1> predicate_mf(lref<Obj>& obj_, R(Obj2::* mempred)(P1) const, const A1& arg1) { return MemPredicate1_r<Obj,R(Obj::*)(P1) const,A1>(obj_, mempred, arg1); } // 2 template<typename R, typename P1, typename P2, typename Obj, typename Obj2, typename A1, typename A2> inline MemPredicate2_r<Obj,R(Obj::*)(P1,P2),A1,A2> predicate_mf(lref<Obj>& obj_, R(Obj2::* mempred)(P1,P2), const A1& arg1, const A2& arg2) { return MemPredicate2_r<Obj,R(Obj::*)(P1,P2),A1,A2>(obj_, mempred, arg1, arg2); } template<typename R, typename P1, typename P2, typename Obj, typename Obj2, typename A1, typename A2> inline MemPredicate2_r<Obj,R(Obj::*)(P1,P2) const,A1,A2> predicate_mf(lref<Obj>& obj_, R(Obj2::* mempred)(P1,P2) const, const A1& arg1, const A2& arg2) { return MemPredicate2_r<Obj,R(Obj::*)(P1,P2) const,A1,A2>(obj_, mempred, arg1, arg2); } // 3 template<typename R, typename P1, typename P2, typename P3, typename Obj, typename Obj2, typename A1, typename A2, typename A3> inline MemPredicate3_r<Obj,R(Obj::*)(P1,P2,P3),A1,A2,A3> predicate_mf(lref<Obj>& obj_, R(Obj2::* mempred)(P1,P2,P3), const A1& arg1, const A2& arg2, const A3& arg3) { return MemPredicate3_r<Obj,R(Obj::*)(P1,P2,P3),A1,A2,A3>(obj_, mempred, arg1, arg2, arg3); } template<typename R, typename P1, typename P2, typename P3, typename Obj, typename Obj2, typename A1, typename A2, typename A3> inline MemPredicate3_r<Obj,R(Obj::*)(P1,P2,P3) const,A1,A2,A3> predicate_mf(lref<Obj>& obj_, R(Obj2::* mempred)(P1,P2,P3) const, const A1& arg1, const A2& arg2, const A3& arg3) { return MemPredicate3_r<Obj,R(Obj::*)(P1,P2,P3) const,A1,A2,A3>(obj_, mempred, arg1, arg2, arg3); } // 4 template<typename R, typename P1, typename P2, typename P3, typename P4, typename Obj, typename Obj2, typename A1, typename A2, typename A3, typename A4> inline MemPredicate4_r<Obj,R(Obj::*)(P1,P2,P3,P4),A1,A2,A3,A4> predicate_mf(lref<Obj>& obj_, R(Obj2::* mempred)(P1,P2,P3,P4), const A1& arg1, const A2& arg2, const A3& arg3, const A4& arg4) { return MemPredicate4_r<Obj,R(Obj::*)(P1,P2,P3,P4),A1,A2,A3,A4>(obj_, mempred, arg1, arg2, arg3, arg4); } template<typename R, typename P1, typename P2, typename P3, typename P4, typename Obj, typename Obj2, typename A1, typename A2, typename A3, typename A4> inline MemPredicate4_r<Obj,R(Obj::*)(P1,P2,P3,P4) const,A1,A2,A3,A4> predicate_mf(lref<Obj>& obj_, R(Obj2::* mempred)(P1,P2,P3,P4) const, const A1& arg1, const A2& arg2, const A3& arg3, const A4& arg4) { return MemPredicate4_r<Obj,R(Obj::*)(P1,P2,P3,P4) const,A1,A2,A3,A4>(obj_, mempred, arg1, arg2, arg3, arg4); } // 5 template<typename R, typename P1, typename P2, typename P3, typename P4, typename P5, typename Obj, typename Obj2, typename A1, typename A2, typename A3, typename A4, typename A5> inline MemPredicate5_r<Obj,R(Obj::*)(P1,P2,P3,P4,P5),A1,A2,A3,A4,A5> predicate_mf(lref<Obj>& obj_, R(Obj2::* mempred)(P1,P2,P3,P4,P5), const A1& arg1, const A2& arg2, const A3& arg3, const A4& arg4, const A5& arg5) { return MemPredicate5_r<Obj,R(Obj::*)(P1,P2,P3,P4,P5),A1,A2,A3,A4,A5>(obj_, mempred, arg1, arg2, arg3, arg4, arg5); } template<typename R, typename P1, typename P2, typename P3, typename P4, typename P5, typename Obj, typename Obj2, typename A1, typename A2, typename A3, typename A4, typename A5> inline MemPredicate5_r<Obj,R(Obj::*)(P1,P2,P3,P4,P5) const,A1,A2,A3,A4,A5> predicate_mf(lref<Obj>& obj_, R(Obj2::* mempred)(P1,P2,P3,P4,P5) const, const A1& arg1, const A2& arg2, const A3& arg3, const A4& arg4, const A5& arg5) { return MemPredicate5_r<Obj,R(Obj::*)(P1,P2,P3,P4,P5) const,A1,A2,A3,A4,A5>(obj_, mempred, arg1, arg2, arg3, arg4, arg5); } // 6 template<typename R, typename P1, typename P2, typename P3, typename P4, typename P5, typename P6, typename Obj, typename Obj2, typename A1, typename A2, typename A3, typename A4, typename A5, typename A6> inline MemPredicate6_r<Obj,R(Obj::*)(P1,P2,P3,P4,P5,P6),A1,A2,A3,A4,A5,A6> predicate_mf(lref<Obj>& obj_, R(Obj2::* mempred)(P1,P2,P3,P4,P5,P6), const A1& arg1, const A2& arg2, const A3& arg3, const A4& arg4, const A5& arg5, const A6& arg6) { return MemPredicate6_r<Obj,R(Obj::*)(P1,P2,P3,P4,P5,P6),A1,A2,A3,A4,A5,A6>(obj_, mempred, arg1, arg2, arg3, arg4, arg5, arg6); } template<typename R, typename P1, typename P2, typename P3, typename P4, typename P5, typename P6, typename Obj, typename Obj2, typename A1, typename A2, typename A3, typename A4, typename A5, typename A6> inline MemPredicate6_r<Obj,R(Obj::*)(P1,P2,P3,P4,P5,P6) const,A1,A2,A3,A4,A5,A6> predicate_mf(lref<Obj>& obj_, R(Obj2::* mempred)(P1,P2,P3,P4,P5,P6) const, const A1& arg1, const A2& arg2, const A3& arg3, const A4& arg4, const A5& arg5, const A6& arg6) { return MemPredicate6_r<Obj,R(Obj::*)(P1,P2,P3,P4,P5,P6) const,A1,A2,A3,A4,A5,A6>(obj_, mempred, arg1, arg2, arg3, arg4, arg5, arg6); } //---------------------------------------------------------------- // predicate_mem : Unify with a member variable //---------------------------------------------------------------- template<typename Obj, typename MemberT> class Predicate_mem_r : public detail::TestOnlyRelation<Predicate_mem_r<Obj,MemberT> > { lref<Obj> obj_; MemberT Obj::* mem; public: Predicate_mem_r(const lref<Obj>& obj_, MemberT Obj::* mem) : obj_(obj_), mem(mem) { } bool apply() { return (*obj_).*mem; } }; template<typename Obj, typename Obj2, typename MemberT> inline Predicate_mem_r<Obj, MemberT> predicate_mem(lref<Obj>& obj_, MemberT Obj2::* mem) { return Predicate_mem_r<Obj, MemberT>(obj_, mem); } } // namespace castor #endif
jbandela/Castor_Mirror
includes/predicate.h
C
mit
17,894
# encoding: utf-8 # frozen_string_literal: true require 'spec_helper' describe RuboCop::Cop::Style::ElseAlignment do subject(:cop) { described_class.new(config) } let(:config) do RuboCop::Config.new('Lint/EndAlignment' => end_alignment_config) end let(:end_alignment_config) do { 'Enabled' => true, 'AlignWith' => 'variable' } end it 'accepts a ternary if' do inspect_source(cop, 'cond ? func1 : func2') expect(cop.offenses).to be_empty end context 'with if statement' do it 'registers an offense for misaligned else' do inspect_source(cop, ['if cond', ' func1', ' else', ' func2', 'end']) expect(cop.messages).to eq(['Align `else` with `if`.']) expect(cop.highlights).to eq(['else']) end it 'registers an offense for misaligned elsif' do inspect_source(cop, [' if a1', ' b1', 'elsif a2', ' b2', ' end']) expect(cop.messages).to eq(['Align `elsif` with `if`.']) expect(cop.highlights).to eq(['elsif']) end it 'accepts indentation after else when if is on new line after ' \ 'assignment' do inspect_source(cop, ['Rails.application.config.ideal_postcodes_key =', ' if Rails.env.production? || Rails.env.staging?', ' "AAAA-AAAA-AAAA-AAAA"', ' else', ' "BBBB-BBBB-BBBB-BBBB"', ' end']) expect(cop.offenses).to be_empty end describe '#autocorrect' do it 'corrects bad alignment' do corrected = autocorrect_source(cop, [' if a1', ' b1', ' elsif a2', ' b2', 'else', ' c', ' end']) expect(cop.messages).to eq(['Align `elsif` with `if`.', 'Align `else` with `if`.']) expect(corrected) .to eq [' if a1', ' b1', ' elsif a2', ' b2', ' else', ' c', ' end'].join("\n") end end it 'accepts a one line if statement' do inspect_source(cop, 'if cond then func1 else func2 end') expect(cop.offenses).to be_empty end it 'accepts a correctly aligned if/elsif/else/end' do inspect_source(cop, ['if a1', ' b1', 'elsif a2', ' b2', 'else', ' c', 'end']) expect(cop.offenses).to be_empty end context 'with assignment' do context 'when alignment style is variable' do context 'and end is aligned with variable' do it 'accepts an if-else with end aligned with setter' do inspect_source(cop, ['foo.bar = if baz', ' derp1', 'else', ' derp2', 'end']) expect(cop.offenses).to be_empty end it 'accepts an if-elsif-else with end aligned with setter' do inspect_source(cop, ['foo.bar = if baz', ' derp1', 'elsif meh', ' derp2', 'else', ' derp3', 'end']) expect(cop.offenses).to be_empty end it 'accepts an if with end aligned with element assignment' do inspect_source(cop, ['foo[bar] = if baz', ' derp', 'end']) expect(cop.offenses).to be_empty end it 'accepts an if/else' do inspect_source(cop, ['var = if a', ' 0', 'else', ' 1', 'end']) expect(cop.offenses).to be_empty end it 'accepts an if/else with chaining after the end' do inspect_source(cop, ['var = if a', ' 0', 'else', ' 1', 'end.abc.join("")']) expect(cop.offenses).to be_empty end it 'accepts an if/else with chaining with a block after the end' do inspect_source(cop, ['var = if a', ' 0', 'else', ' 1', 'end.abc.tap {}']) expect(cop.offenses).to be_empty end end context 'and end is aligned with keyword' do it 'registers offenses for an if with setter' do inspect_source(cop, ['foo.bar = if baz', ' derp1', ' elsif meh', ' derp2', ' else', ' derp3', ' end']) expect(cop.messages).to eq(['Align `elsif` with `foo.bar`.', 'Align `else` with `foo.bar`.']) end it 'registers an offense for an if with element assignment' do inspect_source(cop, ['foo[bar] = if baz', ' derp1', ' else', ' derp2', ' end']) expect(cop.messages).to eq(['Align `else` with `foo[bar]`.']) end it 'registers an offense for an if' do inspect_source(cop, ['var = if a', ' 0', ' else', ' 1', ' end']) expect(cop.messages).to eq(['Align `else` with `var`.']) end end end shared_examples 'assignment and if with keyword alignment' do context 'and end is aligned with variable' do it 'registers an offense for an if' do inspect_source(cop, ['var = if a', ' 0', 'elsif b', ' 1', 'end']) expect(cop.messages).to eq(['Align `elsif` with `if`.']) end it 'autocorrects bad alignment' do corrected = autocorrect_source(cop, ['var = if a', ' b1', 'else', ' b2', 'end']) expect(corrected).to eq ['var = if a', ' b1', ' else', ' b2', 'end'].join("\n") end end context 'and end is aligned with keyword' do it 'accepts an if in assignment' do inspect_source(cop, ['var = if a', ' 0', ' end']) expect(cop.offenses).to be_empty end it 'accepts an if/else in assignment' do inspect_source(cop, ['var = if a', ' 0', ' else', ' 1', ' end']) expect(cop.offenses).to be_empty end it 'accepts an if/else in assignment on next line' do inspect_source(cop, ['var =', ' if a', ' 0', ' else', ' 1', ' end']) expect(cop.offenses).to be_empty end it 'accepts a while in assignment' do inspect_source(cop, ['var = while a', ' b', ' end']) expect(cop.offenses).to be_empty end it 'accepts an until in assignment' do inspect_source(cop, ['var = until a', ' b', ' end']) expect(cop.offenses).to be_empty end end end context 'when alignment style is keyword by choice' do let(:end_alignment_config) do { 'Enabled' => true, 'AlignWith' => 'keyword' } end include_examples 'assignment and if with keyword alignment' end context 'when alignment style is keyword by default' do let(:end_alignment_config) do { 'Enabled' => false, 'AlignWith' => 'variable' } end include_examples 'assignment and if with keyword alignment' end end it 'accepts an if/else branches with rescue clauses' do # Because of how the rescue clauses come out of Parser, these are # special and need to be tested. inspect_source(cop, ['if a', ' a rescue nil', 'else', ' a rescue nil', 'end']) expect(cop.offenses).to be_empty end end context 'with unless' do it 'registers an offense for misaligned else' do inspect_source(cop, ['unless cond', ' func1', ' else', ' func2', 'end']) expect(cop.messages).to eq(['Align `else` with `unless`.']) end it 'accepts a correctly aligned else in an otherwise empty unless' do inspect_source(cop, ['unless a', 'else', 'end']) expect(cop.offenses).to be_empty end it 'accepts an empty unless' do inspect_source(cop, ['unless a', 'end']) expect(cop.offenses).to be_empty end end context 'with case' do it 'registers an offense for misaligned else' do inspect_source(cop, ['case a', 'when b', ' c', 'when d', ' e', ' else', ' f', 'end']) expect(cop.messages).to eq(['Align `else` with `when`.']) end it 'accepts correctly aligned case/when/else' do inspect_source(cop, ['case a', 'when b', ' c', ' c', 'when d', 'else', ' f', 'end']) expect(cop.offenses).to be_empty end it 'accepts case without else' do inspect_source(cop, ['case superclass', 'when /\A(#{NAMESPACEMATCH})(?:\s|\Z)/', ' $1', 'when "self"', ' namespace.path', 'end']) expect(cop.offenses).to be_empty end it 'accepts else aligned with when but not with case' do # "Indent when as deep as case" is the job of another cop, and this is # one of the possible styles supported by configuration. inspect_source(cop, ['case code_type', " when 'ruby', 'sql', 'plain'", ' code_type', " when 'erb'", " 'ruby; html-script: true'", ' when "html"', " 'xml'", ' else', " 'plain'", 'end']) expect(cop.offenses).to be_empty end end context 'with def/defs' do it 'accepts an empty def body' do inspect_source(cop, ['def test', 'end']) expect(cop.offenses).to be_empty end it 'accepts an empty defs body' do inspect_source(cop, ['def self.test', 'end']) expect(cop.offenses).to be_empty end if RUBY_VERSION >= '2.1' context 'when modifier and def are on the same line' do it 'accepts a correctly aligned body' do inspect_source(cop, ['private def test', ' something', 'rescue', ' handling', 'else', ' something_else', 'end']) expect(cop.offenses).to be_empty end it 'registers an offense for else not aligned with private' do inspect_source(cop, ['private def test', ' something', ' rescue', ' handling', ' else', ' something_else', ' end']) expect(cop.messages).to eq(['Align `else` with `private`.']) end end end end context 'with begin/rescue/else/ensure/end' do it 'registers an offense for misaligned else' do inspect_source(cop, ['def my_func', " puts 'do something outside block'", ' begin', " puts 'do something error prone'", ' rescue SomeException, SomeOther => e', " puts 'wrongly intended error handling'", ' rescue', " puts 'wrongly intended error handling'", 'else', " puts 'wrongly intended normal case handling'", ' ensure', " puts 'wrongly intended common handling'", ' end', 'end']) expect(cop.messages).to eq(['Align `else` with `begin`.']) end it 'accepts a correctly aligned else' do inspect_source(cop, ['begin', " raise StandardError.new('Fail') if rand(2).odd?", 'rescue StandardError => error', ' $stderr.puts error.message', 'else', " $stdout.puts 'Lucky you!'", 'end']) expect(cop.offenses).to be_empty end end context 'with def/rescue/else/ensure/end' do it 'accepts a correctly aligned else' do inspect_source(cop, ['def my_func(string)', ' puts string', 'rescue => e', ' puts e', 'else', ' puts e', 'ensure', " puts 'I love methods that print'", 'end']) expect(cop.offenses).to be_empty end it 'registers an offense for misaligned else' do inspect_source(cop, ['def my_func(string)', ' puts string', 'rescue => e', ' puts e', ' else', ' puts e', 'ensure', " puts 'I love methods that print'", 'end']) expect(cop.messages).to eq(['Align `else` with `def`.']) end end context 'with def/rescue/else/end' do it 'accepts a correctly aligned else' do inspect_source(cop, ['def my_func', " puts 'do something error prone'", 'rescue SomeException', " puts 'error handling'", 'rescue', " puts 'error handling'", 'else', " puts 'normal handling'", 'end']) expect(cop.messages).to be_empty end it 'registers an offense for misaligned else' do inspect_source(cop, ['def my_func', " puts 'do something error prone'", 'rescue SomeException', " puts 'error handling'", 'rescue', " puts 'error handling'", ' else', " puts 'normal handling'", 'end']) expect(cop.messages).to eq(['Align `else` with `def`.']) end end end
mrb/rubocop
spec/rubocop/cop/style/else_alignment_spec.rb
Ruby
mit
17,903
// // CollectionViewCell.h // Timetable // // Created by FuShouqiang on 16/10/18. // Copyright © 2016年 fu. All rights reserved. // #import <UIKit/UIKit.h> //课程表主CollectionView @interface CollectionViewCell : UICollectionViewCell @property (nonatomic, copy) NSString *cellName; @property (nonatomic, copy) NSString *place; @property (nonatomic, assign) NSInteger signNumber; @end
594438666233/SQ_WDDXSH_B
SX_WDDXSH/SX_WDDXSH/Modules/Schedule/View/CollectionViewCell.h
C
mit
399
class TripsController < ApplicationController before_action :set_trip, only: [:show, :update, :destroy, :edit] def index if current_user @created_trips = current_user.created_trips @joined_trips = current_user.trips else @trips = Trip.order(:start_at).limit(25) end end def new @trip = Trip.new end def create @trip = Trip.new(trip_params) @trip.user_id = current_user.id if @trip.save redirect_to @trip else redirect_to '/' end end def show #For Mapbox @coord = [[@trip.destination.lat, @trip.destination.lng], [@trip.origin.lat, @trip.origin.lng]] respond_to do |format| format.html format.json { render json: @coord } end end private def set_trip @trip = Trip.find(params[:id]) end def trip_params params.require(:trip).permit(:origin_id, :destination_id, :start_at, :end_at) end end
willot/raft-new
app/controllers/trips_controller.rb
Ruby
mit
952
module RedditKit class Client # Methods for searching reddit's links. module Search # Search for links. # # @param query [String] The search query. # @option options [String, RedditKit::Subreddit] subreddit The optional subreddit to search. # @option options [true, false] restrict_to_subreddit Whether to search only in a specified subreddit. # @option options [1..100] limit The number of links to return. # @option options [String] count The number of results to return before or after. This is different from `limit`. # @option options [relevance, new, hot, top, comments] sort The sorting order for search results. # @option options [String] before Only return links before this full name. # @option options [String] after Only return links after this full name. # @option options [cloudsearch, lucene, plain] syntax Specify the syntax for the search. Learn more: http://www.reddit.com/r/redditdev/comments/1hpicu/whats_this_syntaxcloudsearch_do/cawm0fe # @option options [hour, day, week, month, year, all] time Show results with a specific time period. # @return [RedditKit::PaginatedResponse] def search(query, options = {}) path = "%s/search.json" % ('r/' + options[:subreddit] if options[:subreddit]) parameters = { :q => query, :restrict_sr => options[:restrict_to_subreddit], :limit => options[:limit], :count => options[:count], :sort => options[:sort], :before => options[:before], :after => options[:after], :syntax => options[:syntax], :t => options[:time] } objects_from_response(:get, path, parameters) end end end end
samsymons/RedditKit.rb
lib/redditkit/client/search.rb
Ruby
mit
1,908
//APP var app = angular.module('PortfolioApp', ['ngRoute', 'slick']); //ROUTING app.config(function ($routeProvider) { "ngInject"; $routeProvider .when('/', { controller: "HomeController", templateUrl: "js/angular/views/home-view.html" }) .when('/work/:projectId', { controller: 'ProjectController', templateUrl: 'js/angular/views/project-view.html' }) .otherwise({ redirectTo: '/' }); }); //CONTROLLERS app.controller('HomeController', ['$scope', 'projects', function($scope, projects) { "ngInject"; projects.success(function(data) { $scope.projects = data; }); //init function for binding function bindListeners() { $("header").on("click", ".mobile-toggle", function() { $(this).toggleClass("active"); }) $("header, .about").on("click", ".nav-link", function(e) { e.preventDefault(); e.stopImmediatePropagation(); if($(window).width() <= 740) $(".mobile-toggle").removeClass("active"); var anchor = $(this).attr("href"); $('html, body').animate({ scrollTop: $(anchor).offset().top - 70 }, 500); }) } //Home page initializations angular.element(document).ready(function () { bindListeners(); }); }]); app.controller('ProjectController', ['$scope', '$routeParams', '$http', function($scope, $routeParams, $http, $sce) { "ngInject"; $scope.video = false; $http.get('projects/' + $routeParams.projectId + '.json').success(function(data) { $scope.detail = data; }) .error(function(data) { console.log("Failed to get data") }); } ]); //SERVICES app.factory('projects', ['$http', function($http) { "ngInject"; return $http.get('projects/project-list.json') .success(function(data) { return data; }) .error(function(data) { return data; console.log("Failed to get data") }); }]); //FILTERS app.filter('safe', function($sce) { "ngInject"; return function(val) { return $sce.trustAsHtml(val); }; });
michael-eightnine/frontend-portfolio
site/js/angular/app.js
JavaScript
mit
1,907
// Copyright (c) 2018 Louis Wu // 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.Threading; namespace Unicorn { public static class CancellationTokenSourceExtensions { public static void CancelAndDispose(this CancellationTokenSource cancellationTokenSource) { if (cancellationTokenSource == null) { return; } try { cancellationTokenSource.Cancel(); cancellationTokenSource.Dispose(); } catch (ObjectDisposedException) { } catch (AggregateException) { } } } }
FatJohn/UnicornToolkit
Library/Unicorn.Shared/Extension/CancellationTokenSourceExtensions.cs
C#
mit
1,739
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content="Creative One Page Parallax Template"> <meta name="keywords" content="Creative, Onepage, Parallax, HTML5, Bootstrap, Popular, custom, personal, portfolio" /> <meta name="author" content=""> <title>Sistem Monitoring KP - Sisfor ITS</title> <link href="<?php echo base_url().'/asset_umum/css/bootstrap.min.css';?>" rel="stylesheet"> <link href="<?php echo base_url().'/asset_umum/css/prettyPhoto.css';?>" rel="stylesheet"> <link href="<?php echo base_url().'/asset_umum/css/font-awesome.min.css';?>" rel="stylesheet"> <link href="<?php echo base_url().'/asset_umum/css/animate.css';?>" rel="stylesheet"> <link href="<?php echo base_url().'/asset_umum/css/main.css';?>" rel="stylesheet"> <link href="<?php echo base_url().'/asset_umum/css/responsive.css';?>" rel="stylesheet"> <!--[if lt IE 9]> <script src="js/html5shiv.js"></script> <script src="js/respond.min.js"></script> <![endif]--> <link rel="shortcut icon" href="images/ico/favicon.png"> <link rel="apple-touch-icon-precomposed" sizes="144x144" href="<?php echo base_url().'/asset_umum/images/ico/apple-touch-icon-144-precomposed.png';?>"> <link rel="apple-touch-icon-precomposed" sizes="114x114" href="<?php echo base_url().'/asset_umum/images/ico/apple-touch-icon-114-precomposed.png';?>"> <link rel="apple-touch-icon-precomposed" sizes="72x72" href="<?php echo base_url().'/asset_umum/images/ico/apple-touch-icon-72-precomposed.png';?>"> <link rel="apple-touch-icon-precomposed" href="<?php echo base_url().'/asset_umum/images/ico/apple-touch-icon-57-precomposed.png';?>"> </head><!--/head--> <body> <div class="preloader"> <div class="preloder-wrap"> <div class="preloder-inner"> <div class="ball"></div> <div class="ball"></div> <div class="ball"></div> <div class="ball"></div> <div class="ball"></div> <div class="ball"></div> <div class="ball"></div> </div> </div> </div><!--/.preloader--> <header id="navigation"> <div class="navbar navbar-inverse navbar-fixed-top" role="banner"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#navigation"><h1><img src="<?php echo base_url().'/asset_umum/images/logo1.png';?>" alt="logo"></h1></a> </div> <div class="collapse navbar-collapse"> <ul class="nav navbar-nav navbar-right"> <li class="scroll active"><a href="#navigation">Home</a></li> <li class="scroll"><a href="<?php echo base_url('index.php/c_user/lapor');?>">Laporan</a></li> <li class="scroll"><a href="#history">History</a></li> <li class="scroll"><a href="#contact">Contact</a></li> <li class="scroll"><a href="<?php echo base_url('index.php/c_user/logout');?>">Logout</a></li> </ul> </div> </div> </div><!--/navbar--> </header> <!--/#navigation--> <section id="home"> <div class="home-pattern"></div> <div id="main-carousel" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> <li data-target="#main-carousel" data-slide-to="0" class="active"></li> <li data-target="#main-carousel" data-slide-to="1"></li> <li data-target="#main-carousel" data-slide-to="2"></li> </ol><!--/.carousel-indicators--> <div class="carousel-inner"> <div class="item active" style="background-image: url(<?php echo base_url().'/asset_umum/images/slider/s1.jpg';?>)"> <div class="carousel-caption"> <div> <h2 class="heading animated bounceInDown">Institut Teknologi Sepuluh Nopember</h2> <p class="animated bounceInUp">Information Systems Department</p> </div> </div> </div> <div class="item" style="background-image: url(<?php echo base_url().'asset_umum/images/slider/s2.jpg';?>)"> <div class="carousel-caption"> <div> <h2 class="heading animated bounceInDown"><span>Sistem Monitoring KP</span></h2> <p class="animated bounceInUp">Sistem terintegrasi untuk mahasiswa Sistem Informasi</p> </div> </div> </div> <div class="item" style="background-image: url(<?php echo base_url().'asset_umum/images/slider/s3.jpg';?>)"> <div class="carousel-caption"> <div> <h2 class="heading animated bounceInRight">Create and Submit!</h2> <p class="animated bounceInLeft">Mudah dan praktis digunakan</p> <a class="btn btn-default slider-btn animated bounceInUp" href="<?php echo base_url('index.php/c_user/logout');?>">Get Started</a> </div> </div> </div> </div><!--/.carousel-inner--> <a class="carousel-left member-carousel-control hidden-xs" href="#main-carousel" data-slide="prev"><i class="fa fa-angle-left"></i></a> <a class="carousel-right member-carousel-control hidden-xs" href="#main-carousel" data-slide="next"><i class="fa fa-angle-right"></i></a> </div> </section><!--/#home--> <section id="history"> <div class="container"> <div class="row text-center clearfix"> <div class="col-sm-8 col-sm-offset-2"> <h2 class="title-one">History</h2> <p class="blog-heading">Historis pengumpulan laporan KP</p> </div> </div> <div class="row"> <div class="col-sm-4"> <div class="single-blog"> <img src="images/blog/1.jpg" alt="" /> <h2>Lorem ipsum dolor sit amet</h2> <ul class="post-meta"> <li><i class="fa fa-pencil-square-o"></i><strong> Posted By:</strong> John</li> <li><i class="fa fa-clock-o"></i><strong> Posted On:</strong> Apr 15 2014</li> </ul> <div class="blog-content"> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p> </div> <a href="" class="btn btn-primary" data-toggle="modal" data-target="#blog-detail">Read More</a> </div> <div class="modal fade" id="blog-detail" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-body"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> <img src="images/blog/3.jpg" alt="" /> <h2>Lorem ipsum dolor sit amet</h2> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p><p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p> </div> </div> </div> </div> </div> <div class="col-sm-4"> <div class="single-blog"> <img src="images/blog/2.jpg" alt="" /> <h2>Lorem ipsum dolor sit amet</h2> <ul class="post-meta"> <li><i class="fa fa-pencil-square-o"></i><strong> Posted By:</strong> John</li> <li><i class="fa fa-clock-o"></i><strong> Posted On:</strong> Apr 15 2014</li> </ul> <div class="blog-content"> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p> </div> <a href="" class="btn btn-primary" data-toggle="modal" data-target="#blog-two">Read More</a> </div> <div class="modal fade" id="blog-two" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-body"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> <img src="images/blog/2.jpg" alt="" /> <h2>Lorem ipsum dolor sit amet</h2> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p><p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p> </div> </div> </div> </div> </div> <div class="col-sm-4"> <div class="single-blog"> <img src="images/blog/3.jpg" alt="" /> <h2>Lorem ipsum dolor sit amet</h2> <ul class="post-meta"> <li><i class="fa fa-pencil-square-o"></i><strong> Posted By:</strong> John</li> <li><i class="fa fa-clock-o"></i><strong> Posted On:</strong> Apr 15 2014</li> </ul> <div class="blog-content"> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p> </div> <a href="" class="btn btn-primary" data-toggle="modal" data-target="#blog-three">Read More</a> </div> <div class="modal fade" id="blog-three" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-body"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> <img src="images/blog/3.jpg" alt="" /> <h2>Lorem ipsum dolor sit amet</h2> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p><p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p> </div> </div> </div> </div> </div> <div class="col-sm-4"> <div class="single-blog"> <img src="images/blog/3.jpg" alt="" /> <h2>Lorem ipsum dolor sit amet</h2> <ul class="post-meta"> <li><i class="fa fa-pencil-square-o"></i><strong> Posted By:</strong> John</li> <li><i class="fa fa-clock-o"></i><strong> Posted On:</strong> Apr 15 2014</li> </ul> <div class="blog-content"> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p> </div> <a href="" class="btn btn-primary" data-toggle="modal" data-target="#blog-four">Read More</a></div> <div class="modal fade" id="blog-four" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-body"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> <img src="images/blog/3.jpg" alt="" /> <h2>Lorem ipsum dolor sit amet</h2> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p><p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p> </div> </div> </div> </div> </div> <div class="col-sm-4"> <div class="single-blog"> <img src="images/blog/2.jpg" alt="" /> <h2>Lorem ipsum dolor sit amet</h2> <ul class="post-meta"> <li><i class="fa fa-pencil-square-o"></i><strong> Posted By:</strong> John</li> <li><i class="fa fa-clock-o"></i><strong> Posted On:</strong> Apr 15 2014</li> </ul> <div class="blog-content"> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p> </div> <a href="" class="btn btn-primary" data-toggle="modal" data-target="#blog-six">Read More</a> </div> <div class="modal fade" id="blog-six" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-body"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> <img src="images/blog/2.jpg" alt="" /> <h2>Lorem ipsum dolor sit amet</h2> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p><p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p> </div> </div> </div> </div> </div> <div class="col-sm-4"> <div class="single-blog"> <img src="images/blog/1.jpg" alt="" /> <h2>Lorem ipsum dolor sit amet</h2> <ul class="post-meta"> <li><i class="fa fa-pencil-square-o"></i><strong> Posted By:</strong> John</li> <li><i class="fa fa-clock-o"></i><strong> Posted On:</strong> Apr 15 2014</li> </ul> <div class="blog-content"> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p> </div> <a href="" class="btn btn-primary" data-toggle="modal" data-target="#blog-seven">Read More</a> </div> <div class="modal fade" id="blog-seven" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-body"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> <img src="images/blog/1.jpg" alt="" /> <h2>Lorem ipsum dolor sit amet</h2> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p><p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p> </div> </div> </div> </div> </div> </div> </div> </section> <!--/#blog--> <section id="contact"> <div class="container"> <div class="row text-center clearfix"> <div class="col-sm-8 col-sm-offset-2"> <div class="contact-heading"> <h2 class="title-one">Contact With Us</h2> <p></p> </div> </div> </div> </div> <div class="container"> <div class="contact-details"> <div class="pattern"></div> <div class="row text-center clearfix"> <div class="col-sm-6"> <div class="contact-address"> <address><p><span>Departemen </span>Sistem Informasi</p><strong> Sekretariat <br> Lt. 2 Gd. Lama FTIf ITS <br> Institut Teknologi Sepuluh Nopember, Sukolilo <br> Surabaya, 60111 <br> Indonesia <br> Phone: +62 31 5999944 <br> </strong> </address> </div> </div> <div class="col-sm-6"> <div id="contact-details"> <div class="status alert alert-success" style="display: none"></div> <div class="contact-address"><address><p>Sisfor <span>KP</span></p><strong>Jam Buka : 08.00-16.00<br> +62 31 5999944</strong><br></address> <div class="social-icons"> <a href="https://ms-my.facebook.com/pages/Jurusan-Sistem-Informasi-ITS/149235835122966" class="facebook external" data-animate-hover="shake"><i class="fa fa-facebook"></i></a> <a href="https://www.instagram.com/hmsi_its/" class="instagram external" data-animate-hover="shake"><i class="fa fa-instagram"></i></a> <a href="https://mail.google.com/mail/?view=cm&fs=1&tf=1&to=jurusan@is.its.ac.id&su=Hello&shva=1" class="email external" data-animate-hover="shake"><i class="fa fa-envelope"></i></a> </div> </div> </div> </div> </div> </div> </div> </section> <!--/#contact--> <footer id="footer"> <div class="container"> <div class="text-center"> <p>Copyright &copy; 2017 - <a href="http://is.its.ac.id/">Information System Department</a> | ITS </p> </div> </div> </footer> <!--/#footer--> <script type="text/javascript" src="<?php echo base_url().'/asset_umum/js/jquery.js';?>"></script> <script type="text/javascript" src="<?php echo base_url().'/asset_umum/js/bootstrap.min.js';?>"></script> <script type="text/javascript" src="<?php echo base_url().'/asset_umum/js/smoothscroll.js';?>"></script> <script type="text/javascript" src="<?php echo base_url().'/asset_umum/js/jquery.isotope.min.js';?>"></script> <script type="text/javascript" src="<?php echo base_url().'/asset_umum/js/jquery.prettyPhoto.js';?>"></script> <script type="text/javascript" src="<?php echo base_url().'/asset_umum/js/jquery.parallax.js';?>"></script> <script type="text/javascript" src="<?php echo base_url().'/asset_umum/js/main.js';?>"></script> </body> </html>
dinanandka/MonitoringKP_KPPL
application/views/welcome.php
PHP
mit
21,424
# CoreDataHelpers
tschmitz/CoreDataHelpers
README.md
Markdown
mit
18
let original: (fn: FrameRequestCallback) => number; let requesters: any[] = []; function fakeRaf(fn: FrameRequestCallback): number { requesters.push(fn); return requesters.length; } function use() { original = window.requestAnimationFrame; window.requestAnimationFrame = fakeRaf; } function restore() { setTimeout(() => { window.requestAnimationFrame = original; }, 2000); } function step() { let cur = requesters; requesters = []; cur.forEach(function(f) { return f(16); }); } export default { use, restore, step, };
motorcyclejs/dom
test/helpers/fake-raf.ts
TypeScript
mit
552
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MotoBotCore.Interfaces { public interface IChannel { string Name { get; set; } string Motd { get; set; } } }
luetm/MotoBot
MotoBotCore/Interfaces/IChannel.cs
C#
mit
267
//----------------------------------------------------------------------------- // Декодер Mpeg Layer 1,2,3 // Копонент звукового двигателя Шквал // команда : AntiTank // разработчик : Гилязетдинов Марат (Марыч) //----------------------------------------------------------------------------- // включения #include <string.h> #include <math.h> #include "MpegDecoder.h" void CDecompressMpeg::imdct_init() { int k, p, n; double t, pi; n = 18; pi = 4.0 * atan(1.0); t = pi / (4 * n); for (p = 0; p < n; p++) w[p] = (float) (2.0 * cos(t * (2 * p + 1))); for (p = 0; p < 9; p++) w2[p] = (float) (2.0 * cos(2 * t * (2 * p + 1))); t = pi / (2 * n); for (k = 0; k < 9; k++) { for (p = 0; p < 4; p++) coef[k][p] = (float) (cos(t * (2 * k) * (2 * p + 1))); } n = 6; pi = 4.0 * atan(1.0); t = pi / (4 * n); for (p = 0; p < n; p++) v[p] = (float) (2.0 * cos(t * (2 * p + 1))); for (p = 0; p < 3; p++) v2[p] = (float) (2.0 * cos(2 * t * (2 * p + 1))); t = pi / (2 * n); k = 1; p = 0; coef87 = (float) (cos(t * (2 * k) * (2 * p + 1))); for (p = 0; p < 6; p++) v[p] = v[p] / 2.0f; coef87 = (float) (2.0 * coef87); } void CDecompressMpeg::imdct18(float f[18]) /* 18 point */ { int p; float a[9], b[9]; float ap, bp, a8p, b8p; float g1, g2; for (p = 0; p < 4; p++) { g1 = w[p] * f[p]; g2 = w[17 - p] * f[17 - p]; ap = g1 + g2; // a[p] bp = w2[p] * (g1 - g2); // b[p] g1 = w[8 - p] * f[8 - p]; g2 = w[9 + p] * f[9 + p]; a8p = g1 + g2; // a[8-p] b8p = w2[8 - p] * (g1 - g2); // b[8-p] a[p] = ap + a8p; a[5 + p] = ap - a8p; b[p] = bp + b8p; b[5 + p] = bp - b8p; } g1 = w[p] * f[p]; g2 = w[17 - p] * f[17 - p]; a[p] = g1 + g2; b[p] = w2[p] * (g1 - g2); f[0] = 0.5f * (a[0] + a[1] + a[2] + a[3] + a[4]); f[1] = 0.5f * (b[0] + b[1] + b[2] + b[3] + b[4]); f[2] = coef[1][0] * a[5] + coef[1][1] * a[6] + coef[1][2] * a[7] + coef[1][3] * a[8]; f[3] = coef[1][0] * b[5] + coef[1][1] * b[6] + coef[1][2] * b[7] + coef[1][3] * b[8] - f[1]; f[1] = f[1] - f[0]; f[2] = f[2] - f[1]; f[4] = coef[2][0] * a[0] + coef[2][1] * a[1] + coef[2][2] * a[2] + coef[2][3] * a[3] - a[4]; f[5] = coef[2][0] * b[0] + coef[2][1] * b[1] + coef[2][2] * b[2] + coef[2][3] * b[3] - b[4] - f[3]; f[3] = f[3] - f[2]; f[4] = f[4] - f[3]; f[6] = coef[3][0] * (a[5] - a[7] - a[8]); f[7] = coef[3][0] * (b[5] - b[7] - b[8]) - f[5]; f[5] = f[5] - f[4]; f[6] = f[6] - f[5]; f[8] = coef[4][0] * a[0] + coef[4][1] * a[1] + coef[4][2] * a[2] + coef[4][3] * a[3] + a[4]; f[9] = coef[4][0] * b[0] + coef[4][1] * b[1] + coef[4][2] * b[2] + coef[4][3] * b[3] + b[4] - f[7]; f[7] = f[7] - f[6]; f[8] = f[8] - f[7]; f[10] = coef[5][0] * a[5] + coef[5][1] * a[6] + coef[5][2] * a[7] + coef[5][3] * a[8]; f[11] = coef[5][0] * b[5] + coef[5][1] * b[6] + coef[5][2] * b[7] + coef[5][3] * b[8] - f[9]; f[9] = f[9] - f[8]; f[10] = f[10] - f[9]; f[12] = 0.5f * (a[0] + a[2] + a[3]) - a[1] - a[4]; f[13] = 0.5f * (b[0] + b[2] + b[3]) - b[1] - b[4] - f[11]; f[11] = f[11] - f[10]; f[12] = f[12] - f[11]; f[14] = coef[7][0] * a[5] + coef[7][1] * a[6] + coef[7][2] * a[7] + coef[7][3] * a[8]; f[15] = coef[7][0] * b[5] + coef[7][1] * b[6] + coef[7][2] * b[7] + coef[7][3] * b[8] - f[13]; f[13] = f[13] - f[12]; f[14] = f[14] - f[13]; f[16] = coef[8][0] * a[0] + coef[8][1] * a[1] + coef[8][2] * a[2] + coef[8][3] * a[3] + a[4]; f[17] = coef[8][0] * b[0] + coef[8][1] * b[1] + coef[8][2] * b[2] + coef[8][3] * b[3] + b[4] - f[15]; f[15] = f[15] - f[14]; f[16] = f[16] - f[15]; f[17] = f[17] - f[16]; } /*--------------------------------------------------------------------*/ /* does 3, 6 pt dct. changes order from f[i][window] c[window][i] */ void CDecompressMpeg::imdct6_3(float f[]) /* 6 point */ { int w; float buf[18]; float* a,* c; // b[i] = a[3+i] float g1, g2; float a02, b02; c = f; a = buf; for (w = 0; w < 3; w++) { g1 = v[0] * f[3 * 0]; g2 = v[5] * f[3 * 5]; a[0] = g1 + g2; a[3 + 0] = v2[0] * (g1 - g2); g1 = v[1] * f[3 * 1]; g2 = v[4] * f[3 * 4]; a[1] = g1 + g2; a[3 + 1] = v2[1] * (g1 - g2); g1 = v[2] * f[3 * 2]; g2 = v[3] * f[3 * 3]; a[2] = g1 + g2; a[3 + 2] = v2[2] * (g1 - g2); a += 6; f++; } a = buf; for (w = 0; w < 3; w++) { a02 = (a[0] + a[2]); b02 = (a[3 + 0] + a[3 + 2]); c[0] = a02 + a[1]; c[1] = b02 + a[3 + 1]; c[2] = coef87 * (a[0] - a[2]); c[3] = coef87 * (a[3 + 0] - a[3 + 2]) - c[1]; c[1] = c[1] - c[0]; c[2] = c[2] - c[1]; c[4] = a02 - a[1] - a[1]; c[5] = b02 - a[3 + 1] - a[3 + 1] - c[3]; c[3] = c[3] - c[2]; c[4] = c[4] - c[3]; c[5] = c[5] - c[4]; a += 6; c += 6; } } void CDecompressMpeg::fdct_init() /* gen coef for N=32 (31 coefs) */ { int p, n, i, k; double t, pi; pi = 4.0 * atan(1.0); n = 16; k = 0; for (i = 0; i < 5; i++, n = n / 2) { for (p = 0; p < n; p++, k++) { t = (pi / (4 * n)) * (2 * p + 1); coef32[k] = (float) (0.50 / cos(t)); } } } void CDecompressMpeg::forward_bf(int m, int n, float x[], float f[], float coef[]) { int i, j, n2; int p, q, p0, k; p0 = 0; n2 = n >> 1; for (i = 0; i < m; i++, p0 += n) { k = 0; p = p0; q = p + n - 1; for (j = 0; j < n2; j++, p++, q--, k++) { f[p] = x[p] + x[q]; f[n2 + p] = coef[k] * (x[p] - x[q]); } } } void CDecompressMpeg::back_bf(int m, int n, float x[], float f[]) { int i, j, n2, n21; int p, q, p0; p0 = 0; n2 = n >> 1; n21 = n2 - 1; for (i = 0; i < m; i++, p0 += n) { p = p0; q = p0; for (j = 0; j < n2; j++, p += 2, q++) f[p] = x[q]; p = p0 + 1; for (j = 0; j < n21; j++, p += 2, q++) f[p] = x[q] + x[q + 1]; f[p] = x[q]; } } void CDecompressMpeg::fdct32(float x[], float c[]) { float a[32]; /* ping pong buffers */ float b[32]; int p, q; // если эквалайзер включен занести значения /* if (m_enableEQ) { for (p = 0; p < 32; p++) x[p] *= m_equalizer[p]; }*/ /* special first stage */ for (p = 0, q = 31; p < 16; p++, q--) { a[p] = x[p] + x[q]; a[16 + p] = coef32[p] * (x[p] - x[q]); } forward_bf(2, 16, a, b, coef32 + 16); forward_bf(4, 8, b, a, coef32 + 16 + 8); forward_bf(8, 4, a, b, coef32 + 16 + 8 + 4); forward_bf(16, 2, b, a, coef32 + 16 + 8 + 4 + 2); back_bf(8, 4, a, b); back_bf(4, 8, b, a); back_bf(2, 16, a, b); back_bf(1, 32, b, c); } void CDecompressMpeg::fdct32_dual(float x[], float c[]) { float a[32]; /* ping pong buffers */ float b[32]; int p, pp, qq; /* if (m_enableEQ) { for (p = 0; p < 32; p++) x[p] *= m_equalizer[p]; }*/ /* special first stage for dual chan (interleaved x) */ pp = 0; qq = 2 * 31; for (p = 0; p < 16; p++, pp += 2, qq -= 2) { a[p] = x[pp] + x[qq]; a[16 + p] = coef32[p] * (x[pp] - x[qq]); } forward_bf(2, 16, a, b, coef32 + 16); forward_bf(4, 8, b, a, coef32 + 16 + 8); forward_bf(8, 4, a, b, coef32 + 16 + 8 + 4); forward_bf(16, 2, b, a, coef32 + 16 + 8 + 4 + 2); back_bf(8, 4, a, b); back_bf(4, 8, b, a); back_bf(2, 16, a, b); back_bf(1, 32, b, c); } void CDecompressMpeg::fdct32_dual_mono(float x[], float c[]) { float a[32]; /* ping pong buffers */ float b[32]; float t1, t2; int p, pp, qq; /* special first stage */ pp = 0; qq = 2 * 31; for (p = 0; p < 16; p++, pp += 2, qq -= 2) { t1 = 0.5F * (x[pp] + x[pp + 1]); t2 = 0.5F * (x[qq] + x[qq + 1]); a[p] = t1 + t2; a[16 + p] = coef32[p] * (t1 - t2); } forward_bf(2, 16, a, b, coef32 + 16); forward_bf(4, 8, b, a, coef32 + 16 + 8); forward_bf(8, 4, a, b, coef32 + 16 + 8 + 4); forward_bf(16, 2, b, a, coef32 + 16 + 8 + 4 + 2); back_bf(8, 4, a, b); back_bf(4, 8, b, a); back_bf(2, 16, a, b); back_bf(1, 32, b, c); } void CDecompressMpeg::fdct16(float x[], float c[]) { float a[16]; /* ping pong buffers */ float b[16]; int p, q; /* special first stage (drop highest sb) */ a[0] = x[0]; a[8] = coef32[16] * x[0]; for (p = 1, q = 14; p < 8; p++, q--) { a[p] = x[p] + x[q]; a[8 + p] = coef32[16 + p] * (x[p] - x[q]); } forward_bf(2, 8, a, b, coef32 + 16 + 8); forward_bf(4, 4, b, a, coef32 + 16 + 8 + 4); forward_bf(8, 2, a, b, coef32 + 16 + 8 + 4 + 2); back_bf(4, 4, b, a); back_bf(2, 8, a, b); back_bf(1, 16, b, c); } void CDecompressMpeg::fdct16_dual(float x[], float c[]) { float a[16]; /* ping pong buffers */ float b[16]; int p, pp, qq; /* special first stage for interleaved input */ a[0] = x[0]; a[8] = coef32[16] * x[0]; pp = 2; qq = 2 * 14; for (p = 1; p < 8; p++, pp += 2, qq -= 2) { a[p] = x[pp] + x[qq]; a[8 + p] = coef32[16 + p] * (x[pp] - x[qq]); } forward_bf(2, 8, a, b, coef32 + 16 + 8); forward_bf(4, 4, b, a, coef32 + 16 + 8 + 4); forward_bf(8, 2, a, b, coef32 + 16 + 8 + 4 + 2); back_bf(4, 4, b, a); back_bf(2, 8, a, b); back_bf(1, 16, b, c); } void CDecompressMpeg::fdct16_dual_mono(float x[], float c[]) { float a[16]; /* ping pong buffers */ float b[16]; float t1, t2; int p, pp, qq; /* special first stage */ a[0] = 0.5F * (x[0] + x[1]); a[8] = coef32[16] * a[0]; pp = 2; qq = 2 * 14; for (p = 1; p < 8; p++, pp += 2, qq -= 2) { t1 = 0.5F * (x[pp] + x[pp + 1]); t2 = 0.5F * (x[qq] + x[qq + 1]); a[p] = t1 + t2; a[8 + p] = coef32[16 + p] * (t1 - t2); } forward_bf(2, 8, a, b, coef32 + 16 + 8); forward_bf(4, 4, b, a, coef32 + 16 + 8 + 4); forward_bf(8, 2, a, b, coef32 + 16 + 8 + 4 + 2); back_bf(4, 4, b, a); back_bf(2, 8, a, b); back_bf(1, 16, b, c); } void CDecompressMpeg::fdct8(float x[], float c[]) { float a[8]; /* ping pong buffers */ float b[8]; int p, q; /* special first stage */ b[0] = x[0] + x[7]; b[4] = coef32[16 + 8] * (x[0] - x[7]); for (p = 1, q = 6; p < 4; p++, q--) { b[p] = x[p] + x[q]; b[4 + p] = coef32[16 + 8 + p] * (x[p] - x[q]); } forward_bf(2, 4, b, a, coef32 + 16 + 8 + 4); forward_bf(4, 2, a, b, coef32 + 16 + 8 + 4 + 2); back_bf(2, 4, b, a); back_bf(1, 8, a, c); } void CDecompressMpeg::fdct8_dual(float x[], float c[]) { float a[8]; /* ping pong buffers */ float b[8]; int p, pp, qq; /* special first stage for interleaved input */ b[0] = x[0] + x[14]; b[4] = coef32[16 + 8] * (x[0] - x[14]); pp = 2; qq = 2 * 6; for (p = 1; p < 4; p++, pp += 2, qq -= 2) { b[p] = x[pp] + x[qq]; b[4 + p] = coef32[16 + 8 + p] * (x[pp] - x[qq]); } forward_bf(2, 4, b, a, coef32 + 16 + 8 + 4); forward_bf(4, 2, a, b, coef32 + 16 + 8 + 4 + 2); back_bf(2, 4, b, a); back_bf(1, 8, a, c); } void CDecompressMpeg::fdct8_dual_mono(float x[], float c[]) { float a[8]; /* ping pong buffers */ float b[8]; float t1, t2; int p, pp, qq; /* special first stage */ t1 = 0.5F * (x[0] + x[1]); t2 = 0.5F * (x[14] + x[15]); b[0] = t1 + t2; b[4] = coef32[16 + 8] * (t1 - t2); pp = 2; qq = 2 * 6; for (p = 1; p < 4; p++, pp += 2, qq -= 2) { t1 = 0.5F * (x[pp] + x[pp + 1]); t2 = 0.5F * (x[qq] + x[qq + 1]); b[p] = t1 + t2; b[4 + p] = coef32[16 + 8 + p] * (t1 - t2); } forward_bf(2, 4, b, a, coef32 + 16 + 8 + 4); forward_bf(4, 2, a, b, coef32 + 16 + 8 + 4 + 2); back_bf(2, 4, b, a); back_bf(1, 8, a, c); } void CDecompressMpeg::bitget_init(unsigned char* buf) { bs_ptr0 = bs_ptr = buf; bits = 0; bitbuf = 0; } int CDecompressMpeg::bitget(int n) { unsigned int x; if (bits < n) { /* refill bit buf if necessary */ while (bits <= 24) { bitbuf = (bitbuf << 8) | *bs_ptr++; bits += 8; } } bits -= n; x = bitbuf >> bits; bitbuf -= x << bits; return x; } void CDecompressMpeg::bitget_skip(int n) { unsigned int k; if (bits < n) { n -= bits; k = n >> 3; /*--- bytes = n/8 --*/ bs_ptr += k; n -= k << 3; bitbuf = *bs_ptr++; bits = 8; } bits -= n; bitbuf -= (bitbuf >> bits) << bits; } void CDecompressMpeg::bitget_init_end(unsigned char* buf_end) { bs_ptr_end = buf_end; } int CDecompressMpeg::bitget_overrun() { return bs_ptr > bs_ptr_end; } int CDecompressMpeg::bitget_bits_used() { unsigned int n; n = ((bs_ptr - bs_ptr0) << 3) - bits; return n; } void CDecompressMpeg::bitget_check(int n) { if (bits < n) { while (bits <= 24) { bitbuf = (bitbuf << 8) | *bs_ptr++; bits += 8; } } } /* only huffman */ /*----- get n bits - checks for n+2 avail bits (linbits+sign) -----*/ int CDecompressMpeg::bitget_lb(int n) { unsigned int x; if (bits < (n + 2)) { /* refill bit buf if necessary */ while (bits <= 24) { bitbuf = (bitbuf << 8) | *bs_ptr++; bits += 8; } } bits -= n; x = bitbuf >> bits; bitbuf -= x << bits; return x; } /*------------- get n bits but DO NOT remove from bitstream --*/ int CDecompressMpeg::bitget2(int n) { unsigned int x; if (bits < (MAXBITS + 2)) { /* refill bit buf if necessary */ while (bits <= 24) { bitbuf = (bitbuf << 8) | *bs_ptr++; bits += 8; } } x = bitbuf >> (bits - n); return x; } /*------------- remove n bits from bitstream ---------*/ void CDecompressMpeg::bitget_purge(int n) { bits -= n; bitbuf -= (bitbuf >> bits) << bits; } void CDecompressMpeg::mac_bitget_check(int n) { if (bits < n) { while (bits <= 24) { bitbuf = (bitbuf << 8) | *bs_ptr++; bits += 8; } } } int CDecompressMpeg::mac_bitget(int n) { unsigned int code; bits -= n; code = bitbuf >> bits; bitbuf -= code << bits; return code; } int CDecompressMpeg::mac_bitget2(int n) { return (bitbuf >> (bits - n)); } int CDecompressMpeg::mac_bitget_1bit() { unsigned int code; bits--; code = bitbuf >> bits; bitbuf -= code << bits; return code; } void CDecompressMpeg::mac_bitget_purge(int n) { bits -= n; bitbuf -= (bitbuf >> bits) << bits; } void CDecompressMpeg::windowB(float* vbuf, int vb_ptr, unsigned char* pcm) { int i, j; int si, bx; float* coef; float sum; long tmp; si = vb_ptr + 16; bx = (si + 32) & 511; coef = wincoef; /*-- first 16 --*/ for (i = 0; i < 16; i++) { sum = 0.0F; for (j = 0; j < 8; j++) { sum += (*coef++) * vbuf[si]; si = (si + 64) & 511; sum -= (*coef++) * vbuf[bx]; bx = (bx + 64) & 511; } si++; bx--; tmp = (long) sum; if (tmp > 32767) tmp = 32767; else if (tmp < -32768) tmp = -32768; *pcm++ = ((unsigned char) (tmp >> 8)) ^ 0x80; } /*-- special case --*/ sum = 0.0F; for (j = 0; j < 8; j++) { sum += (*coef++) * vbuf[bx]; bx = (bx + 64) & 511; } tmp = (long) sum; if (tmp > 32767) tmp = 32767; else if (tmp < -32768) tmp = -32768; *pcm++ = ((unsigned char) (tmp >> 8)) ^ 0x80; /*-- last 15 --*/ coef = wincoef + 255; /* back pass through coefs */ for (i = 0; i < 15; i++) { si--; bx++; sum = 0.0F; for (j = 0; j < 8; j++) { sum += (*coef--) * vbuf[si]; si = (si + 64) & 511; sum += (*coef--) * vbuf[bx]; bx = (bx + 64) & 511; } tmp = (long) sum; if (tmp > 32767) tmp = 32767; else if (tmp < -32768) tmp = -32768; *pcm++ = ((unsigned char) (tmp >> 8)) ^ 0x80; } } void CDecompressMpeg::windowB_dual(float* vbuf, int vb_ptr, unsigned char* pcm) { int i, j; /* dual window interleaves output */ int si, bx; float* coef; float sum; long tmp; si = vb_ptr + 16; bx = (si + 32) & 511; coef = wincoef; /*-- first 16 --*/ for (i = 0; i < 16; i++) { sum = 0.0F; for (j = 0; j < 8; j++) { sum += (*coef++) * vbuf[si]; si = (si + 64) & 511; sum -= (*coef++) * vbuf[bx]; bx = (bx + 64) & 511; } si++; bx--; tmp = (long) sum; if (tmp > 32767) tmp = 32767; else if (tmp < -32768) tmp = -32768; *pcm = ((unsigned char) (tmp >> 8)) ^ 0x80; pcm += 2; } /*-- special case --*/ sum = 0.0F; for (j = 0; j < 8; j++) { sum += (*coef++) * vbuf[bx]; bx = (bx + 64) & 511; } tmp = (long) sum; if (tmp > 32767) tmp = 32767; else if (tmp < -32768) tmp = -32768; *pcm = ((unsigned char) (tmp >> 8)) ^ 0x80; pcm += 2; /*-- last 15 --*/ coef = wincoef + 255; /* back pass through coefs */ for (i = 0; i < 15; i++) { si--; bx++; sum = 0.0F; for (j = 0; j < 8; j++) { sum += (*coef--) * vbuf[si]; si = (si + 64) & 511; sum += (*coef--) * vbuf[bx]; bx = (bx + 64) & 511; } tmp = (long) sum; if (tmp > 32767) tmp = 32767; else if (tmp < -32768) tmp = -32768; *pcm = ((unsigned char) (tmp >> 8)) ^ 0x80; pcm += 2; } } void CDecompressMpeg::windowB16(float* vbuf, int vb_ptr, unsigned char* pcm) { int i, j; unsigned char si, bx; float* coef; float sum; long tmp; si = vb_ptr + 8; bx = si + 16; coef = wincoef; /*-- first 8 --*/ for (i = 0; i < 8; i++) { sum = 0.0F; for (j = 0; j < 8; j++) { sum += (*coef++) * vbuf[si]; si += 32; sum -= (*coef++) * vbuf[bx]; bx += 32; } si++; bx--; coef += 16; tmp = (long) sum; if (tmp > 32767) tmp = 32767; else if (tmp < -32768) tmp = -32768; *pcm++ = ((unsigned char) (tmp >> 8)) ^ 0x80; } /*-- special case --*/ sum = 0.0F; for (j = 0; j < 8; j++) { sum += (*coef++) * vbuf[bx]; bx += 32; } tmp = (long) sum; if (tmp > 32767) tmp = 32767; else if (tmp < -32768) tmp = -32768; *pcm++ = ((unsigned char) (tmp >> 8)) ^ 0x80; /*-- last 7 --*/ coef = wincoef + 255; /* back pass through coefs */ for (i = 0; i < 7; i++) { coef -= 16; si--; bx++; sum = 0.0F; for (j = 0; j < 8; j++) { sum += (*coef--) * vbuf[si]; si += 32; sum += (*coef--) * vbuf[bx]; bx += 32; } tmp = (long) sum; if (tmp > 32767) tmp = 32767; else if (tmp < -32768) tmp = -32768; *pcm++ = ((unsigned char) (tmp >> 8)) ^ 0x80; } } void CDecompressMpeg::windowB16_dual(float* vbuf, int vb_ptr, unsigned char* pcm) { int i, j; unsigned char si, bx; float* coef; float sum; long tmp; si = vb_ptr + 8; bx = si + 16; coef = wincoef; /*-- first 8 --*/ for (i = 0; i < 8; i++) { sum = 0.0F; for (j = 0; j < 8; j++) { sum += (*coef++) * vbuf[si]; si += 32; sum -= (*coef++) * vbuf[bx]; bx += 32; } si++; bx--; coef += 16; tmp = (long) sum; if (tmp > 32767) tmp = 32767; else if (tmp < -32768) tmp = -32768; *pcm = ((unsigned char) (tmp >> 8)) ^ 0x80; pcm += 2; } /*-- special case --*/ sum = 0.0F; for (j = 0; j < 8; j++) { sum += (*coef++) * vbuf[bx]; bx += 32; } tmp = (long) sum; if (tmp > 32767) tmp = 32767; else if (tmp < -32768) tmp = -32768; *pcm = ((unsigned char) (tmp >> 8)) ^ 0x80; pcm += 2; /*-- last 7 --*/ coef = wincoef + 255; /* back pass through coefs */ for (i = 0; i < 7; i++) { coef -= 16; si--; bx++; sum = 0.0F; for (j = 0; j < 8; j++) { sum += (*coef--) * vbuf[si]; si += 32; sum += (*coef--) * vbuf[bx]; bx += 32; } tmp = (long) sum; if (tmp > 32767) tmp = 32767; else if (tmp < -32768) tmp = -32768; *pcm = ((unsigned char) (tmp >> 8)) ^ 0x80; pcm += 2; } } void CDecompressMpeg::windowB8(float* vbuf, int vb_ptr, unsigned char* pcm) { int i, j; int si, bx; float* coef; float sum; long tmp; si = vb_ptr + 4; bx = (si + 8) & 127; coef = wincoef; /*-- first 4 --*/ for (i = 0; i < 4; i++) { sum = 0.0F; for (j = 0; j < 8; j++) { sum += (*coef++) * vbuf[si]; si = (si + 16) & 127; sum -= (*coef++) * vbuf[bx]; bx = (bx + 16) & 127; } si++; bx--; coef += 48; tmp = (long) sum; if (tmp > 32767) tmp = 32767; else if (tmp < -32768) tmp = -32768; *pcm++ = ((unsigned char) (tmp >> 8)) ^ 0x80; } /*-- special case --*/ sum = 0.0F; for (j = 0; j < 8; j++) { sum += (*coef++) * vbuf[bx]; bx = (bx + 16) & 127; } tmp = (long) sum; if (tmp > 32767) tmp = 32767; else if (tmp < -32768) tmp = -32768; *pcm++ = ((unsigned char) (tmp >> 8)) ^ 0x80; /*-- last 3 --*/ coef = wincoef + 255; /* back pass through coefs */ for (i = 0; i < 3; i++) { coef -= 48; si--; bx++; sum = 0.0F; for (j = 0; j < 8; j++) { sum += (*coef--) * vbuf[si]; si = (si + 16) & 127; sum += (*coef--) * vbuf[bx]; bx = (bx + 16) & 127; } tmp = (long) sum; if (tmp > 32767) tmp = 32767; else if (tmp < -32768) tmp = -32768; *pcm++ = ((unsigned char) (tmp >> 8)) ^ 0x80; } } /*--------------- 8 pt dual window (interleaved output) -----------------*/ void CDecompressMpeg::windowB8_dual(float* vbuf, int vb_ptr, unsigned char* pcm) { int i, j; int si, bx; float* coef; float sum; long tmp; si = vb_ptr + 4; bx = (si + 8) & 127; coef = wincoef; /*-- first 4 --*/ for (i = 0; i < 4; i++) { sum = 0.0F; for (j = 0; j < 8; j++) { sum += (*coef++) * vbuf[si]; si = (si + 16) & 127; sum -= (*coef++) * vbuf[bx]; bx = (bx + 16) & 127; } si++; bx--; coef += 48; tmp = (long) sum; if (tmp > 32767) tmp = 32767; else if (tmp < -32768) tmp = -32768; *pcm = ((unsigned char) (tmp >> 8)) ^ 0x80; pcm += 2; } /*-- special case --*/ sum = 0.0F; for (j = 0; j < 8; j++) { sum += (*coef++) * vbuf[bx]; bx = (bx + 16) & 127; } tmp = (long) sum; if (tmp > 32767) tmp = 32767; else if (tmp < -32768) tmp = -32768; *pcm = ((unsigned char) (tmp >> 8)) ^ 0x80; pcm += 2; /*-- last 3 --*/ coef = wincoef + 255; /* back pass through coefs */ for (i = 0; i < 3; i++) { coef -= 48; si--; bx++; sum = 0.0F; for (j = 0; j < 8; j++) { sum += (*coef--) * vbuf[si]; si = (si + 16) & 127; sum += (*coef--) * vbuf[bx]; bx = (bx + 16) & 127; } tmp = (long) sum; if (tmp > 32767) tmp = 32767; else if (tmp < -32768) tmp = -32768; *pcm = ((unsigned char) (tmp >> 8)) ^ 0x80; pcm += 2; } } void CDecompressMpeg::sbtB_mono(float* sample, void* in_pcm, int n) { int i; unsigned char * pcm = (unsigned char *) in_pcm; for (i = 0; i < n; i++) { fdct32(sample, vbuf + vb_ptr); windowB(vbuf, vb_ptr, pcm); sample += 64; vb_ptr = (vb_ptr - 32) & 511; pcm += 32; } } void CDecompressMpeg::sbtB_dual(float* sample, void* in_pcm, int n) { int i; unsigned char * pcm = (unsigned char *) in_pcm; for (i = 0; i < n; i++) { fdct32_dual(sample, vbuf + vb_ptr); fdct32_dual(sample + 1, vbuf2 + vb_ptr); windowB_dual(vbuf, vb_ptr, pcm); windowB_dual(vbuf2, vb_ptr, pcm + 1); sample += 64; vb_ptr = (vb_ptr - 32) & 511; pcm += 64; } } void CDecompressMpeg::sbtB_dual_mono(float* sample, void* in_pcm, int n) { int i; unsigned char * pcm = (unsigned char *) in_pcm; for (i = 0; i < n; i++) { fdct32_dual_mono(sample, vbuf + vb_ptr); windowB(vbuf, vb_ptr, pcm); sample += 64; vb_ptr = (vb_ptr - 32) & 511; pcm += 32; } } void CDecompressMpeg::sbtB_dual_left(float* sample, void* in_pcm, int n) { int i; unsigned char * pcm = (unsigned char *) in_pcm; for (i = 0; i < n; i++) { fdct32_dual(sample, vbuf + vb_ptr); windowB(vbuf, vb_ptr, pcm); sample += 64; vb_ptr = (vb_ptr - 32) & 511; pcm += 32; } } void CDecompressMpeg::sbtB_dual_right(float* sample, void* in_pcm, int n) { int i; unsigned char * pcm = (unsigned char *) in_pcm; sample++; /* point to right chan */ for (i = 0; i < n; i++) { fdct32_dual(sample, vbuf + vb_ptr); windowB(vbuf, vb_ptr, pcm); sample += 64; vb_ptr = (vb_ptr - 32) & 511; pcm += 32; } } void CDecompressMpeg::sbtB16_mono(float* sample, void* in_pcm, int n) { int i; unsigned char * pcm = (unsigned char *) in_pcm; for (i = 0; i < n; i++) { fdct16(sample, vbuf + vb_ptr); windowB16(vbuf, vb_ptr, pcm); sample += 64; vb_ptr = (vb_ptr - 16) & 255; pcm += 16; } } void CDecompressMpeg::sbtB16_dual(float* sample, void* in_pcm, int n) { int i; unsigned char * pcm = (unsigned char *) in_pcm; for (i = 0; i < n; i++) { fdct16_dual(sample, vbuf + vb_ptr); fdct16_dual(sample + 1, vbuf2 + vb_ptr); windowB16_dual(vbuf, vb_ptr, pcm); windowB16_dual(vbuf2, vb_ptr, pcm + 1); sample += 64; vb_ptr = (vb_ptr - 16) & 255; pcm += 32; } } void CDecompressMpeg::sbtB16_dual_mono(float* sample, void* in_pcm, int n) { int i; unsigned char * pcm = (unsigned char *) in_pcm; for (i = 0; i < n; i++) { fdct16_dual_mono(sample, vbuf + vb_ptr); windowB16(vbuf, vb_ptr, pcm); sample += 64; vb_ptr = (vb_ptr - 16) & 255; pcm += 16; } } void CDecompressMpeg::sbtB16_dual_left(float* sample, void* in_pcm, int n) { int i; unsigned char * pcm = (unsigned char *) in_pcm; for (i = 0; i < n; i++) { fdct16_dual(sample, vbuf + vb_ptr); windowB16(vbuf, vb_ptr, pcm); sample += 64; vb_ptr = (vb_ptr - 16) & 255; pcm += 16; } } void CDecompressMpeg::sbtB16_dual_right(float* sample, void* in_pcm, int n) { int i; unsigned char * pcm = (unsigned char *) in_pcm; sample++; for (i = 0; i < n; i++) { fdct16_dual(sample, vbuf + vb_ptr); windowB16(vbuf, vb_ptr, pcm); sample += 64; vb_ptr = (vb_ptr - 16) & 255; pcm += 16; } } void CDecompressMpeg::sbtB8_mono(float* sample, void* in_pcm, int n) { int i; unsigned char * pcm = (unsigned char *) in_pcm; for (i = 0; i < n; i++) { fdct8(sample, vbuf + vb_ptr); windowB8(vbuf, vb_ptr, pcm); sample += 64; vb_ptr = (vb_ptr - 8) & 127; pcm += 8; } } void CDecompressMpeg::sbtB8_dual(float* sample, void* in_pcm, int n) { int i; unsigned char * pcm = (unsigned char *) in_pcm; for (i = 0; i < n; i++) { fdct8_dual(sample, vbuf + vb_ptr); fdct8_dual(sample + 1, vbuf2 + vb_ptr); windowB8_dual(vbuf, vb_ptr, pcm); windowB8_dual(vbuf2, vb_ptr, pcm + 1); sample += 64; vb_ptr = (vb_ptr - 8) & 127; pcm += 16; } } void CDecompressMpeg::sbtB8_dual_mono(float* sample, void* in_pcm, int n) { int i; unsigned char * pcm = (unsigned char *) in_pcm; for (i = 0; i < n; i++) { fdct8_dual_mono(sample, vbuf + vb_ptr); windowB8(vbuf, vb_ptr, pcm); sample += 64; vb_ptr = (vb_ptr - 8) & 127; pcm += 8; } } void CDecompressMpeg::sbtB8_dual_left(float* sample, void* in_pcm, int n) { int i; unsigned char * pcm = (unsigned char *) in_pcm; for (i = 0; i < n; i++) { fdct8_dual(sample, vbuf + vb_ptr); windowB8(vbuf, vb_ptr, pcm); sample += 64; vb_ptr = (vb_ptr - 8) & 127; pcm += 8; } } void CDecompressMpeg::sbtB8_dual_right(float* sample, void* in_pcm, int n) { int i; unsigned char * pcm = (unsigned char *) in_pcm; sample++; for (i = 0; i < n; i++) { fdct8_dual(sample, vbuf + vb_ptr); windowB8(vbuf, vb_ptr, pcm); sample += 64; vb_ptr = (vb_ptr - 8) & 127; pcm += 8; } } void CDecompressMpeg::sbtB_mono_L3(float* sample, void* in_pcm, int ch) { int i; unsigned char * pcm = (unsigned char *) in_pcm; ch = 0; for (i = 0; i < 18; i++) { fdct32(sample, vbuf + vb_ptr); windowB(vbuf, vb_ptr, pcm); sample += 32; vb_ptr = (vb_ptr - 32) & 511; pcm += 32; } } void CDecompressMpeg::sbtB_dual_L3(float* sample, void* in_pcm, int ch) { int i; unsigned char * pcm = (unsigned char *) in_pcm; if (ch == 0) for (i = 0; i < 18; i++) { fdct32(sample, vbuf + vb_ptr); windowB_dual(vbuf, vb_ptr, pcm); sample += 32; vb_ptr = (vb_ptr - 32) & 511; pcm += 64; } else for (i = 0; i < 18; i++) { fdct32(sample, vbuf2 + vb2_ptr); windowB_dual(vbuf2, vb2_ptr, pcm + 1); sample += 32; vb2_ptr = (vb2_ptr - 32) & 511; pcm += 64; } } void CDecompressMpeg::sbtB16_mono_L3(float* sample, void* in_pcm, int ch) { int i; unsigned char * pcm = (unsigned char *) in_pcm; ch = 0; for (i = 0; i < 18; i++) { fdct16(sample, vbuf + vb_ptr); windowB16(vbuf, vb_ptr, pcm); sample += 32; vb_ptr = (vb_ptr - 16) & 255; pcm += 16; } } void CDecompressMpeg::sbtB16_dual_L3(float* sample, void* in_pcm, int ch) { int i; unsigned char * pcm = (unsigned char *) in_pcm; if (ch == 0) { for (i = 0; i < 18; i++) { fdct16(sample, vbuf + vb_ptr); windowB16_dual(vbuf, vb_ptr, pcm); sample += 32; vb_ptr = (vb_ptr - 16) & 255; pcm += 32; } } else { for (i = 0; i < 18; i++) { fdct16(sample, vbuf2 + vb2_ptr); windowB16_dual(vbuf2, vb2_ptr, pcm + 1); sample += 32; vb2_ptr = (vb2_ptr - 16) & 255; pcm += 32; } } } void CDecompressMpeg::sbtB8_mono_L3(float* sample, void* in_pcm, int ch) { int i; unsigned char * pcm = (unsigned char *) in_pcm; ch = 0; for (i = 0; i < 18; i++) { fdct8(sample, vbuf + vb_ptr); windowB8(vbuf, vb_ptr, pcm); sample += 32; vb_ptr = (vb_ptr - 8) & 127; pcm += 8; } } void CDecompressMpeg::sbtB8_dual_L3(float* sample, void* in_pcm, int ch) { int i; unsigned char * pcm = (unsigned char *) in_pcm; if (ch == 0) { for (i = 0; i < 18; i++) { fdct8(sample, vbuf + vb_ptr); windowB8_dual(vbuf, vb_ptr, pcm); sample += 32; vb_ptr = (vb_ptr - 8) & 127; pcm += 16; } } else { for (i = 0; i < 18; i++) { fdct8(sample, vbuf2 + vb2_ptr); windowB8_dual(vbuf2, vb2_ptr, pcm + 1); sample += 32; vb2_ptr = (vb2_ptr - 8) & 127; pcm += 16; } } } // window coefs float CDecompressMpeg::wincoef[264] = { 0.000000000f, 0.000442505f, -0.003250122f, 0.007003784f, -0.031082151f, 0.078628540f, -0.100311279f, 0.572036743f, -1.144989014f, -0.572036743f, -0.100311279f, -0.078628540f, -0.031082151f, -0.007003784f, -0.003250122f, -0.000442505f, 0.000015259f, 0.000473022f, -0.003326416f, 0.007919312f, -0.030517576f, 0.084182739f, -0.090927124f, 0.600219727f, -1.144287109f, -0.543823242f, -0.108856201f, -0.073059082f, -0.031478882f, -0.006118774f, -0.003173828f, -0.000396729f, 0.000015259f, 0.000534058f, -0.003387451f, 0.008865356f, -0.029785154f, 0.089706421f, -0.080688477f, 0.628295898f, -1.142211914f, -0.515609741f, -0.116577141f, -0.067520142f, -0.031738281f, -0.005294800f, -0.003082275f, -0.000366211f, 0.000015259f, 0.000579834f, -0.003433228f, 0.009841919f, -0.028884888f, 0.095169067f, -0.069595337f, 0.656219482f, -1.138763428f, -0.487472534f, -0.123474121f, -0.061996460f, -0.031845093f, -0.004486084f, -0.002990723f, -0.000320435f, 0.000015259f, 0.000625610f, -0.003463745f, 0.010848999f, -0.027801514f, 0.100540161f, -0.057617184f, 0.683914185f, -1.133926392f, -0.459472656f, -0.129577637f, -0.056533810f, -0.031814575f, -0.003723145f, -0.002899170f, -0.000289917f, 0.000015259f, 0.000686646f, -0.003479004f, 0.011886597f, -0.026535034f, 0.105819702f, -0.044784546f, 0.711318970f, -1.127746582f, -0.431655884f, -0.134887695f, -0.051132202f, -0.031661987f, -0.003005981f, -0.002792358f, -0.000259399f, 0.000015259f, 0.000747681f, -0.003479004f, 0.012939452f, -0.025085449f, 0.110946655f, -0.031082151f, 0.738372803f, -1.120223999f, -0.404083252f, -0.139450073f, -0.045837402f, -0.031387329f, -0.002334595f, -0.002685547f, -0.000244141f, 0.000030518f, 0.000808716f, -0.003463745f, 0.014022826f, -0.023422241f, 0.115921021f, -0.016510010f, 0.765029907f, -1.111373901f, -0.376800537f, -0.143264771f, -0.040634155f, -0.031005858f, -0.001693726f, -0.002578735f, -0.000213623f, 0.000030518f, 0.000885010f, -0.003417969f, 0.015121460f, -0.021575928f, 0.120697014f, -0.001068115f, 0.791213989f, -1.101211548f, -0.349868774f, -0.146362305f, -0.035552979f, -0.030532837f, -0.001098633f, -0.002456665f, -0.000198364f, 0.000030518f, 0.000961304f, -0.003372192f, 0.016235352f, -0.019531250f, 0.125259399f, 0.015228271f, 0.816864014f, -1.089782715f, -0.323318481f, -0.148773193f, -0.030609131f, -0.029937742f, -0.000549316f, -0.002349854f, -0.000167847f, 0.000030518f, 0.001037598f, -0.003280640f, 0.017349243f, -0.017257690f, 0.129562378f, 0.032379150f, 0.841949463f, -1.077117920f, -0.297210693f, -0.150497437f, -0.025817871f, -0.029281614f, -0.000030518f, -0.002243042f, -0.000152588f, 0.000045776f, 0.001113892f, -0.003173828f, 0.018463135f, -0.014801024f, 0.133590698f, 0.050354004f, 0.866363525f, -1.063217163f, -0.271591187f, -0.151596069f, -0.021179199f, -0.028533936f, 0.000442505f, -0.002120972f, -0.000137329f, 0.000045776f, 0.001205444f, -0.003051758f, 0.019577026f, -0.012115479f, 0.137298584f, 0.069168091f, 0.890090942f, -1.048156738f, -0.246505737f, -0.152069092f, -0.016708374f, -0.027725220f, 0.000869751f, -0.002014160f, -0.000122070f, 0.000061035f, 0.001296997f, -0.002883911f, 0.020690918f, -0.009231566f, 0.140670776f, 0.088775635f, 0.913055420f, -1.031936646f, -0.221984863f, -0.151962280f, -0.012420653f, -0.026840210f, 0.001266479f, -0.001907349f, -0.000106812f, 0.000061035f, 0.001388550f, -0.002700806f, 0.021789551f, -0.006134033f, 0.143676758f, 0.109161377f, 0.935195923f, -1.014617920f, -0.198059082f, -0.151306152f, -0.008316040f, -0.025909424f, 0.001617432f, -0.001785278f, -0.000106812f, 0.000076294f, 0.001480103f, -0.002487183f, 0.022857666f, -0.002822876f, 0.146255493f, 0.130310059f, 0.956481934f, -0.996246338f, -0.174789429f, -0.150115967f, -0.004394531f, -0.024932859f, 0.001937866f, -0.001693726f, -0.000091553f, -0.001586914f, -0.023910521f, -0.148422241f, -0.976852417f, 0.152206421f, 0.000686646f, -0.002227783f, 0.000076294f, }; void CDecompressMpeg::window(float* vbuf, int vb_ptr, short* pcm) { int i, j; int si, bx; float* coef; float sum; long tmp; si = vb_ptr + 16; bx = (si + 32) & 511; coef = wincoef; /*-- first 16 --*/ for (i = 0; i < 16; i++) { sum = 0.0F; for (j = 0; j < 8; j++) { sum += (*coef++) * vbuf[si]; si = (si + 64) & 511; sum -= (*coef++) * vbuf[bx]; bx = (bx + 64) & 511; } si++; bx--; tmp = (long) sum; if (tmp > 32767) tmp = 32767; else if (tmp < -32768) tmp = -32768; *pcm++ = (short) tmp; } /*-- special case --*/ sum = 0.0F; for (j = 0; j < 8; j++) { sum += (*coef++) * vbuf[bx]; bx = (bx + 64) & 511; } tmp = (long) sum; if (tmp > 32767) tmp = 32767; else if (tmp < -32768) tmp = -32768; *pcm++ = (short) tmp; /*-- last 15 --*/ coef = wincoef + 255; /* back pass through coefs */ for (i = 0; i < 15; i++) { si--; bx++; sum = 0.0F; for (j = 0; j < 8; j++) { sum += (*coef--) * vbuf[si]; si = (si + 64) & 511; sum += (*coef--) * vbuf[bx]; bx = (bx + 64) & 511; } tmp = (long) sum; if (tmp > 32767) tmp = 32767; else if (tmp < -32768) tmp = -32768; *pcm++ = (short) tmp; } } void CDecompressMpeg::window_dual(float* vbuf, int vb_ptr, short* pcm) { int i, j; /* dual window interleaves output */ int si, bx; float* coef; float sum; long tmp; si = vb_ptr + 16; bx = (si + 32) & 511; coef = wincoef; /*-- first 16 --*/ for (i = 0; i < 16; i++) { sum = 0.0F; for (j = 0; j < 8; j++) { sum += (*coef++) * vbuf[si]; si = (si + 64) & 511; sum -= (*coef++) * vbuf[bx]; bx = (bx + 64) & 511; } si++; bx--; tmp = (long) sum; if (tmp > 32767) tmp = 32767; else if (tmp < -32768) tmp = -32768; *pcm = (short) tmp; pcm += 2; } /*-- special case --*/ sum = 0.0F; for (j = 0; j < 8; j++) { sum += (*coef++) * vbuf[bx]; bx = (bx + 64) & 511; } tmp = (long) sum; if (tmp > 32767) tmp = 32767; else if (tmp < -32768) tmp = -32768; *pcm = (short) tmp; pcm += 2; /*-- last 15 --*/ coef = wincoef + 255; /* back pass through coefs */ for (i = 0; i < 15; i++) { si--; bx++; sum = 0.0F; for (j = 0; j < 8; j++) { sum += (*coef--) * vbuf[si]; si = (si + 64) & 511; sum += (*coef--) * vbuf[bx]; bx = (bx + 64) & 511; } tmp = (long) sum; if (tmp > 32767) tmp = 32767; else if (tmp < -32768) tmp = -32768; *pcm = (short) tmp; pcm += 2; } } void CDecompressMpeg::window16(float* vbuf, int vb_ptr, short* pcm) { int i, j; unsigned char si, bx; float* coef; float sum; long tmp; si = vb_ptr + 8; bx = si + 16; coef = wincoef; /*-- first 8 --*/ for (i = 0; i < 8; i++) { sum = 0.0F; for (j = 0; j < 8; j++) { sum += (*coef++) * vbuf[si]; si += 32; sum -= (*coef++) * vbuf[bx]; bx += 32; } si++; bx--; coef += 16; tmp = (long) sum; if (tmp > 32767) tmp = 32767; else if (tmp < -32768) tmp = -32768; *pcm++ = (short) tmp; } /*-- special case --*/ sum = 0.0F; for (j = 0; j < 8; j++) { sum += (*coef++) * vbuf[bx]; bx += 32; } tmp = (long) sum; if (tmp > 32767) tmp = 32767; else if (tmp < -32768) tmp = -32768; *pcm++ = (short) tmp; /*-- last 7 --*/ coef = wincoef + 255; /* back pass through coefs */ for (i = 0; i < 7; i++) { coef -= 16; si--; bx++; sum = 0.0F; for (j = 0; j < 8; j++) { sum += (*coef--) * vbuf[si]; si += 32; sum += (*coef--) * vbuf[bx]; bx += 32; } tmp = (long) sum; if (tmp > 32767) tmp = 32767; else if (tmp < -32768) tmp = -32768; *pcm++ = (short) tmp; } } void CDecompressMpeg::window16_dual(float* vbuf, int vb_ptr, short* pcm) { int i, j; unsigned char si, bx; float* coef; float sum; long tmp; si = vb_ptr + 8; bx = si + 16; coef = wincoef; /*-- first 8 --*/ for (i = 0; i < 8; i++) { sum = 0.0F; for (j = 0; j < 8; j++) { sum += (*coef++) * vbuf[si]; si += 32; sum -= (*coef++) * vbuf[bx]; bx += 32; } si++; bx--; coef += 16; tmp = (long) sum; if (tmp > 32767) tmp = 32767; else if (tmp < -32768) tmp = -32768; *pcm = (short) tmp; pcm += 2; } /*-- special case --*/ sum = 0.0F; for (j = 0; j < 8; j++) { sum += (*coef++) * vbuf[bx]; bx += 32; } tmp = (long) sum; if (tmp > 32767) tmp = 32767; else if (tmp < -32768) tmp = -32768; *pcm = (short) tmp; pcm += 2; /*-- last 7 --*/ coef = wincoef + 255; /* back pass through coefs */ for (i = 0; i < 7; i++) { coef -= 16; si--; bx++; sum = 0.0F; for (j = 0; j < 8; j++) { sum += (*coef--) * vbuf[si]; si += 32; sum += (*coef--) * vbuf[bx]; bx += 32; } tmp = (long) sum; if (tmp > 32767) tmp = 32767; else if (tmp < -32768) tmp = -32768; *pcm = (short) tmp; pcm += 2; } } void CDecompressMpeg::window8(float* vbuf, int vb_ptr, short* pcm) { int i, j; int si, bx; float* coef; float sum; long tmp; si = vb_ptr + 4; bx = (si + 8) & 127; coef = wincoef; /*-- first 4 --*/ for (i = 0; i < 4; i++) { sum = 0.0F; for (j = 0; j < 8; j++) { sum += (*coef++) * vbuf[si]; si = (si + 16) & 127; sum -= (*coef++) * vbuf[bx]; bx = (bx + 16) & 127; } si++; bx--; coef += 48; tmp = (long) sum; if (tmp > 32767) tmp = 32767; else if (tmp < -32768) tmp = -32768; *pcm++ = (short) tmp; } /*-- special case --*/ sum = 0.0F; for (j = 0; j < 8; j++) { sum += (*coef++) * vbuf[bx]; bx = (bx + 16) & 127; } tmp = (long) sum; if (tmp > 32767) tmp = 32767; else if (tmp < -32768) tmp = -32768; *pcm++ = (short) tmp; /*-- last 3 --*/ coef = wincoef + 255; /* back pass through coefs */ for (i = 0; i < 3; i++) { coef -= 48; si--; bx++; sum = 0.0F; for (j = 0; j < 8; j++) { sum += (*coef--) * vbuf[si]; si = (si + 16) & 127; sum += (*coef--) * vbuf[bx]; bx = (bx + 16) & 127; } tmp = (long) sum; if (tmp > 32767) tmp = 32767; else if (tmp < -32768) tmp = -32768; *pcm++ = (short) tmp; } } void CDecompressMpeg::window8_dual(float* vbuf, int vb_ptr, short* pcm) { int i, j; int si, bx; float* coef; float sum; long tmp; si = vb_ptr + 4; bx = (si + 8) & 127; coef = wincoef; /*-- first 4 --*/ for (i = 0; i < 4; i++) { sum = 0.0F; for (j = 0; j < 8; j++) { sum += (*coef++) * vbuf[si]; si = (si + 16) & 127; sum -= (*coef++) * vbuf[bx]; bx = (bx + 16) & 127; } si++; bx--; coef += 48; tmp = (long) sum; if (tmp > 32767) tmp = 32767; else if (tmp < -32768) tmp = -32768; *pcm = (short) tmp; pcm += 2; } /*-- special case --*/ sum = 0.0F; for (j = 0; j < 8; j++) { sum += (*coef++) * vbuf[bx]; bx = (bx + 16) & 127; } tmp = (long) sum; if (tmp > 32767) tmp = 32767; else if (tmp < -32768) tmp = -32768; *pcm = (short) tmp; pcm += 2; /*-- last 3 --*/ coef = wincoef + 255; /* back pass through coefs */ for (i = 0; i < 3; i++) { coef -= 48; si--; bx++; sum = 0.0F; for (j = 0; j < 8; j++) { sum += (*coef--) * vbuf[si]; si = (si + 16) & 127; sum += (*coef--) * vbuf[bx]; bx = (bx + 16) & 127; } tmp = (long) sum; if (tmp > 32767) tmp = 32767; else if (tmp < -32768) tmp = -32768; *pcm = (short) tmp; pcm += 2; } } void CDecompressMpeg::sbt_init() { int i; /* clear window vbuf */ for (i = 0; i < 512; i++) { vbuf[i] = 0.0F; vbuf2[i] = 0.0F; } vb2_ptr = vb_ptr = 0; } void CDecompressMpeg::sbt_mono(float* sample, void* in_pcm, int n) { int i; short* pcm = (short*) in_pcm; for (i = 0; i < n; i++) { fdct32(sample, vbuf + vb_ptr); window(vbuf, vb_ptr, pcm); sample += 64; vb_ptr = (vb_ptr - 32) & 511; pcm += 32; } } void CDecompressMpeg::sbt_dual(float* sample, void* in_pcm, int n) { int i; short* pcm = (short*) in_pcm; for (i = 0; i < n; i++) { fdct32_dual(sample, vbuf + vb_ptr); fdct32_dual(sample + 1, vbuf2 + vb_ptr); window_dual(vbuf, vb_ptr, pcm); window_dual(vbuf2, vb_ptr, pcm + 1); sample += 64; vb_ptr = (vb_ptr - 32) & 511; pcm += 64; } } void CDecompressMpeg::sbt_dual_mono(float* sample, void* in_pcm, int n) { int i; short* pcm = (short*) in_pcm; for (i = 0; i < n; i++) { fdct32_dual_mono(sample, vbuf + vb_ptr); window(vbuf, vb_ptr, pcm); sample += 64; vb_ptr = (vb_ptr - 32) & 511; pcm += 32; } } void CDecompressMpeg::sbt_dual_left(float* sample, void* in_pcm, int n) { int i; short* pcm = (short*) in_pcm; for (i = 0; i < n; i++) { fdct32_dual(sample, vbuf + vb_ptr); window(vbuf, vb_ptr, pcm); sample += 64; vb_ptr = (vb_ptr - 32) & 511; pcm += 32; } } void CDecompressMpeg::sbt_dual_right(float* sample, void* in_pcm, int n) { int i; short* pcm = (short*) in_pcm; sample++; /* point to right chan */ for (i = 0; i < n; i++) { fdct32_dual(sample, vbuf + vb_ptr); window(vbuf, vb_ptr, pcm); sample += 64; vb_ptr = (vb_ptr - 32) & 511; pcm += 32; } } void CDecompressMpeg::sbt16_mono(float* sample, void* in_pcm, int n) { int i; short* pcm = (short*) in_pcm; for (i = 0; i < n; i++) { fdct16(sample, vbuf + vb_ptr); window16(vbuf, vb_ptr, pcm); sample += 64; vb_ptr = (vb_ptr - 16) & 255; pcm += 16; } } void CDecompressMpeg::sbt16_dual(float* sample, void* in_pcm, int n) { int i; short* pcm = (short*) in_pcm; for (i = 0; i < n; i++) { fdct16_dual(sample, vbuf + vb_ptr); fdct16_dual(sample + 1, vbuf2 + vb_ptr); window16_dual(vbuf, vb_ptr, pcm); window16_dual(vbuf2, vb_ptr, pcm + 1); sample += 64; vb_ptr = (vb_ptr - 16) & 255; pcm += 32; } } void CDecompressMpeg::sbt16_dual_mono(float* sample, void* in_pcm, int n) { int i; short* pcm = (short*) in_pcm; for (i = 0; i < n; i++) { fdct16_dual_mono(sample, vbuf + vb_ptr); window16(vbuf, vb_ptr, pcm); sample += 64; vb_ptr = (vb_ptr - 16) & 255; pcm += 16; } } void CDecompressMpeg::sbt16_dual_left(float* sample, void* in_pcm, int n) { int i; short* pcm = (short*) in_pcm; for (i = 0; i < n; i++) { fdct16_dual(sample, vbuf + vb_ptr); window16(vbuf, vb_ptr, pcm); sample += 64; vb_ptr = (vb_ptr - 16) & 255; pcm += 16; } } void CDecompressMpeg::sbt16_dual_right(float* sample, void* in_pcm, int n) { int i; short* pcm = (short*) in_pcm; sample++; for (i = 0; i < n; i++) { fdct16_dual(sample, vbuf + vb_ptr); window16(vbuf, vb_ptr, pcm); sample += 64; vb_ptr = (vb_ptr - 16) & 255; pcm += 16; } } void CDecompressMpeg::sbt8_mono(float* sample, void* in_pcm, int n) { int i; short* pcm = (short*) in_pcm; for (i = 0; i < n; i++) { fdct8(sample, vbuf + vb_ptr); window8(vbuf, vb_ptr, pcm); sample += 64; vb_ptr = (vb_ptr - 8) & 127; pcm += 8; } } void CDecompressMpeg::sbt8_dual(float* sample, void* in_pcm, int n) { int i; short* pcm = (short*) in_pcm; for (i = 0; i < n; i++) { fdct8_dual(sample, vbuf + vb_ptr); fdct8_dual(sample + 1, vbuf2 + vb_ptr); window8_dual(vbuf, vb_ptr, pcm); window8_dual(vbuf2, vb_ptr, pcm + 1); sample += 64; vb_ptr = (vb_ptr - 8) & 127; pcm += 16; } } void CDecompressMpeg::sbt8_dual_mono(float* sample, void* in_pcm, int n) { int i; short* pcm = (short*) in_pcm; for (i = 0; i < n; i++) { fdct8_dual_mono(sample, vbuf + vb_ptr); window8(vbuf, vb_ptr, pcm); sample += 64; vb_ptr = (vb_ptr - 8) & 127; pcm += 8; } } void CDecompressMpeg::sbt8_dual_left(float* sample, void* in_pcm, int n) { int i; short* pcm = (short*) in_pcm; for (i = 0; i < n; i++) { fdct8_dual(sample, vbuf + vb_ptr); window8(vbuf, vb_ptr, pcm); sample += 64; vb_ptr = (vb_ptr - 8) & 127; pcm += 8; } } void CDecompressMpeg::sbt8_dual_right(float* sample, void* in_pcm, int n) { int i; short* pcm = (short*) in_pcm; sample++; for (i = 0; i < n; i++) { fdct8_dual(sample, vbuf + vb_ptr); window8(vbuf, vb_ptr, pcm); sample += 64; vb_ptr = (vb_ptr - 8) & 127; pcm += 8; } } void CDecompressMpeg::sbt_mono_L3(float* sample, void* in_pcm, int ch) { int i; short* pcm = (short*) in_pcm; ch = 0; for (i = 0; i < 18; i++) { fdct32(sample, vbuf + vb_ptr); window(vbuf, vb_ptr, pcm); sample += 32; vb_ptr = (vb_ptr - 32) & 511; pcm += 32; } } void CDecompressMpeg::sbt_dual_L3(float* sample, void* in_pcm, int ch) { int i; short* pcm = (short*) in_pcm; if (ch == 0) for (i = 0; i < 18; i++) { fdct32(sample, vbuf + vb_ptr); window_dual(vbuf, vb_ptr, pcm); sample += 32; vb_ptr = (vb_ptr - 32) & 511; pcm += 64; } else for (i = 0; i < 18; i++) { fdct32(sample, vbuf2 + vb2_ptr); window_dual(vbuf2, vb2_ptr, pcm + 1); sample += 32; vb2_ptr = (vb2_ptr - 32) & 511; pcm += 64; } } void CDecompressMpeg::sbt16_mono_L3(float* sample, void* in_pcm, int ch) { int i; short* pcm = (short*) in_pcm; ch = 0; for (i = 0; i < 18; i++) { fdct16(sample, vbuf + vb_ptr); window16(vbuf, vb_ptr, pcm); sample += 32; vb_ptr = (vb_ptr - 16) & 255; pcm += 16; } } void CDecompressMpeg::sbt16_dual_L3(float* sample, void* in_pcm, int ch) { int i; short* pcm = (short*) in_pcm; if (ch == 0) { for (i = 0; i < 18; i++) { fdct16(sample, vbuf + vb_ptr); window16_dual(vbuf, vb_ptr, pcm); sample += 32; vb_ptr = (vb_ptr - 16) & 255; pcm += 32; } } else { for (i = 0; i < 18; i++) { fdct16(sample, vbuf2 + vb2_ptr); window16_dual(vbuf2, vb2_ptr, pcm + 1); sample += 32; vb2_ptr = (vb2_ptr - 16) & 255; pcm += 32; } } } void CDecompressMpeg::sbt8_mono_L3(float* sample, void* in_pcm, int ch) { int i; short* pcm = (short*) in_pcm; ch = 0; for (i = 0; i < 18; i++) { fdct8(sample, vbuf + vb_ptr); window8(vbuf, vb_ptr, pcm); sample += 32; vb_ptr = (vb_ptr - 8) & 127; pcm += 8; } } void CDecompressMpeg::sbt8_dual_L3(float* sample, void* in_pcm, int ch) { int i; short* pcm = (short*) in_pcm; if (ch == 0) { for (i = 0; i < 18; i++) { fdct8(sample, vbuf + vb_ptr); window8_dual(vbuf, vb_ptr, pcm); sample += 32; vb_ptr = (vb_ptr - 8) & 127; pcm += 16; } } else { for (i = 0; i < 18; i++) { fdct8(sample, vbuf2 + vb2_ptr); window8_dual(vbuf2, vb2_ptr, pcm + 1); sample += 32; vb2_ptr = (vb2_ptr - 8) & 127; pcm += 16; } } } int CDecompressMpeg::br_tbl[3][3][16] = { {// MPEG-1 // Layer1 { 0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, 0 }, // Layer2 { 0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 0 }, // Layer3 { 0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 0 }, }, {// MPEG-2 // Layer1 { 0, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256, 0 }, // Layer2 { 0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, 0 }, // Layer3 { 0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, 0 }, }, {// MPEG-2.5 // Layer1 (not available) { 0, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256, 0 }, // Layer2 (not available) { 0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, 0 }, // Layer3 { 0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, 0 }, }, }; int CDecompressMpeg::fr_tbl[3][4] = { { 44100, 48000, 32000, 0 }, // MPEG-1 { 22050, 24000, 16000, 0 }, // MPEG-2 { 11025, 12000, 8000, 0 }, // MPEG-2.5 }; void CDecompressMpeg::mp3DecodeInit() { m_option.reduction = 0; m_option.convert = 0; m_option.freqLimit = 24000; L1table_init(); L2table_init(); L3table_init(); } int CDecompressMpeg::mp3GetHeader(BYTE* buf, MPEG_HEADER* h) { h->version = (buf[1] & 0x08) >> 3; h->layer = (buf[1] & 0x06) >> 1; h->error_prot = (buf[1] & 0x01); h->br_index = (buf[2] & 0xf0) >> 4; h->fr_index = (buf[2] & 0x0c) >> 2; h->padding = (buf[2] & 0x02) >> 1; h->extension = (buf[2] & 0x01); h->mode = (buf[3] & 0xc0) >> 6; h->mode_ext = (buf[3] & 0x30) >> 4; h->copyright = (buf[3] & 0x08) >> 3; h->original = (buf[3] & 0x04) >> 2; h->emphasis = (buf[3] & 0x03); if (buf[0] != 0xFF) { //sync error m_last_error = MP3_ERROR_INVALID_SYNC; return 0; } if ((buf[1] & 0xF0) == 0xF0) //MPEG-1, MPEG-2 h->version = (h->version) ? 1 : 2; else if ((buf[1] & 0xF0) == 0xE0) //MPEG-2.5 h->version = 3; else { m_last_error = MP3_ERROR_INVALID_SYNC; return 0; } if (h->fr_index >= 3 || h->br_index == 0 || h->br_index >= 15 || h->layer == 0 || h->layer >= 4) { m_last_error = MP3_ERROR_INVALID_HEADER; return 0; } h->layer = 4 - h->layer; h->error_prot = (h->error_prot) ? 0 : 1; return 1; } bool CDecompressMpeg::mp3GetHeaderInfo(BYTE* buffer, MPEG_HEADER_INFO* info) { int ch, ver; MPEG_HEADER* h =& info->header; // получим информацию из заголовка if (!mp3GetHeader(buffer, h)) return false; // расчет нужных данных info->curBitRate = br_tbl[h->version - 1][h->layer - 1][h->br_index] * 1000; switch (h->layer) { case 1: //layer1 info->curFrameSize = (12 * info->curBitRate / m_frequency + h->padding) * 4; break; case 2: //layer2 info->curFrameSize = 144 * info->curBitRate / m_frequency + h->padding; break; case 3: //layer3 if (h->version == 1) info->curFrameSize = 144 * info->curBitRate / m_frequency + h->padding; else info->curFrameSize = (144 * info->curBitRate / m_frequency) / 2 + h->padding; break; } ch = (h->mode == 3) ? 1 : 2; ver = (h->version == 1) ? 1 : 2; info->samplesInFrame = (1152 >> m_option.reduction) / ver; info->outputSize = info->samplesInFrame * 2 * ch; return true; } int CDecompressMpeg::mp3GetLastError() { return m_last_error; } int CDecompressMpeg::mp3FindSync(BYTE* buf, int size, int* sync) { int i; MPEG_HEADER h; *sync = 0; size -= 3; if (size <= 0) { m_last_error = MP3_ERROR_OUT_OF_BUFFER; return 0; } // поиск данных for (i = 0; i < size; i++) { if (buf[i] == 0xFF) { if (mp3GetHeader(buf + i, & h)) { if ((h.layer == _layer) && (h.version == _version) && (h.br_index == _br_index) && (h.fr_index == _fr_index) && (h.mode == _mode)) break; } } } if (i == size) { m_last_error = MP3_ERROR_OUT_OF_BUFFER; return 0; } *sync = i; return 1; } void CDecompressMpeg::mp3GetDecodeOption(MPEG_DECODE_OPTION* option) { *option = m_option; } int CDecompressMpeg::mp3SetDecodeOption(MPEG_DECODE_OPTION* option) { m_option = *option; return 1; } /* //----------------------------------------------------------------------------- // Установка эквалайзера // value - указатель на параметры эквалайзера //----------------------------------------------------------------------------- int CDecompressMpeg::mp3SetEqualizer(int* value) { int i; if (value == (void*)0) { m_enableEQ = 0; return 1; } m_enableEQ = 1; //60, 170, 310, 600, 1K, 3K for (i = 0; i < 6; i ++) { m_equalizer[i] = (float)pow(10,(double)value[i]/200); } //6K m_equalizer[6] = (float)pow(10,(double)value[6]/200); m_equalizer[7] = m_equalizer[6]; //12K m_equalizer[8] = (float)pow(10,(double)value[7]/200); m_equalizer[9] = m_equalizer[8]; m_equalizer[10] = m_equalizer[8]; m_equalizer[11] = m_equalizer[8]; //14K m_equalizer[12] = (float)pow(10,(double)value[8]/200); m_equalizer[13] = m_equalizer[12]; m_equalizer[14] = m_equalizer[12]; m_equalizer[15] = m_equalizer[12]; m_equalizer[16] = m_equalizer[12]; m_equalizer[17] = m_equalizer[12]; m_equalizer[18] = m_equalizer[12]; m_equalizer[19] = m_equalizer[12]; //16K m_equalizer[20] = (float)pow(10,(double)value[9]/200); m_equalizer[21] = m_equalizer[20]; m_equalizer[22] = m_equalizer[20]; m_equalizer[23] = m_equalizer[20]; m_equalizer[24] = m_equalizer[20]; m_equalizer[25] = m_equalizer[20]; m_equalizer[26] = m_equalizer[20]; m_equalizer[27] = m_equalizer[20]; m_equalizer[28] = m_equalizer[20]; m_equalizer[29] = m_equalizer[20]; m_equalizer[30] = m_equalizer[20]; m_equalizer[31] = m_equalizer[20]; return 1; } */ #define VBR_FRAMES_FLAG 0x0001 #define VBR_BYTES_FLAG 0x0002 #define VBR_TOC_FLAG 0x0004 #define VBR_SCALE_FLAG 0x0008 // big endian extract int CDecompressMpeg::extractInt4(BYTE* buf) { return buf[3] | (buf[2] << 8) | (buf[1] << 16) | (buf[0] << 24); } //----------------------------------------------------------------------------- // извленение заголовка и важных данных // mpeg - указатель на буфер с данными // size - размер буфера с данными // info - указатель на структуру куда поместить расширенные данные // decFlag - ? помоему использовать настройки частоты из файла //----------------------------------------------------------------------------- int CDecompressMpeg::mp3GetDecodeInfo(BYTE* mpeg, int size, MPEG_DECODE_INFO* info, int decFlag) { MPEG_HEADER* h =& info->header; byte* p = mpeg; int vbr; DWORD minBitRate, maxBitRate; DWORD i, j, flags; //int bitRate; //int frame_size; // if (size < 156) {//max vbr header size // m_last_error = MP3_ERROR_OUT_OF_BUFFER; // return 0; // } if (!mp3GetHeader(p, h)) { return 0; } //check VBR Header p += 4;//skip mpeg header if (h->error_prot) p += 2;//skip crc if (h->layer == 3) { //skip side info if (h->version == 1) { //MPEG-1 if (h->mode != 3) p += 32; else p += 17; } else { //MPEG-2, MPEG-2.5 if (h->mode != 3) p += 17; else p += 9; } } info->bitRate = br_tbl[h->version - 1][h->layer - 1][h->br_index] * 1000; info->frequency = fr_tbl[h->version - 1][h->fr_index]; if (memcmp(p, "Xing", 4) == 0) { //VBR p += 4; flags = extractInt4(p); p += 4; if (!(flags & (VBR_FRAMES_FLAG | VBR_BYTES_FLAG))) { m_last_error = MP3_ERROR_INVALID_HEADER; return 0; } info->frames = extractInt4(p); p += 4; info->dataSize = extractInt4(p); p += 4; if (flags & VBR_TOC_FLAG) p += 100; if (flags & VBR_SCALE_FLAG) p += 4; /* //•WЏЂVBR‘О‰ћ if ( p[0] == mpeg[0] && p[1] == mpeg[1] ) { info->skipSize = (int)(p - mpeg); } else { bitRate = br_tbl[h->version-1][h->layer-1][h->br_index] * 1000; switch (h->layer) { case 1://layer1 frame_size = (12 * bitRate / fr_tbl[h->version-1][h->fr_index]) * 4;//one slot is 4 bytes long if (h->padding) frame_size += 4; break; case 2://layer2 frame_size = 144 * bitRate / fr_tbl[h->version-1][h->fr_index]; if (h->padding) frame_size ++; break; case 3://layer3 frame_size = 144 * bitRate / fr_tbl[h->version-1][h->fr_index]; if (h->version != 1) //MPEG-2, MPEG-2.5 frame_size /= 2; if (h->padding) frame_size ++; break; } info->skipSize = (int)(frame_size); } info->bitRate = 0; */ vbr = 1; minBitRate = 0xffffffff; maxBitRate = 0; for (i = 1; i < 15; i ++) { j = br_tbl[h->version - 1][h->layer - 1][i] * 1000; if (j < minBitRate) minBitRate = j; if (j > maxBitRate) maxBitRate = j; } } else if (memcmp(p, "VBRI", 4) == 0) { //VBRI p += 10; info->dataSize = extractInt4(p); p += 4; info->frames = extractInt4(p); p += 4; vbr = 1; minBitRate = 0xffffffff; maxBitRate = 0; for (i = 1; i < 15; i ++) { j = br_tbl[h->version - 1][h->layer - 1][i] * 1000; if (j < minBitRate) minBitRate = j; if (j > maxBitRate) maxBitRate = j; } } else { //not VBR vbr = 0; info->frames = 0; //info->skipSize = 0; info->dataSize = 0; //info->bitRate = br_tbl[h->version-1][h->layer-1][h->br_index] * 1000; } // info->frequency = fr_tbl[h->version-1][h->fr_index]; // info->msPerFrame = ms_p_f_table[h->layer-1][h->fr_index]; // if (h->version == 3) info->msPerFrame *= 2; switch (h->layer) { case 1: //layer1 info->outputSize = 384 >> m_option.reduction; //if (info->bitRate) { if (!vbr) { info->skipSize = 0; info->minInputSize = (12 * info->bitRate / info->frequency) * 4;//one slot is 4 bytes long info->maxInputSize = info->minInputSize + 4; } else { info->skipSize = (12 * info->bitRate / info->frequency + h->padding) * 4; info->minInputSize = (12 * minBitRate / info->frequency) * 4; info->maxInputSize = (12 * maxBitRate / info->frequency) * 4 + 4; } break; case 2: //layer2 info->outputSize = 1152 >> m_option.reduction; //if (info->bitRate) { if (!vbr) { info->skipSize = 0; info->minInputSize = 144 * info->bitRate / info->frequency; info->maxInputSize = info->minInputSize + 1; } else { info->skipSize = 144 * info->bitRate / info->frequency + h->padding; info->minInputSize = 144 * minBitRate / info->frequency; info->maxInputSize = 144 * maxBitRate / info->frequency + 1; } break; case 3: //layer3 i = (h->version == 1) ? 1 : 2; //info->outputSize = 1152 >> m_option.reduction; info->outputSize = (1152 >> m_option.reduction) / i; //if (info->bitRate) { if (!vbr) { info->skipSize = 0; info->minInputSize = 144 * info->bitRate / info->frequency / i; info->maxInputSize = info->minInputSize + 1; } else { info->skipSize = 144 * info->bitRate / info->frequency / i + h->padding; info->minInputSize = 144 * minBitRate / info->frequency / i; info->maxInputSize = 144 * maxBitRate / info->frequency / i + 1; } break; /* if (h->version != 1) { //MPEG-2, MPEG-2.5 info->outputSize /= 2; info->minInputSize /= 2; info->maxInputSize /= 2; } info->maxInputSize ++; break; */ } if ((h->mode == 3) || (m_option.convert & 3)) info->channels = 1; else info->channels = 2; if (m_option.convert & 8) { //not available info->bitsPerSample = 8; info->outputSize *= info->channels; } else { info->bitsPerSample = 16; info->outputSize *= info->channels * 2; } if (decFlag == 1) { m_frequency = info->frequency; m_pcm_size = info->outputSize; } info->frequency >>= m_option.reduction; info->HeadBitRate = info->bitRate; if (vbr) info->bitRate = 0; return 1; } // начало декодирования int CDecompressMpeg::mp3DecodeStart(BYTE* mpeg, int size) { MPEG_DECODE_INFO info; MPEG_HEADER* h =& info.header; // распаковка заголовка и предрасчет важных данных if (!mp3GetDecodeInfo(mpeg, size, & info, 1)) return 0; // инициализация sbt_init(); // вызов методов инициализации слоя switch (h->layer) { case 1: L1decode_start(h); break; case 2: L2decode_start(h); break; case 3: L3decode_start(h); break; } return 1; } // декодирование 1 фрейма int CDecompressMpeg::mp3DecodeFrame(MPEG_DECODE_PARAM* param) { MPEG_HEADER* h =& param->header; // проверка размера входных данных if (param->inputSize <= 4) { m_last_error = MP3_ERROR_OUT_OF_BUFFER; return 0; } // прочитаем заголовок if (!mp3GetHeader((unsigned char *) param->inputBuf, h)) { return 0; } // вычисление размера данных в фрейме param->bitRate = br_tbl[h->version - 1][h->layer - 1][h->br_index] * 1000; switch (h->layer) { //layer1 case 1: m_frame_size = (12 * param->bitRate / m_frequency + h->padding) * 4; break; //layer2 case 2: m_frame_size = 144 * param->bitRate / m_frequency + h->padding; break; //layer3 case 3: if (h->version == 1) m_frame_size = 144 * param->bitRate / m_frequency + h->padding; else m_frame_size = (144 * param->bitRate / m_frequency) / 2 + h->padding; break; } // проверка размера входных данных if (param->inputSize < m_frame_size) { m_last_error = MP3_ERROR_OUT_OF_BUFFER; return 0; } // подбор декодера switch (h->layer) { case 1: L1decode_frame(h, (unsigned char *) param->inputBuf, (unsigned char *) param->outputBuf); break; case 2: L2decode_frame(h, (unsigned char *) param->inputBuf, (unsigned char *) param->outputBuf); break; case 3: L3decode_frame(h, (unsigned char *) param->inputBuf, (unsigned char *) param->outputBuf); break; } //!!!todo m_frame_proc(h, (unsigned char*)param->inputBuf, (unsigned char *)param->outputBuf); // скоректируем размеры входного и выходного буфера param->inputSize = m_frame_size; param->outputSize = m_pcm_size; return 1; } void CDecompressMpeg::mp3Reset(void) { sbt_init(); L3decode_reset(); } //----------------------------------------------------------------------------- // Установка новой позиции файла // на входе : pos - новая позиция в файле // на выходе : * //----------------------------------------------------------------------------- int CDecompressMpeg::mp3seek(DWORD frame) { // инициализация переменных DWORD cur = 0; DWORD back = 3; int off = 0; DWORD need_frame_offset = 0; // позиционируемся на данных if (_curFrame != frame) { if (_curFrame != (frame - 1)) { // прочитаем на несколько фреймов назад if (frame > back) frame -= back; else { back = frame; frame = 0; } if (!_vbr) { // приблизительный расчет положения фрейма need_frame_offset = (DWORD) floor(((double) frame * _bitPerFrame) / 8); // поиск начала фрейма while (1) { // установка позиции чтения if (SourceData->seek(need_frame_offset, 0) != need_frame_offset) return 0; // проверка на конец файла if (SourceData->eof()) return 0; // прочитаем данные для поиска начала if (SourceData->peek(_frameBuffer, _minFrameSize) != _minFrameSize) return 0; // поиск начала файла if (!mp3FindSync(_frameBuffer, _minFrameSize, & off)) { need_frame_offset += (_minFrameSize - 3); } else { need_frame_offset += off; break; } }; } else { need_frame_offset = _vbrFrameOffTable[frame]; } if (SourceData->seek(need_frame_offset, 0) != need_frame_offset) return 0; mp3Reset(); // сбросим декодер for (int ch = 0; ch < 2; ch++) { for (int gr = 0; gr < 2; gr++) { for (int sam = 0; sam < 576; sam++) { m_sample[ch][gr][sam].s = 0; m_sample[ch][gr][sam].x = 0; } } } for (cur = 0; cur < back; cur++) { SourceData->peek(_frameBuffer, 4); if (!mp3GetHeaderInfo(_frameBuffer, & _mpegHI)) return 0; _curFrameSize = _mpegHI.curFrameSize; if (SourceData->read(_frameBuffer, _curFrameSize) != _curFrameSize) return 0; _mpegDP.header = _mpegHI.header; _mpegDP.bitRate = _mpegHI.curBitRate; _mpegDP.inputBuf = _frameBuffer; _mpegDP.inputSize = _mpegHI.curFrameSize; _mpegDP.outputBuf = _sampleBuffer; _mpegDP.outputSize = _mpegHI.outputSize; // декодирование одного фрейма if (!mp3DecodeFrame(&_mpegDP)) return 0; } } } return 1; } //----------------------------------------------------------------------------- // Конструктор декодера // на входе : a - указатель на данные файла // на выходе : * //----------------------------------------------------------------------------- CDecompressMpeg::CDecompressMpeg(WAVEFORMATEX* pcm_format, bool& flag, CAbstractSoundFile* a) : CAbstractDecompressor(pcm_format, flag, a) { DWORD cur; DWORD pos; MPEG_HEADER_INFO info; BYTE head[156]; // файл не определен flag = false; // инициализация декодера mp3DecodeInit(); // инициализация данных декодера m_cs_factorL1 = m_cs_factor[0]; // m_enableEQ = 0; memset(&m_side_info, 0, sizeof(SIDE_INFO)); memset(&m_scale_fac, 0, sizeof(SCALE_FACTOR) * 4); memset(&m_cb_info, 0, sizeof(CB_INFO) * 4); memset(&m_nsamp, 0, sizeof(int) * 4); // очистим указатели на буфера _frameBuffer = 0; _vbr = 0; _vbrFrameOffTable = 0; // получение информаци о файле if (SourceData->peek(head, sizeof(head)) != sizeof(head)) return; if (!mp3GetDecodeInfo(head, sizeof(head), & _mpegDI, 1)) return; if (!mp3GetHeaderInfo(head, & _mpegHI)) return; // получим интерисующую нас информацию _channels = _mpegDI.channels; _frequency = _mpegDI.frequency; _bitrate = _mpegDI.HeadBitRate; _vbr = _mpegDI.bitRate ? false : true; _minFrameSize = _mpegDI.minInputSize; _maxFrameSize = _mpegDI.maxInputSize; _samplesInFrame = _mpegHI.samplesInFrame; _curFrameSize = _mpegHI.curFrameSize; _version = _mpegDI.header.version; _layer = _mpegDI.header.layer; _br_index = _mpegDI.header.br_index; _fr_index = _mpegDI.header.fr_index; _mode = _mpegDI.header.mode; _slotSize = (_mpegDI.header.layer == 1) ? 4 : 1; _bitPerFrame = (_mpegDI.header.version == 1) ? (double) (144 * 8 * _bitrate) / (double) _frequency : (double) (144 * 8 * _bitrate) / (double) (_frequency * 2); _frames = _vbr ? _mpegDI.frames : (DWORD) floor(((double) ((SourceData->size + _slotSize) * 8)) / _bitPerFrame); _samplesInFile = _frames * _samplesInFrame; //********************************************************************************* // отладка // заполним таблицу смещений cur = 0; pos = 0; while (!SourceData->eof()) { SourceData->seek(pos, 0); if (SourceData->peek(head, 4) != 4) break; if (!mp3GetHeaderInfo(head, & info)) break; pos += info.curFrameSize; cur++; } SourceData->seek(0, 0); if (cur != _frames) _frames = cur; _vbr = true; //********************************************************************************** // файл с переменным битрейтом ? if (_vbr) { // выделим память под таблицу смещений на фреймы #if AGSS_USE_MALLOC _vbrFrameOffTable = (DWORD *) malloc(_frames * sizeof(DWORD)); #else _vbrFrameOffTable = (DWORD *) GlobalAlloc(GPTR, _frames * sizeof(DWORD)); #endif if (!_vbrFrameOffTable) return; cur = 0; pos = 0; // заполним таблицу смещений while (cur != _frames) { SourceData->seek(pos, 0); SourceData->peek(head, 4); if (!mp3GetHeaderInfo(head, & info)) break; _vbrFrameOffTable[cur] = pos; pos += info.curFrameSize; cur++; } SourceData->seek(0, 0); } // выделим феймовый буфер #if AGSS_USE_MALLOC _frameBuffer = (BYTE *) malloc(_mpegDI.maxInputSize); #else _frameBuffer = (BYTE *) GlobalAlloc(GPTR, _mpegDI.maxInputSize); #endif if (!_frameBuffer) return; // прочитаем один фрейм if (SourceData->read(_frameBuffer, _curFrameSize) != _curFrameSize) { #if AGSS_USE_MALLOC free(_frameBuffer); #else GlobalFree(_frameBuffer); #endif _frameBuffer = 0; return; } // начало декодирования if (!mp3DecodeStart(_frameBuffer, _curFrameSize)) { #if AGSS_USE_MALLOC free(_frameBuffer); #else GlobalFree(_frameBuffer); #endif _frameBuffer = 0; return; } // подготовка к декодированию первого фрейма _mpegDP.header = _mpegDI.header; _mpegDP.bitRate = _mpegDI.bitRate; _mpegDP.inputBuf = _frameBuffer; _mpegDP.inputSize = _curFrameSize; _mpegDP.outputBuf = _sampleBuffer; _mpegDP.outputSize = _mpegDI.outputSize; // декодируем первый фрейм if (!mp3DecodeFrame(&_mpegDP)) { #if AGSS_USE_MALLOC free(_frameBuffer); #else GlobalFree(_frameBuffer); #endif _frameBuffer = 0; return; } // установим дополнительные параметры _curFrame = 0; _curSampleOffset = 0; // преобразуем данные для Direct X (иначе Direct X не сможет создать буфер) pcm_format->wFormatTag = 1; pcm_format->wBitsPerSample = 16; pcm_format->nSamplesPerSec = _frequency; pcm_format->nChannels = _channels; pcm_format->nBlockAlign = (pcm_format->nChannels * pcm_format->wBitsPerSample) >> 3; pcm_format->nAvgBytesPerSec = pcm_format->nBlockAlign * pcm_format->nSamplesPerSec; // файл определен flag = true; } //----------------------------------------------------------------------------- // Деструктор декодера // на входе : * // на выходе : * //----------------------------------------------------------------------------- CDecompressMpeg::~CDecompressMpeg() { if (_vbrFrameOffTable) { #if AGSS_USE_MALLOC free(_vbrFrameOffTable); #else GlobalFree(_vbrFrameOffTable); #endif _vbrFrameOffTable = 0; } if (_frameBuffer) { #if AGSS_USE_MALLOC free(_frameBuffer); #else GlobalFree(_frameBuffer); #endif _frameBuffer = 0; } } //----------------------------------------------------------------------------- // Декомпрессия Mp3 формата в моно данные // на входе : buffer - указатель на буфер // start - смещение в данных звука, в семплах // length - количество семплов для декодирования // на выходе : На сколько байт сдвинулся буфер в который // читали семплы //----------------------------------------------------------------------------- DWORD CDecompressMpeg::GetMonoSamples(void* buffer, DWORD start, DWORD length, bool loop) { DWORD NeedFrame; DWORD NeedOffset; DWORD samples; DWORD i; BYTE head[4]; short* dst = (short*) buffer; // проверка выхода за пределы if (start > _samplesInFile) return 0; // проверка на чтение сверх нормы if ((start + length) > _samplesInFile) length = _samplesInFile - start; // вычислим текущую позицию чтения NeedFrame = start / _samplesInFrame; NeedOffset = start % _samplesInFrame; // позиционируемся на данных if (!mp3seek(NeedFrame)) return 0; DWORD remaining = length; DWORD readsize = 0; bool readframe = false; while (remaining) { if ((_channels == 1) && (NeedOffset == 0) && (remaining > _samplesInFrame)) readframe = true; else readframe = false; if (_curFrame != NeedFrame) { _curFrame = NeedFrame; if (SourceData->peek(&head, 4) != 4) break; if (!mp3GetHeaderInfo(head, & _mpegHI)) return 0; _curFrameSize = _mpegHI.curFrameSize; if (SourceData->read(_frameBuffer, _curFrameSize) != _curFrameSize) return 0; _mpegDP.header = _mpegHI.header; _mpegDP.bitRate = _mpegHI.curBitRate; _mpegDP.inputBuf = _frameBuffer; _mpegDP.inputSize = _mpegHI.curFrameSize; _mpegDP.outputBuf = (readframe) ? dst : _sampleBuffer; _mpegDP.outputSize = _mpegHI.outputSize; // декодирование одного фрейма if (!mp3DecodeFrame(&_mpegDP)) return 0; } samples = _samplesInFrame - NeedOffset; readsize = (remaining > samples) ? samples : remaining; short* src = _sampleBuffer + (NeedOffset* _channels); if (_channels == 1) { if (!readframe) memcpy(dst, src, readsize * 2); dst += readsize; } else { for (i = 0; i < readsize; i++) { int s = ((int) src[0] + (int) src[1]) >> 1; s = (s < -32768) ? -32768 : (s > 32767) ? 32767 : s; *dst++ = (short) s; src += 2; } } NeedOffset = 0; remaining -= readsize; if (remaining) NeedFrame++; } return ((DWORD) dst - (DWORD) buffer); } //----------------------------------------------------------------------------- // Декомпрессия Mp3 формата в стерео данные // на входе : buffer - указатель на буфер // start - смещение в данных звука, в семплах // length - количество семплов для декодирования // на выходе : На сколько байт сдвинулся буфер в который // читали семплы //----------------------------------------------------------------------------- DWORD CDecompressMpeg::GetStereoSamples(void* buffer, DWORD start, DWORD length, bool loop) { DWORD NeedFrame; DWORD NeedOffset; // DWORD NeedFrameOffset; DWORD samples; DWORD i; BYTE head[4]; // int off; short* dst = (short*) buffer; // проверка выхода за пределы if (start > _samplesInFile) return 0; // проверка на чтение сверх нормы if ((start + length) > _samplesInFile) length = _samplesInFile - start; // вычислим текущую позицию чтения NeedFrame = start / _samplesInFrame; NeedOffset = start % _samplesInFrame; // позиционируемся на данных if (!mp3seek(NeedFrame)) return 0; DWORD remaining = length; DWORD readsize = 0; bool readframe = false; while (remaining) { if ((_channels == 2) && (NeedOffset == 0) && (remaining > _samplesInFrame)) readframe = true; else readframe = false; if (_curFrame != NeedFrame) { _curFrame = NeedFrame; SourceData->peek(&head, 4); if (!mp3GetHeaderInfo(head, & _mpegHI)) return 0; _curFrameSize = _mpegHI.curFrameSize; if (SourceData->read(_frameBuffer, _curFrameSize) != _curFrameSize) return 0; _mpegDP.header = _mpegHI.header; _mpegDP.bitRate = _mpegHI.curBitRate; _mpegDP.inputBuf = _frameBuffer; _mpegDP.inputSize = _mpegHI.curFrameSize; _mpegDP.outputBuf = (readframe) ? dst : _sampleBuffer; _mpegDP.outputSize = _mpegHI.outputSize; // декодирование одного фрейма if (!mp3DecodeFrame(&_mpegDP)) return 0; } samples = _samplesInFrame - NeedOffset; readsize = (remaining > samples) ? samples : remaining; short* src = _sampleBuffer + (NeedOffset* _channels); if (_channels == 1) { for (i = 0; i < readsize; i++) { *dst++ = *src; *dst++ = *src; src++; } } else { if (!readframe) memcpy(dst, src, readsize * 4); dst += readsize * 2; } NeedOffset = 0; remaining -= readsize; if (remaining) NeedFrame++; } return ((DWORD) dst - (DWORD) buffer); } //----------------------------------------------------------------------------- // Создание тишины на заданом отрезке буфера моно режим // на входе : buffer - указатель на буфер // length - количество семплов // на выходе : На сколько байт сдвинулся буфер //----------------------------------------------------------------------------- DWORD CDecompressMpeg::GetMonoMute(void* buffer, DWORD length) { length <<= 1; memset(buffer, 0, length); return length; } //----------------------------------------------------------------------------- // Создание тишины на заданом отрезке буфера стерео режим // на входе : buffer - указатель на буфер // length - количество семплов // на выходе : На сколько байт сдвинулся буфер //----------------------------------------------------------------------------- DWORD CDecompressMpeg::GetStereoMute(void* buffer, DWORD length) { length <<= 2; memset(buffer, 0, length); return length; } //----------------------------------------------------------------------------- // Получение количества семплов в файле // на входе : * // на выходе : Количество семплов в файла //----------------------------------------------------------------------------- DWORD CDecompressMpeg::GetSamplesInFile(void) { return _samplesInFile; } //----------------------------------------------------------------------------- // Получение количества байт в треке моно режим // на входе : * // на выходе : Количество баит в треке //----------------------------------------------------------------------------- DWORD CDecompressMpeg::GetRealMonoDataSize(void) { return _samplesInFile * 2; } //----------------------------------------------------------------------------- // Получение количества байт в треке стерео режим // на входе : * // на выходе : Количество баит в треке //----------------------------------------------------------------------------- DWORD CDecompressMpeg::GetRealStereoDataSize(void) { return _samplesInFile * 4; }
gecko0307/squall
source/SoundFile/MP3/MpegDecoder.cpp
C++
mit
77,394
import { moduleForModel, test } from 'ember-qunit'; import Pretender from 'pretender'; // ToDo: Install ember-cli-faker import mocks from './mocks'; const { inventoryMock, productMock, componentsMock } = mocks; let mockServer; moduleForModel('inventory', 'Unit | Serializer | inventory', { needs: ['serializer:application', 'model:product', 'model:inventory', 'model:component'], beforeEach() { mockServer = new Pretender(function() { this.get('/products', function() { const response = { records: [productMock] }; return [200, { "Content-Type": "application/json" }, JSON.stringify(response)]; }); this.get(`/products/${productMock.id}`, function() { return [200, { "Content-Type": "application/json" }, JSON.stringify(productMock)]; }); this.get('/inventories', function() { const response = { records: [inventoryMock] }; return [200, { "Content-Type": "application/json" }, JSON.stringify(response)]; }); this.get(`/components/${componentsMock[0].id}`, function() { return [200, { "Content-Type": "application/json" }, JSON.stringify(componentsMock[0])]; }); this.get(`/components/${componentsMock[1].id}`, function() { return [200, { "Content-Type": "application/json" }, JSON.stringify(componentsMock[1])]; }); }); }, afterEach() { mockServer.shutdown(); } }); test('it serializes records', function(assert) { return this.store().findAll('inventory').then((inventories) => { assert.equal(inventories.get('length'), 1); const inventory = inventories.objectAt(0); assert.ok(inventory.get('created')); assert.equal(inventory.get('qty'), inventoryMock.fields['qty']); assert.equal(inventory.get('restock-at'), inventoryMock.fields['restock-at']); }); }); test('it serializes belongsTo relationship', function(assert) { return this.store().findAll('inventory').then((inventories) => { const inventory = inventories.objectAt(0); inventory.get('product').then((product) => { assert.equal(product.get('name'), productMock.fields.name); assert.equal(product.get('description'), productMock.fields.description); }); }); }); test('it serializes hasMany relationship', function(assert) { return this.store().findAll('product').then((products) => { const product = products.objectAt(0); product.get('components').then((components) => { components.forEach((component, index) => { assert.equal(component.get('name'), componentsMock[index].fields.name); }); }); }); });
benoror/ember-airtable
tests/unit/serializers/inventory-test.js
JavaScript
mit
2,679
# Acknowledgements This application makes use of the following third party libraries: ## FMDB If you are using FMDB in your project, I'd love to hear about it. Let Gus know by sending an email to gus@flyingmeat.com. And if you happen to come across either Gus Mueller or Rob Ryan in a bar, you might consider purchasing a drink of their choosing if FMDB has been useful to you. Finally, and shortly, this is the MIT License. Copyright (c) 2008-2014 Flying Meat 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. ## MBProgressHUD Copyright (c) 2009-2015 Matej Bukovinski 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. Generated by CocoaPods - http://cocoapods.org
githubydq/DQLoveWords
LoveWords/Pods/Target Support Files/Pods/Pods-acknowledgements.markdown
Markdown
mit
2,626
package com.asksunny.batch.tasklets; public class Demo1 { long id; String name; public Demo1() { } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
devsunny/app-galleries
batch-flow-process/src/main/java/com/asksunny/batch/tasklets/Demo1.java
Java
mit
341
package net.glowstone.net.codec.play.game; import com.flowpowered.network.Codec; import io.netty.buffer.ByteBuf; import java.io.IOException; import net.glowstone.net.GlowBufUtils; import net.glowstone.net.message.play.game.UpdateBlockEntityMessage; import net.glowstone.util.nbt.CompoundTag; import org.bukkit.util.BlockVector; public final class UpdateBlockEntityCodec implements Codec<UpdateBlockEntityMessage> { @Override public UpdateBlockEntityMessage decode(ByteBuf buffer) throws IOException { BlockVector pos = GlowBufUtils.readBlockPosition(buffer); int action = buffer.readByte(); CompoundTag nbt = GlowBufUtils.readCompound(buffer); return new UpdateBlockEntityMessage(pos.getBlockX(), pos.getBlockY(), pos.getBlockZ(), action, nbt); } @Override public ByteBuf encode(ByteBuf buf, UpdateBlockEntityMessage message) throws IOException { GlowBufUtils.writeBlockPosition(buf, message.getX(), message.getY(), message.getZ()); buf.writeByte(message.getAction()); GlowBufUtils.writeCompound(buf, message.getNbt()); return buf; } }
GlowstoneMC/GlowstonePlusPlus
src/main/java/net/glowstone/net/codec/play/game/UpdateBlockEntityCodec.java
Java
mit
1,140
//--------------------------------------------------------------------- // <copyright file="DuplicateStream.cs" company="Microsoft Corporation"> // Copyright (c) 1999, Microsoft Corporation. All rights reserved. // </copyright> // <summary> // Part of the Deployment Tools Foundation project. // </summary> //--------------------------------------------------------------------- namespace Microsoft.PackageManagement.Archivers.Internal.Compression { using System; using System.IO; /// <summary> /// Duplicates a source stream by maintaining a separate position. /// </summary> /// <remarks> /// WARNING: duplicate streams are not thread-safe with respect to each other or the original stream. /// If multiple threads use duplicate copies of the same stream, they must synchronize for any operations. /// </remarks> public class DuplicateStream : Stream { private Stream source; private long position; /// <summary> /// Creates a new duplicate of a stream. /// </summary> /// <param name="source">source of the duplicate</param> public DuplicateStream(Stream source) { if (source == null) { throw new ArgumentNullException("source"); } this.source = DuplicateStream.OriginalStream(source); } /// <summary> /// Gets the original stream that was used to create the duplicate. /// </summary> public Stream Source { get { return this.source; } } /// <summary> /// Gets a value indicating whether the source stream supports reading. /// </summary> /// <value>true if the stream supports reading; otherwise, false.</value> public override bool CanRead { get { return this.source.CanRead; } } /// <summary> /// Gets a value indicating whether the source stream supports writing. /// </summary> /// <value>true if the stream supports writing; otherwise, false.</value> public override bool CanWrite { get { return this.source.CanWrite; } } /// <summary> /// Gets a value indicating whether the source stream supports seeking. /// </summary> /// <value>true if the stream supports seeking; otherwise, false.</value> public override bool CanSeek { get { return this.source.CanSeek; } } /// <summary> /// Gets the length of the source stream. /// </summary> public override long Length { get { return this.source.Length; } } /// <summary> /// Gets or sets the position of the current stream, /// ignoring the position of the source stream. /// </summary> public override long Position { get { return this.position; } set { this.position = value; } } /// <summary> /// Retrieves the original stream from a possible duplicate stream. /// </summary> /// <param name="stream">Possible duplicate stream.</param> /// <returns>If the stream is a DuplicateStream, returns /// the duplicate's source; otherwise returns the same stream.</returns> public static Stream OriginalStream(Stream stream) { DuplicateStream dupStream = stream as DuplicateStream; return dupStream != null ? dupStream.Source : stream; } /// <summary> /// Flushes the source stream. /// </summary> public override void Flush() { this.source.Flush(); } /// <summary> /// Sets the length of the source stream. /// </summary> /// <param name="value">The desired length of the stream in bytes.</param> public override void SetLength(long value) { this.source.SetLength(value); } #if !CORECLR /// <summary> /// Closes the underlying stream, effectively closing ALL duplicates. /// </summary> public override void Close() { this.source.Close(); } #endif /// <summary> /// Disposes the stream /// </summary> /// <param name="disposing"></param> protected override void Dispose(bool disposing) { if (disposing) { this.source.Dispose(); } } /// <summary> /// Reads from the source stream while maintaining a separate position /// and not impacting the source stream's position. /// </summary> /// <param name="buffer">An array of bytes. When this method returns, the buffer /// contains the specified byte array with the values between offset and /// (offset + count - 1) replaced by the bytes read from the current source.</param> /// <param name="offset">The zero-based byte offset in buffer at which to begin /// storing the data read from the current stream.</param> /// <param name="count">The maximum number of bytes to be read from the current stream.</param> /// <returns>The total number of bytes read into the buffer. This can be less /// than the number of bytes requested if that many bytes are not currently available, /// or zero (0) if the end of the stream has been reached.</returns> public override int Read(byte[] buffer, int offset, int count) { long saveSourcePosition = this.source.Position; this.source.Position = this.position; int read = this.source.Read(buffer, offset, count); this.position = this.source.Position; this.source.Position = saveSourcePosition; return read; } /// <summary> /// Writes to the source stream while maintaining a separate position /// and not impacting the source stream's position. /// </summary> /// <param name="buffer">An array of bytes. This method copies count /// bytes from buffer to the current stream.</param> /// <param name="offset">The zero-based byte offset in buffer at which /// to begin copying bytes to the current stream.</param> /// <param name="count">The number of bytes to be written to the /// current stream.</param> public override void Write(byte[] buffer, int offset, int count) { long saveSourcePosition = this.source.Position; this.source.Position = this.position; this.source.Write(buffer, offset, count); this.position = this.source.Position; this.source.Position = saveSourcePosition; } /// <summary> /// Changes the position of this stream without impacting the /// source stream's position. /// </summary> /// <param name="offset">A byte offset relative to the origin parameter.</param> /// <param name="origin">A value of type SeekOrigin indicating the reference /// point used to obtain the new position.</param> /// <returns>The new position within the current stream.</returns> public override long Seek(long offset, SeekOrigin origin) { long originPosition = 0; if (origin == SeekOrigin.Current) { originPosition = this.position; } else if (origin == SeekOrigin.End) { originPosition = this.Length; } this.position = originPosition + offset; return this.position; } } }
OneGet/oneget
src/Microsoft.PackageManagement.ArchiverProviders/Compression/DuplicateStream.cs
C#
mit
8,313
+(function () { 'use strict'; angular .module('DashboardApplication') .controller('FileManagerRemoveFolderController', ['$scope', '$q', 'Event', 'FoldersRest', FileManagerRemoveFolderController]); function FileManagerRemoveFolderController($scope, $q, Event, FoldersRest) { var vm = this; var folderId = $scope.ngDialogData.folderId; vm.removeFolder = removeFolder; function removeFolder() { var id = folderId; var $defer = $q.defer(); FoldersRest.one(id).remove().then(function () { console.log("FoldersRest"); debugger; Event.publish('FOLDERS_TREEVIEW_UPDATED'); alert('فولدر با موفقیت حذف شد', 'انجام شد!'); $defer.resolve(); }, function (error) { $defer.reject(error); }); return $defer.promise; } } })();
MozhganNajafi/andisheh-bartar
source/dashboard/components/filemanager/controllers/removefolder.controller.js
JavaScript
mit
980
package co.colector.model.request; import java.util.ArrayList; import java.util.List; import co.colector.ColectorApplication; import co.colector.R; import co.colector.model.IdInputValue; import co.colector.model.IdValue; import co.colector.model.Survey; import co.colector.model.AnswerValue; import co.colector.session.AppSession; import co.colector.utils.NetworkUtils; /** * Created by dherrera on 11/10/15. */ public class SendSurveyRequest { private String colector_id; private String form_id; private String longitud; private String latitud; private String horaini; private String horafin; private List<IdInputValue> responses; public SendSurveyRequest(Survey survey) { this.colector_id = String.valueOf(AppSession.getInstance().getUser().getColector_id()); this.form_id = String.valueOf(survey.getForm_id()); this.longitud = survey.getInstanceLongitude(); this.latitud = survey.getInstanceLatitude(); this.horaini = survey.getInstanceHoraIni(); this.horafin = survey.getInstanceHoraFin(); this.setResponsesData(survey.getInstanceAnswers()); } public List<IdInputValue> getResponses() { return responses; } public void setResponses(List<IdInputValue> responses) { this.responses = responses; } private void setResponsesData(List<IdValue> responsesData) { responses = new ArrayList<>(); for (IdValue item : responsesData) { switch (item.getmType()) { case 6: case 14: case 16: for (AnswerValue answerValue : item.getValue()) if (!answerValue.getValue().equals("")) { int lastIndex = answerValue.getValue().length(); int slashIndex = answerValue.getValue().lastIndexOf("/"); responses.add(new IdInputValue(String.valueOf(item.getId()), ColectorApplication.getInstance().getString(R.string.image_name_format, NetworkUtils.getAndroidID(ColectorApplication.getInstance()), answerValue.getValue().substring((slashIndex + 1), lastIndex)))); } break; default: for (AnswerValue answerValue : item.getValue()) responses.add(new IdInputValue(String.valueOf(item.getId()), answerValue.getValue())); } } } }
jlpuma24/colector-android-telecomsoftsrs
app/src/main/java/co/colector/model/request/SendSurveyRequest.java
Java
mit
2,516
package controllers import ( "github.com/revel/revel" "AuthKeyPush/app/models" ) type Auth struct { *revel.Controller } func (c Auth) Github(code string) revel.Result { login := models.GitHub(code) if login == true { c.Session["login"] = "true" } else { c.Session["login"] = "false" c.Session["msg"] = "Login faied. Check conf/site.json or README.md" } return c.Redirect("/") }
rluisr/AuthKeyPush
app/controllers/auth.go
GO
mit
397
--- layout: about title: Sobre o Vagrant current: Sobre --- <div class="alert alert-block alert-info"> <strong>Observação:</strong> Essa página fala sobre o projeto Vagrant em si. Se em vez isso você estiver procurando pela documentação sobre o que o Vagrant é e como começar a utilizá-lo, vá para o <a href="/v1/docs/getting-started/index.html">guia de iniciação.</a> </div> # Sobre o Vagrant O Vagrant é um projeto livre e de código aberto. A visão do projeto é criar uma ferramenta que gerencie de forma transparente todas as partes complexas do desenvolvimento moderno com ambientes virtuais sem afetar demais o fluxo de trabalho diário do desenvolvedor. O Vagrant foi criado em [21 de janeiro de 2010](https://github.com/mitchellh/vagrant/commit/050bfd9c686b06c292a9614662b0ab1bbf652db3) por [Mitchell Hashimoto](https://github.com/mitchellh) e [John Bender](http://johnbender.us/). A primeira versão do Vagrant lançada foi a 0.1.0 em [7 de março de 2010](https://github.com/mitchellh/vagrant/commit/296f234b50440b81adc8b75160591e199572d06d). Hoje, o Vagrant é considerado estável e é usado por por milhares de pessoas no mundo inteiro. A visão do Vagrant se mantém inalterada, e avança em direção ao seu objetivo ambicioso de colocar todo o desenvolvimento para ambientes virtualizados tornando isso mais fácil do que não fazê-lo. Adicionalmente, o trabalho continua para que o Vagrant rode de forma idêntica em todas as principais plaformas e sistemas operacionais consumidos (Linux, Mac OS X e Windows). O desenvolvimento do Vagrant não é apoiado por apenas uma única empresa, e os desenvolvedores trabalham no Vagrant em seu tempo livre. Muito do trabalho e da ajuda que move o desenvolvimento do Vagrant é graças as generosas [contribuições](/contribute/index.html).
FriendsOfVagrant/friendsofvagrant.github.com
about.md
Markdown
mit
1,831
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "init.h" #include "util.h" #include "sync.h" #include "ui_interface.h" #include "base58.h" #include "bitcoinrpc.h" #include "db.h" #include <boost/asio.hpp> #include <boost/asio/ip/v6_only.hpp> #include <boost/bind.hpp> #include <boost/filesystem.hpp> #include <boost/foreach.hpp> #include <boost/iostreams/concepts.hpp> #include <boost/iostreams/stream.hpp> #include <boost/algorithm/string.hpp> #include <boost/lexical_cast.hpp> #include <boost/asio/ssl.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/shared_ptr.hpp> #include <list> using namespace std; using namespace boost; using namespace boost::asio; using namespace json_spirit; static std::string strRPCUserColonPass; // These are created by StartRPCThreads, destroyed in StopRPCThreads static asio::io_service* rpc_io_service = NULL; static ssl::context* rpc_ssl_context = NULL; static boost::thread_group* rpc_worker_group = NULL; static inline unsigned short GetDefaultRPCPort() { return GetBoolArg("-testnet", false) ? 16540 : 16541; } Object JSONRPCError(int code, const string& message) { Object error; error.push_back(Pair("code", code)); error.push_back(Pair("message", message)); return error; } void RPCTypeCheck(const Array& params, const list<Value_type>& typesExpected, bool fAllowNull) { unsigned int i = 0; BOOST_FOREACH(Value_type t, typesExpected) { if (params.size() <= i) break; const Value& v = params[i]; if (!((v.type() == t) || (fAllowNull && (v.type() == null_type)))) { string err = strprintf("Expected type %s, got %s", Value_type_name[t], Value_type_name[v.type()]); throw JSONRPCError(RPC_TYPE_ERROR, err); } i++; } } void RPCTypeCheck(const Object& o, const map<string, Value_type>& typesExpected, bool fAllowNull) { BOOST_FOREACH(const PAIRTYPE(string, Value_type)& t, typesExpected) { const Value& v = find_value(o, t.first); if (!fAllowNull && v.type() == null_type) throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first.c_str())); if (!((v.type() == t.second) || (fAllowNull && (v.type() == null_type)))) { string err = strprintf("Expected type %s for %s, got %s", Value_type_name[t.second], t.first.c_str(), Value_type_name[v.type()]); throw JSONRPCError(RPC_TYPE_ERROR, err); } } } int64 AmountFromValue(const Value& value) { double dAmount = value.get_real(); if (dAmount <= 0.0 || dAmount > 84000000.0) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount"); int64 nAmount = roundint64(dAmount * COIN); if (!MoneyRange(nAmount)) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount"); return nAmount; } Value ValueFromAmount(int64 amount) { return (double)amount / (double)COIN; } std::string HexBits(unsigned int nBits) { union { int32_t nBits; char cBits[4]; } uBits; uBits.nBits = htonl((int32_t)nBits); return HexStr(BEGIN(uBits.cBits), END(uBits.cBits)); } /// /// Note: This interface may still be subject to change. /// string CRPCTable::help(string strCommand) const { string strRet; set<rpcfn_type> setDone; for (map<string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi) { const CRPCCommand *pcmd = mi->second; string strMethod = mi->first; // We already filter duplicates, but these deprecated screw up the sort order if (strMethod.find("label") != string::npos) continue; if (strCommand != "" && strMethod != strCommand) continue; if (pcmd->reqWallet && !pwalletMain) continue; try { Array params; rpcfn_type pfn = pcmd->actor; if (setDone.insert(pfn).second) (*pfn)(params, true); } catch (std::exception& e) { // Help text is returned in an exception string strHelp = string(e.what()); if (strCommand == "") if (strHelp.find('\n') != string::npos) strHelp = strHelp.substr(0, strHelp.find('\n')); strRet += strHelp + "\n"; } } if (strRet == "") strRet = strprintf("help: unknown command: %s\n", strCommand.c_str()); strRet = strRet.substr(0,strRet.size()-1); return strRet; } Value help(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "help [command]\n" "List commands, or get help for a command."); string strCommand; if (params.size() > 0) strCommand = params[0].get_str(); return tableRPC.help(strCommand); } Value stop(const Array& params, bool fHelp) { // Accept the deprecated and ignored 'detach' boolean argument if (fHelp || params.size() > 1) throw runtime_error( "stop\n" "Stop TMCoin server."); // Shutdown will take long enough that the response should get back StartShutdown(); return "TMCoin server stopping"; } // // Call Table // static const CRPCCommand vRPCCommands[] = { // name actor (function) okSafeMode threadSafe reqWallet // ------------------------ ----------------------- ---------- ---------- --------- { "help", &help, true, true, false }, { "stop", &stop, true, true, false }, { "getblockcount", &getblockcount, true, false, false }, { "getbestblockhash", &getbestblockhash, true, false, false }, { "getconnectioncount", &getconnectioncount, true, false, false }, { "getpeerinfo", &getpeerinfo, true, false, false }, { "addnode", &addnode, true, true, false }, { "getaddednodeinfo", &getaddednodeinfo, true, true, false }, { "getdifficulty", &getdifficulty, true, false, false }, { "getnetworkhashps", &getnetworkhashps, true, false, false }, { "getgenerate", &getgenerate, true, false, false }, { "setgenerate", &setgenerate, true, false, true }, { "gethashespersec", &gethashespersec, true, false, false }, { "getinfo", &getinfo, true, false, false }, { "getmininginfo", &getmininginfo, true, false, false }, { "getnewaddress", &getnewaddress, true, false, true }, { "getaccountaddress", &getaccountaddress, true, false, true }, { "setaccount", &setaccount, true, false, true }, { "getaccount", &getaccount, false, false, true }, { "getaddressesbyaccount", &getaddressesbyaccount, true, false, true }, { "sendtoaddress", &sendtoaddress, false, false, true }, { "getreceivedbyaddress", &getreceivedbyaddress, false, false, true }, { "getreceivedbyaccount", &getreceivedbyaccount, false, false, true }, { "listreceivedbyaddress", &listreceivedbyaddress, false, false, true }, { "listreceivedbyaccount", &listreceivedbyaccount, false, false, true }, { "backupwallet", &backupwallet, true, false, true }, { "keypoolrefill", &keypoolrefill, true, false, true }, { "walletpassphrase", &walletpassphrase, true, false, true }, { "walletpassphrasechange", &walletpassphrasechange, false, false, true }, { "walletlock", &walletlock, true, false, true }, { "encryptwallet", &encryptwallet, false, false, true }, { "validateaddress", &validateaddress, true, false, false }, { "getbalance", &getbalance, false, false, true }, { "move", &movecmd, false, false, true }, { "sendfrom", &sendfrom, false, false, true }, { "sendmany", &sendmany, false, false, true }, { "addmultisigaddress", &addmultisigaddress, false, false, true }, { "createmultisig", &createmultisig, true, true , false }, { "getrawmempool", &getrawmempool, true, false, false }, { "getblock", &getblock, false, false, false }, { "getblockhash", &getblockhash, false, false, false }, { "gettransaction", &gettransaction, false, false, true }, { "listtransactions", &listtransactions, false, false, true }, { "listaddressgroupings", &listaddressgroupings, false, false, true }, { "signmessage", &signmessage, false, false, true }, { "verifymessage", &verifymessage, false, false, false }, { "getwork", &getwork, true, false, true }, { "getworkex", &getworkex, true, false, true }, { "listaccounts", &listaccounts, false, false, true }, { "settxfee", &settxfee, false, false, true }, { "getblocktemplate", &getblocktemplate, true, false, false }, { "submitblock", &submitblock, false, false, false }, { "setmininput", &setmininput, false, false, false }, { "listsinceblock", &listsinceblock, false, false, true }, { "makekeypair", &makekeypair, true, false, true }, { "dumpprivkey", &dumpprivkey, true, false, true }, { "importprivkey", &importprivkey, false, false, true }, { "listunspent", &listunspent, false, false, true }, { "getrawtransaction", &getrawtransaction, false, false, false }, { "createrawtransaction", &createrawtransaction, false, false, false }, { "decoderawtransaction", &decoderawtransaction, false, false, false }, { "signrawtransaction", &signrawtransaction, false, false, false }, { "sendrawtransaction", &sendrawtransaction, false, false, false }, { "gettxoutsetinfo", &gettxoutsetinfo, true, false, false }, { "gettxout", &gettxout, true, false, false }, { "lockunspent", &lockunspent, false, false, true }, { "listlockunspent", &listlockunspent, false, false, true }, { "verifychain", &verifychain, true, false, false }, }; CRPCTable::CRPCTable() { unsigned int vcidx; for (vcidx = 0; vcidx < (sizeof(vRPCCommands) / sizeof(vRPCCommands[0])); vcidx++) { const CRPCCommand *pcmd; pcmd = &vRPCCommands[vcidx]; mapCommands[pcmd->name] = pcmd; } } const CRPCCommand *CRPCTable::operator[](string name) const { map<string, const CRPCCommand*>::const_iterator it = mapCommands.find(name); if (it == mapCommands.end()) return NULL; return (*it).second; } // // HTTP protocol // // This ain't Apache. We're just using HTTP header for the length field // and to be compatible with other JSON-RPC implementations. // string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders) { ostringstream s; s << "POST / HTTP/1.1\r\n" << "User-Agent: tmcoin-json-rpc/" << FormatFullVersion() << "\r\n" << "Host: 127.0.0.1\r\n" << "Content-Type: application/json\r\n" << "Content-Length: " << strMsg.size() << "\r\n" << "Connection: close\r\n" << "Accept: application/json\r\n"; BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapRequestHeaders) s << item.first << ": " << item.second << "\r\n"; s << "\r\n" << strMsg; return s.str(); } string rfc1123Time() { char buffer[64]; time_t now; time(&now); struct tm* now_gmt = gmtime(&now); string locale(setlocale(LC_TIME, NULL)); setlocale(LC_TIME, "C"); // we want POSIX (aka "C") weekday/month strings strftime(buffer, sizeof(buffer), "%a, %d %b %Y %H:%M:%S +0000", now_gmt); setlocale(LC_TIME, locale.c_str()); return string(buffer); } static string HTTPReply(int nStatus, const string& strMsg, bool keepalive) { if (nStatus == HTTP_UNAUTHORIZED) return strprintf("HTTP/1.0 401 Authorization Required\r\n" "Date: %s\r\n" "Server: tmcoin-json-rpc/%s\r\n" "WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n" "Content-Type: text/html\r\n" "Content-Length: 296\r\n" "\r\n" "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n" "\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\r\n" "<HTML>\r\n" "<HEAD>\r\n" "<TITLE>Error</TITLE>\r\n" "<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n" "</HEAD>\r\n" "<BODY><H1>401 Unauthorized.</H1></BODY>\r\n" "</HTML>\r\n", rfc1123Time().c_str(), FormatFullVersion().c_str()); const char *cStatus; if (nStatus == HTTP_OK) cStatus = "OK"; else if (nStatus == HTTP_BAD_REQUEST) cStatus = "Bad Request"; else if (nStatus == HTTP_FORBIDDEN) cStatus = "Forbidden"; else if (nStatus == HTTP_NOT_FOUND) cStatus = "Not Found"; else if (nStatus == HTTP_INTERNAL_SERVER_ERROR) cStatus = "Internal Server Error"; else cStatus = ""; return strprintf( "HTTP/1.1 %d %s\r\n" "Date: %s\r\n" "Connection: %s\r\n" "Content-Length: %"PRIszu"\r\n" "Content-Type: application/json\r\n" "Server: tmcoin-json-rpc/%s\r\n" "\r\n" "%s", nStatus, cStatus, rfc1123Time().c_str(), keepalive ? "keep-alive" : "close", strMsg.size(), FormatFullVersion().c_str(), strMsg.c_str()); } bool ReadHTTPRequestLine(std::basic_istream<char>& stream, int &proto, string& http_method, string& http_uri) { string str; getline(stream, str); // HTTP request line is space-delimited vector<string> vWords; boost::split(vWords, str, boost::is_any_of(" ")); if (vWords.size() < 2) return false; // HTTP methods permitted: GET, POST http_method = vWords[0]; if (http_method != "GET" && http_method != "POST") return false; // HTTP URI must be an absolute path, relative to current host http_uri = vWords[1]; if (http_uri.size() == 0 || http_uri[0] != '/') return false; // parse proto, if present string strProto = ""; if (vWords.size() > 2) strProto = vWords[2]; proto = 0; const char *ver = strstr(strProto.c_str(), "HTTP/1."); if (ver != NULL) proto = atoi(ver+7); return true; } int ReadHTTPStatus(std::basic_istream<char>& stream, int &proto) { string str; getline(stream, str); vector<string> vWords; boost::split(vWords, str, boost::is_any_of(" ")); if (vWords.size() < 2) return HTTP_INTERNAL_SERVER_ERROR; proto = 0; const char *ver = strstr(str.c_str(), "HTTP/1."); if (ver != NULL) proto = atoi(ver+7); return atoi(vWords[1].c_str()); } int ReadHTTPHeaders(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet) { int nLen = 0; loop { string str; std::getline(stream, str); if (str.empty() || str == "\r") break; string::size_type nColon = str.find(":"); if (nColon != string::npos) { string strHeader = str.substr(0, nColon); boost::trim(strHeader); boost::to_lower(strHeader); string strValue = str.substr(nColon+1); boost::trim(strValue); mapHeadersRet[strHeader] = strValue; if (strHeader == "content-length") nLen = atoi(strValue.c_str()); } } return nLen; } int ReadHTTPMessage(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet, string& strMessageRet, int nProto) { mapHeadersRet.clear(); strMessageRet = ""; // Read header int nLen = ReadHTTPHeaders(stream, mapHeadersRet); if (nLen < 0 || nLen > (int)MAX_SIZE) return HTTP_INTERNAL_SERVER_ERROR; // Read message if (nLen > 0) { vector<char> vch(nLen); stream.read(&vch[0], nLen); strMessageRet = string(vch.begin(), vch.end()); } string sConHdr = mapHeadersRet["connection"]; if ((sConHdr != "close") && (sConHdr != "keep-alive")) { if (nProto >= 1) mapHeadersRet["connection"] = "keep-alive"; else mapHeadersRet["connection"] = "close"; } return HTTP_OK; } bool HTTPAuthorized(map<string, string>& mapHeaders) { string strAuth = mapHeaders["authorization"]; if (strAuth.substr(0,6) != "Basic ") return false; string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64); string strUserPass = DecodeBase64(strUserPass64); return TimingResistantEqual(strUserPass, strRPCUserColonPass); } // // JSON-RPC protocol. Bitcoin speaks version 1.0 for maximum compatibility, // but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were // unspecified (HTTP errors and contents of 'error'). // // 1.0 spec: http://json-rpc.org/wiki/specification // 1.2 spec: http://groups.google.com/group/json-rpc/web/json-rpc-over-http // http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx // string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id) { Object request; request.push_back(Pair("method", strMethod)); request.push_back(Pair("params", params)); request.push_back(Pair("id", id)); return write_string(Value(request), false) + "\n"; } Object JSONRPCReplyObj(const Value& result, const Value& error, const Value& id) { Object reply; if (error.type() != null_type) reply.push_back(Pair("result", Value::null)); else reply.push_back(Pair("result", result)); reply.push_back(Pair("error", error)); reply.push_back(Pair("id", id)); return reply; } string JSONRPCReply(const Value& result, const Value& error, const Value& id) { Object reply = JSONRPCReplyObj(result, error, id); return write_string(Value(reply), false) + "\n"; } void ErrorReply(std::ostream& stream, const Object& objError, const Value& id) { // Send error reply from json-rpc error object int nStatus = HTTP_INTERNAL_SERVER_ERROR; int code = find_value(objError, "code").get_int(); if (code == RPC_INVALID_REQUEST) nStatus = HTTP_BAD_REQUEST; else if (code == RPC_METHOD_NOT_FOUND) nStatus = HTTP_NOT_FOUND; string strReply = JSONRPCReply(Value::null, objError, id); stream << HTTPReply(nStatus, strReply, false) << std::flush; } bool ClientAllowed(const boost::asio::ip::address& address) { // Make sure that IPv4-compatible and IPv4-mapped IPv6 addresses are treated as IPv4 addresses if (address.is_v6() && (address.to_v6().is_v4_compatible() || address.to_v6().is_v4_mapped())) return ClientAllowed(address.to_v6().to_v4()); if (address == asio::ip::address_v4::loopback() || address == asio::ip::address_v6::loopback() || (address.is_v4() // Check whether IPv4 addresses match 127.0.0.0/8 (loopback subnet) && (address.to_v4().to_ulong() & 0xff000000) == 0x7f000000)) return true; const string strAddress = address.to_string(); const vector<string>& vAllow = mapMultiArgs["-rpcallowip"]; BOOST_FOREACH(string strAllow, vAllow) if (WildcardMatch(strAddress, strAllow)) return true; return false; } // // IOStream device that speaks SSL but can also speak non-SSL // template <typename Protocol> class SSLIOStreamDevice : public iostreams::device<iostreams::bidirectional> { public: SSLIOStreamDevice(asio::ssl::stream<typename Protocol::socket> &streamIn, bool fUseSSLIn) : stream(streamIn) { fUseSSL = fUseSSLIn; fNeedHandshake = fUseSSLIn; } void handshake(ssl::stream_base::handshake_type role) { if (!fNeedHandshake) return; fNeedHandshake = false; stream.handshake(role); } std::streamsize read(char* s, std::streamsize n) { handshake(ssl::stream_base::server); // HTTPS servers read first if (fUseSSL) return stream.read_some(asio::buffer(s, n)); return stream.next_layer().read_some(asio::buffer(s, n)); } std::streamsize write(const char* s, std::streamsize n) { handshake(ssl::stream_base::client); // HTTPS clients write first if (fUseSSL) return asio::write(stream, asio::buffer(s, n)); return asio::write(stream.next_layer(), asio::buffer(s, n)); } bool connect(const std::string& server, const std::string& port) { ip::tcp::resolver resolver(stream.get_io_service()); ip::tcp::resolver::query query(server.c_str(), port.c_str()); ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query); ip::tcp::resolver::iterator end; boost::system::error_code error = asio::error::host_not_found; while (error && endpoint_iterator != end) { stream.lowest_layer().close(); stream.lowest_layer().connect(*endpoint_iterator++, error); } if (error) return false; return true; } private: bool fNeedHandshake; bool fUseSSL; asio::ssl::stream<typename Protocol::socket>& stream; }; class AcceptedConnection { public: virtual ~AcceptedConnection() {} virtual std::iostream& stream() = 0; virtual std::string peer_address_to_string() const = 0; virtual void close() = 0; }; template <typename Protocol> class AcceptedConnectionImpl : public AcceptedConnection { public: AcceptedConnectionImpl( asio::io_service& io_service, ssl::context &context, bool fUseSSL) : sslStream(io_service, context), _d(sslStream, fUseSSL), _stream(_d) { } virtual std::iostream& stream() { return _stream; } virtual std::string peer_address_to_string() const { return peer.address().to_string(); } virtual void close() { _stream.close(); } typename Protocol::endpoint peer; asio::ssl::stream<typename Protocol::socket> sslStream; private: SSLIOStreamDevice<Protocol> _d; iostreams::stream< SSLIOStreamDevice<Protocol> > _stream; }; void ServiceConnection(AcceptedConnection *conn); // Forward declaration required for RPCListen template <typename Protocol, typename SocketAcceptorService> static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor, ssl::context& context, bool fUseSSL, AcceptedConnection* conn, const boost::system::error_code& error); /** * Sets up I/O resources to accept and handle a new connection. */ template <typename Protocol, typename SocketAcceptorService> static void RPCListen(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor, ssl::context& context, const bool fUseSSL) { // Accept connection AcceptedConnectionImpl<Protocol>* conn = new AcceptedConnectionImpl<Protocol>(acceptor->get_io_service(), context, fUseSSL); acceptor->async_accept( conn->sslStream.lowest_layer(), conn->peer, boost::bind(&RPCAcceptHandler<Protocol, SocketAcceptorService>, acceptor, boost::ref(context), fUseSSL, conn, boost::asio::placeholders::error)); } /** * Accept and handle incoming connection. */ template <typename Protocol, typename SocketAcceptorService> static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor, ssl::context& context, const bool fUseSSL, AcceptedConnection* conn, const boost::system::error_code& error) { // Immediately start accepting new connections, except when we're cancelled or our socket is closed. if (error != asio::error::operation_aborted && acceptor->is_open()) RPCListen(acceptor, context, fUseSSL); AcceptedConnectionImpl<ip::tcp>* tcp_conn = dynamic_cast< AcceptedConnectionImpl<ip::tcp>* >(conn); // TODO: Actually handle errors if (error) { delete conn; } // Restrict callers by IP. It is important to // do this before starting client thread, to filter out // certain DoS and misbehaving clients. else if (tcp_conn && !ClientAllowed(tcp_conn->peer.address())) { // Only send a 403 if we're not using SSL to prevent a DoS during the SSL handshake. if (!fUseSSL) conn->stream() << HTTPReply(HTTP_FORBIDDEN, "", false) << std::flush; delete conn; } else { ServiceConnection(conn); conn->close(); delete conn; } } void StartRPCThreads() { strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]; if ((mapArgs["-rpcpassword"] == "") || (mapArgs["-rpcuser"] == mapArgs["-rpcpassword"])) { unsigned char rand_pwd[32]; RAND_bytes(rand_pwd, 32); string strWhatAmI = "To use tmcoind"; if (mapArgs.count("-server")) strWhatAmI = strprintf(_("To use the %s option"), "\"-server\""); else if (mapArgs.count("-daemon")) strWhatAmI = strprintf(_("To use the %s option"), "\"-daemon\""); uiInterface.ThreadSafeMessageBox(strprintf( _("%s, you must set a rpcpassword in the configuration file:\n" "%s\n" "It is recommended you use the following random password:\n" "rpcuser=tmcoinrpc\n" "rpcpassword=%s\n" "(you do not need to remember this password)\n" "The username and password MUST NOT be the same.\n" "If the file does not exist, create it with owner-readable-only file permissions.\n" "It is also recommended to set alertnotify so you are notified of problems;\n" "for example: alertnotify=echo %%s | mail -s \"TMCoin Alert\" admin@foo.com\n"), strWhatAmI.c_str(), GetConfigFile().string().c_str(), EncodeBase58(&rand_pwd[0],&rand_pwd[0]+32).c_str()), "", CClientUIInterface::MSG_ERROR); StartShutdown(); return; } assert(rpc_io_service == NULL); rpc_io_service = new asio::io_service(); rpc_ssl_context = new ssl::context(*rpc_io_service, ssl::context::sslv23); const bool fUseSSL = GetBoolArg("-rpcssl"); if (fUseSSL) { rpc_ssl_context->set_options(ssl::context::no_sslv2); filesystem::path pathCertFile(GetArg("-rpcsslcertificatechainfile", "server.cert")); if (!pathCertFile.is_complete()) pathCertFile = filesystem::path(GetDataDir()) / pathCertFile; if (filesystem::exists(pathCertFile)) rpc_ssl_context->use_certificate_chain_file(pathCertFile.string()); else printf("ThreadRPCServer ERROR: missing server certificate file %s\n", pathCertFile.string().c_str()); filesystem::path pathPKFile(GetArg("-rpcsslprivatekeyfile", "server.pem")); if (!pathPKFile.is_complete()) pathPKFile = filesystem::path(GetDataDir()) / pathPKFile; if (filesystem::exists(pathPKFile)) rpc_ssl_context->use_private_key_file(pathPKFile.string(), ssl::context::pem); else printf("ThreadRPCServer ERROR: missing server private key file %s\n", pathPKFile.string().c_str()); string strCiphers = GetArg("-rpcsslciphers", "TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH"); SSL_CTX_set_cipher_list(rpc_ssl_context->impl(), strCiphers.c_str()); } // Try a dual IPv6/IPv4 socket, falling back to separate IPv4 and IPv6 sockets const bool loopback = !mapArgs.count("-rpcallowip"); asio::ip::address bindAddress = loopback ? asio::ip::address_v6::loopback() : asio::ip::address_v6::any(); ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", GetDefaultRPCPort())); boost::system::error_code v6_only_error; boost::shared_ptr<ip::tcp::acceptor> acceptor(new ip::tcp::acceptor(*rpc_io_service)); bool fListening = false; std::string strerr; try { acceptor->open(endpoint.protocol()); acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true)); // Try making the socket dual IPv6/IPv4 (if listening on the "any" address) acceptor->set_option(boost::asio::ip::v6_only(loopback), v6_only_error); acceptor->bind(endpoint); acceptor->listen(socket_base::max_connections); RPCListen(acceptor, *rpc_ssl_context, fUseSSL); fListening = true; } catch(boost::system::system_error &e) { strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s"), endpoint.port(), e.what()); } try { // If dual IPv6/IPv4 failed (or we're opening loopback interfaces only), open IPv4 separately if (!fListening || loopback || v6_only_error) { bindAddress = loopback ? asio::ip::address_v4::loopback() : asio::ip::address_v4::any(); endpoint.address(bindAddress); acceptor.reset(new ip::tcp::acceptor(*rpc_io_service)); acceptor->open(endpoint.protocol()); acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true)); acceptor->bind(endpoint); acceptor->listen(socket_base::max_connections); RPCListen(acceptor, *rpc_ssl_context, fUseSSL); fListening = true; } } catch(boost::system::system_error &e) { strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv4: %s"), endpoint.port(), e.what()); } if (!fListening) { uiInterface.ThreadSafeMessageBox(strerr, "", CClientUIInterface::MSG_ERROR); StartShutdown(); return; } rpc_worker_group = new boost::thread_group(); for (int i = 0; i < GetArg("-rpcthreads", 4); i++) rpc_worker_group->create_thread(boost::bind(&asio::io_service::run, rpc_io_service)); } void StopRPCThreads() { if (rpc_io_service == NULL) return; rpc_io_service->stop(); rpc_worker_group->join_all(); delete rpc_worker_group; rpc_worker_group = NULL; delete rpc_ssl_context; rpc_ssl_context = NULL; delete rpc_io_service; rpc_io_service = NULL; } class JSONRequest { public: Value id; string strMethod; Array params; JSONRequest() { id = Value::null; } void parse(const Value& valRequest); }; void JSONRequest::parse(const Value& valRequest) { // Parse request if (valRequest.type() != obj_type) throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object"); const Object& request = valRequest.get_obj(); // Parse id now so errors from here on will have the id id = find_value(request, "id"); // Parse method Value valMethod = find_value(request, "method"); if (valMethod.type() == null_type) throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method"); if (valMethod.type() != str_type) throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string"); strMethod = valMethod.get_str(); if (strMethod != "getwork" && strMethod != "getworkex" && strMethod != "getblocktemplate") printf("ThreadRPCServer method=%s\n", strMethod.c_str()); // Parse params Value valParams = find_value(request, "params"); if (valParams.type() == array_type) params = valParams.get_array(); else if (valParams.type() == null_type) params = Array(); else throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array"); } static Object JSONRPCExecOne(const Value& req) { Object rpc_result; JSONRequest jreq; try { jreq.parse(req); Value result = tableRPC.execute(jreq.strMethod, jreq.params); rpc_result = JSONRPCReplyObj(result, Value::null, jreq.id); } catch (Object& objError) { rpc_result = JSONRPCReplyObj(Value::null, objError, jreq.id); } catch (std::exception& e) { rpc_result = JSONRPCReplyObj(Value::null, JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id); } return rpc_result; } static string JSONRPCExecBatch(const Array& vReq) { Array ret; for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++) ret.push_back(JSONRPCExecOne(vReq[reqIdx])); return write_string(Value(ret), false) + "\n"; } void ServiceConnection(AcceptedConnection *conn) { bool fRun = true; while (fRun) { int nProto = 0; map<string, string> mapHeaders; string strRequest, strMethod, strURI; // Read HTTP request line if (!ReadHTTPRequestLine(conn->stream(), nProto, strMethod, strURI)) break; // Read HTTP message headers and body ReadHTTPMessage(conn->stream(), mapHeaders, strRequest, nProto); if (strURI != "/") { conn->stream() << HTTPReply(HTTP_NOT_FOUND, "", false) << std::flush; break; } // Check authorization if (mapHeaders.count("authorization") == 0) { conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush; break; } if (!HTTPAuthorized(mapHeaders)) { printf("ThreadRPCServer incorrect password attempt from %s\n", conn->peer_address_to_string().c_str()); /* Deter brute-forcing short passwords. If this results in a DOS the user really shouldn't have their RPC port exposed.*/ if (mapArgs["-rpcpassword"].size() < 20) MilliSleep(250); conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush; break; } if (mapHeaders["connection"] == "close") fRun = false; JSONRequest jreq; try { // Parse request Value valRequest; if (!read_string(strRequest, valRequest)) throw JSONRPCError(RPC_PARSE_ERROR, "Parse error"); string strReply; // singleton request if (valRequest.type() == obj_type) { jreq.parse(valRequest); Value result = tableRPC.execute(jreq.strMethod, jreq.params); // Send reply strReply = JSONRPCReply(result, Value::null, jreq.id); // array of requests } else if (valRequest.type() == array_type) strReply = JSONRPCExecBatch(valRequest.get_array()); else throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error"); conn->stream() << HTTPReply(HTTP_OK, strReply, fRun) << std::flush; } catch (Object& objError) { ErrorReply(conn->stream(), objError, jreq.id); break; } catch (std::exception& e) { ErrorReply(conn->stream(), JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id); break; } } } json_spirit::Value CRPCTable::execute(const std::string &strMethod, const json_spirit::Array &params) const { // Find method const CRPCCommand *pcmd = tableRPC[strMethod]; if (!pcmd) throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found"); if (pcmd->reqWallet && !pwalletMain) throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (disabled)"); // Observe safe mode string strWarning = GetWarnings("rpc"); if (strWarning != "" && !GetBoolArg("-disablesafemode") && !pcmd->okSafeMode) throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, string("Safe mode: ") + strWarning); try { // Execute Value result; { if (pcmd->threadSafe) result = pcmd->actor(params, false); else if (!pwalletMain) { LOCK(cs_main); result = pcmd->actor(params, false); } else { LOCK2(cs_main, pwalletMain->cs_wallet); result = pcmd->actor(params, false); } } return result; } catch (std::exception& e) { throw JSONRPCError(RPC_MISC_ERROR, e.what()); } } Object CallRPC(const string& strMethod, const Array& params) { if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "") throw runtime_error(strprintf( _("You must set rpcpassword=<password> in the configuration file:\n%s\n" "If the file does not exist, create it with owner-readable-only file permissions."), GetConfigFile().string().c_str())); // Connect to localhost bool fUseSSL = GetBoolArg("-rpcssl"); asio::io_service io_service; ssl::context context(io_service, ssl::context::sslv23); context.set_options(ssl::context::no_sslv2); asio::ssl::stream<asio::ip::tcp::socket> sslStream(io_service, context); SSLIOStreamDevice<asio::ip::tcp> d(sslStream, fUseSSL); iostreams::stream< SSLIOStreamDevice<asio::ip::tcp> > stream(d); if (!d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", itostr(GetDefaultRPCPort())))) throw runtime_error("couldn't connect to server"); // HTTP basic authentication string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]); map<string, string> mapRequestHeaders; mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64; // Send request string strRequest = JSONRPCRequest(strMethod, params, 1); string strPost = HTTPPost(strRequest, mapRequestHeaders); stream << strPost << std::flush; // Receive HTTP reply status int nProto = 0; int nStatus = ReadHTTPStatus(stream, nProto); // Receive HTTP reply message headers and body map<string, string> mapHeaders; string strReply; ReadHTTPMessage(stream, mapHeaders, strReply, nProto); if (nStatus == HTTP_UNAUTHORIZED) throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)"); else if (nStatus >= 400 && nStatus != HTTP_BAD_REQUEST && nStatus != HTTP_NOT_FOUND && nStatus != HTTP_INTERNAL_SERVER_ERROR) throw runtime_error(strprintf("server returned HTTP error %d", nStatus)); else if (strReply.empty()) throw runtime_error("no response from server"); // Parse reply Value valReply; if (!read_string(strReply, valReply)) throw runtime_error("couldn't parse reply from server"); const Object& reply = valReply.get_obj(); if (reply.empty()) throw runtime_error("expected reply to have result, error and id properties"); return reply; } template<typename T> void ConvertTo(Value& value, bool fAllowNull=false) { if (fAllowNull && value.type() == null_type) return; if (value.type() == str_type) { // reinterpret string as unquoted json value Value value2; string strJSON = value.get_str(); if (!read_string(strJSON, value2)) throw runtime_error(string("Error parsing JSON:")+strJSON); ConvertTo<T>(value2, fAllowNull); value = value2; } else { value = value.get_value<T>(); } } // Convert strings to command-specific RPC representation Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams) { Array params; BOOST_FOREACH(const std::string &param, strParams) params.push_back(param); int n = params.size(); // // Special case non-string parameter types // if (strMethod == "stop" && n > 0) ConvertTo<bool>(params[0]); if (strMethod == "getaddednodeinfo" && n > 0) ConvertTo<bool>(params[0]); if (strMethod == "setgenerate" && n > 0) ConvertTo<bool>(params[0]); if (strMethod == "setgenerate" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "getnetworkhashps" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "getnetworkhashps" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "sendtoaddress" && n > 1) ConvertTo<double>(params[1]); if (strMethod == "settxfee" && n > 0) ConvertTo<double>(params[0]); if (strMethod == "setmininput" && n > 0) ConvertTo<double>(params[0]); if (strMethod == "getreceivedbyaddress" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "getreceivedbyaccount" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "listreceivedbyaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "listreceivedbyaddress" && n > 1) ConvertTo<bool>(params[1]); if (strMethod == "listreceivedbyaccount" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "listreceivedbyaccount" && n > 1) ConvertTo<bool>(params[1]); if (strMethod == "getbalance" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "getblockhash" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "move" && n > 2) ConvertTo<double>(params[2]); if (strMethod == "move" && n > 3) ConvertTo<boost::int64_t>(params[3]); if (strMethod == "sendfrom" && n > 2) ConvertTo<double>(params[2]); if (strMethod == "sendfrom" && n > 3) ConvertTo<boost::int64_t>(params[3]); if (strMethod == "listtransactions" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "listtransactions" && n > 2) ConvertTo<boost::int64_t>(params[2]); if (strMethod == "listaccounts" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "walletpassphrase" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "getblocktemplate" && n > 0) ConvertTo<Object>(params[0]); if (strMethod == "listsinceblock" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "sendmany" && n > 1) ConvertTo<Object>(params[1]); if (strMethod == "sendmany" && n > 2) ConvertTo<boost::int64_t>(params[2]); if (strMethod == "addmultisigaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "addmultisigaddress" && n > 1) ConvertTo<Array>(params[1]); if (strMethod == "createmultisig" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "createmultisig" && n > 1) ConvertTo<Array>(params[1]); if (strMethod == "listunspent" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "listunspent" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "listunspent" && n > 2) ConvertTo<Array>(params[2]); if (strMethod == "getblock" && n > 1) ConvertTo<bool>(params[1]); if (strMethod == "getrawtransaction" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "createrawtransaction" && n > 0) ConvertTo<Array>(params[0]); if (strMethod == "createrawtransaction" && n > 1) ConvertTo<Object>(params[1]); if (strMethod == "signrawtransaction" && n > 1) ConvertTo<Array>(params[1], true); if (strMethod == "signrawtransaction" && n > 2) ConvertTo<Array>(params[2], true); if (strMethod == "gettxout" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "gettxout" && n > 2) ConvertTo<bool>(params[2]); if (strMethod == "lockunspent" && n > 0) ConvertTo<bool>(params[0]); if (strMethod == "lockunspent" && n > 1) ConvertTo<Array>(params[1]); if (strMethod == "importprivkey" && n > 2) ConvertTo<bool>(params[2]); if (strMethod == "verifychain" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "verifychain" && n > 1) ConvertTo<boost::int64_t>(params[1]); return params; } int CommandLineRPC(int argc, char *argv[]) { string strPrint; int nRet = 0; try { // Skip switches while (argc > 1 && IsSwitchChar(argv[1][0])) { argc--; argv++; } // Method if (argc < 2) throw runtime_error("too few parameters"); string strMethod = argv[1]; // Parameters default to strings std::vector<std::string> strParams(&argv[2], &argv[argc]); Array params = RPCConvertValues(strMethod, strParams); // Execute Object reply = CallRPC(strMethod, params); // Parse reply const Value& result = find_value(reply, "result"); const Value& error = find_value(reply, "error"); if (error.type() != null_type) { // Error strPrint = "error: " + write_string(error, false); int code = find_value(error.get_obj(), "code").get_int(); nRet = abs(code); } else { // Result if (result.type() == null_type) strPrint = ""; else if (result.type() == str_type) strPrint = result.get_str(); else strPrint = write_string(result, true); } } catch (boost::thread_interrupted) { throw; } catch (std::exception& e) { strPrint = string("error: ") + e.what(); nRet = 87; } catch (...) { PrintException(NULL, "CommandLineRPC()"); } if (strPrint != "") { fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str()); } return nRet; } #ifdef TEST int main(int argc, char *argv[]) { #ifdef _MSC_VER // Turn off Microsoft heap dump noise _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_WARN, CreateFile("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0)); #endif setbuf(stdin, NULL); setbuf(stdout, NULL); setbuf(stderr, NULL); try { if (argc >= 2 && string(argv[1]) == "-server") { printf("server ready\n"); ThreadRPCServer(NULL); } else { return CommandLineRPC(argc, argv); } } catch (boost::thread_interrupted) { throw; } catch (std::exception& e) { PrintException(&e, "main()"); } catch (...) { PrintException(NULL, "main()"); } return 0; } #endif const CRPCTable tableRPC;
w295472444/TMCOIN
src/bitcoinrpc.cpp
C++
mit
48,637
/** * @module {Module} utils/math * @parent utils * * The module's description is the first paragraph. * * The body of the module's documentation. */ import _ from 'lodash'; /** * @function * * This function's description is the first * paragraph. * * This starts the body. This text comes after the signature. * * @param {Number} first This param's description. * @param {Number} second This param's description. * @return {Number} This return value's description. */ export function sum(first, second){ ... }; /** * @property {{}} * * This function's description is the first * paragraph. * * @option {Number} pi The description of pi. * * @option {Number} e The description of e. */ export var constants = { pi: 3.14159265359, e: 2.71828 };
bitovi/documentjs
lib/process/test/module_with_multiple_exports.js
JavaScript
mit
781
<?php /* WebProfilerBundle:Collector:router.html.twig */ class __TwigTemplate_c8d21550850074782862265b813a9c2aea7c608253db98e24225c2ea859cc33f extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); // line 1 $this->parent = $this->loadTemplate("@WebProfiler/Profiler/layout.html.twig", "WebProfilerBundle:Collector:router.html.twig", 1); $this->blocks = array( 'toolbar' => array($this, 'block_toolbar'), 'menu' => array($this, 'block_menu'), 'panel' => array($this, 'block_panel'), ); } protected function doGetParent(array $context) { return "@WebProfiler/Profiler/layout.html.twig"; } protected function doDisplay(array $context, array $blocks = array()) { $__internal_4f799fe0cc7f22495efc73fba23694e0a3a0583a5214948f3c58038a44fe2573 = $this->env->getExtension("Symfony\\Bundle\\WebProfilerBundle\\Twig\\WebProfilerExtension"); $__internal_4f799fe0cc7f22495efc73fba23694e0a3a0583a5214948f3c58038a44fe2573->enter($__internal_4f799fe0cc7f22495efc73fba23694e0a3a0583a5214948f3c58038a44fe2573_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", "WebProfilerBundle:Collector:router.html.twig")); $__internal_e2229cc8c004aedff67d2ce1c45f9efcfa69922e12b762676067fdd639b13361 = $this->env->getExtension("Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension"); $__internal_e2229cc8c004aedff67d2ce1c45f9efcfa69922e12b762676067fdd639b13361->enter($__internal_e2229cc8c004aedff67d2ce1c45f9efcfa69922e12b762676067fdd639b13361_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", "WebProfilerBundle:Collector:router.html.twig")); $this->parent->display($context, array_merge($this->blocks, $blocks)); $__internal_4f799fe0cc7f22495efc73fba23694e0a3a0583a5214948f3c58038a44fe2573->leave($__internal_4f799fe0cc7f22495efc73fba23694e0a3a0583a5214948f3c58038a44fe2573_prof); $__internal_e2229cc8c004aedff67d2ce1c45f9efcfa69922e12b762676067fdd639b13361->leave($__internal_e2229cc8c004aedff67d2ce1c45f9efcfa69922e12b762676067fdd639b13361_prof); } // line 3 public function block_toolbar($context, array $blocks = array()) { $__internal_cb109454b38b7b24070cff9ccc466e56af2d95b49464b6409586a5d2d6a2c19a = $this->env->getExtension("Symfony\\Bundle\\WebProfilerBundle\\Twig\\WebProfilerExtension"); $__internal_cb109454b38b7b24070cff9ccc466e56af2d95b49464b6409586a5d2d6a2c19a->enter($__internal_cb109454b38b7b24070cff9ccc466e56af2d95b49464b6409586a5d2d6a2c19a_prof = new Twig_Profiler_Profile($this->getTemplateName(), "block", "toolbar")); $__internal_5f178640e8cca7dbb07a0d59d8a8fdfb7be7bfc9c63cb7423b245a520c7e632d = $this->env->getExtension("Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension"); $__internal_5f178640e8cca7dbb07a0d59d8a8fdfb7be7bfc9c63cb7423b245a520c7e632d->enter($__internal_5f178640e8cca7dbb07a0d59d8a8fdfb7be7bfc9c63cb7423b245a520c7e632d_prof = new Twig_Profiler_Profile($this->getTemplateName(), "block", "toolbar")); $__internal_5f178640e8cca7dbb07a0d59d8a8fdfb7be7bfc9c63cb7423b245a520c7e632d->leave($__internal_5f178640e8cca7dbb07a0d59d8a8fdfb7be7bfc9c63cb7423b245a520c7e632d_prof); $__internal_cb109454b38b7b24070cff9ccc466e56af2d95b49464b6409586a5d2d6a2c19a->leave($__internal_cb109454b38b7b24070cff9ccc466e56af2d95b49464b6409586a5d2d6a2c19a_prof); } // line 5 public function block_menu($context, array $blocks = array()) { $__internal_72ed7e1b4749995ea5e7260ecc524f48453edb598dbde0a3016fbc2e5b926b3d = $this->env->getExtension("Symfony\\Bundle\\WebProfilerBundle\\Twig\\WebProfilerExtension"); $__internal_72ed7e1b4749995ea5e7260ecc524f48453edb598dbde0a3016fbc2e5b926b3d->enter($__internal_72ed7e1b4749995ea5e7260ecc524f48453edb598dbde0a3016fbc2e5b926b3d_prof = new Twig_Profiler_Profile($this->getTemplateName(), "block", "menu")); $__internal_475683fdbeda0d78d3d7fe71e064ce50ca9a62435dad2752533107cf00f9f060 = $this->env->getExtension("Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension"); $__internal_475683fdbeda0d78d3d7fe71e064ce50ca9a62435dad2752533107cf00f9f060->enter($__internal_475683fdbeda0d78d3d7fe71e064ce50ca9a62435dad2752533107cf00f9f060_prof = new Twig_Profiler_Profile($this->getTemplateName(), "block", "menu")); // line 6 echo "<span class=\"label\"> <span class=\"icon\">"; // line 7 echo twig_include($this->env, $context, "@WebProfiler/Icon/router.svg"); echo "</span> <strong>Routing</strong> </span> "; $__internal_475683fdbeda0d78d3d7fe71e064ce50ca9a62435dad2752533107cf00f9f060->leave($__internal_475683fdbeda0d78d3d7fe71e064ce50ca9a62435dad2752533107cf00f9f060_prof); $__internal_72ed7e1b4749995ea5e7260ecc524f48453edb598dbde0a3016fbc2e5b926b3d->leave($__internal_72ed7e1b4749995ea5e7260ecc524f48453edb598dbde0a3016fbc2e5b926b3d_prof); } // line 12 public function block_panel($context, array $blocks = array()) { $__internal_c19da141a630f3669f5fe7c94e5a968903f29bcb7cd994a4051ecf7ff1079825 = $this->env->getExtension("Symfony\\Bundle\\WebProfilerBundle\\Twig\\WebProfilerExtension"); $__internal_c19da141a630f3669f5fe7c94e5a968903f29bcb7cd994a4051ecf7ff1079825->enter($__internal_c19da141a630f3669f5fe7c94e5a968903f29bcb7cd994a4051ecf7ff1079825_prof = new Twig_Profiler_Profile($this->getTemplateName(), "block", "panel")); $__internal_312c0a27d2cccc06836145cd58525914aabe820d95097702356e71e0e516ea07 = $this->env->getExtension("Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension"); $__internal_312c0a27d2cccc06836145cd58525914aabe820d95097702356e71e0e516ea07->enter($__internal_312c0a27d2cccc06836145cd58525914aabe820d95097702356e71e0e516ea07_prof = new Twig_Profiler_Profile($this->getTemplateName(), "block", "panel")); // line 13 echo " "; echo $this->env->getRuntime('Symfony\Bridge\Twig\Extension\HttpKernelRuntime')->renderFragment($this->env->getExtension('Symfony\Bridge\Twig\Extension\RoutingExtension')->getPath("_profiler_router", array("token" => (isset($context["token"]) ? $context["token"] : $this->getContext($context, "token"))))); echo " "; $__internal_312c0a27d2cccc06836145cd58525914aabe820d95097702356e71e0e516ea07->leave($__internal_312c0a27d2cccc06836145cd58525914aabe820d95097702356e71e0e516ea07_prof); $__internal_c19da141a630f3669f5fe7c94e5a968903f29bcb7cd994a4051ecf7ff1079825->leave($__internal_c19da141a630f3669f5fe7c94e5a968903f29bcb7cd994a4051ecf7ff1079825_prof); } public function getTemplateName() { return "WebProfilerBundle:Collector:router.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 94 => 13, 85 => 12, 71 => 7, 68 => 6, 59 => 5, 42 => 3, 11 => 1,); } /** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */ public function getSource() { @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED); return $this->getSourceContext()->getCode(); } public function getSourceContext() { return new Twig_Source("{% extends '@WebProfiler/Profiler/layout.html.twig' %} {% block toolbar %}{% endblock %} {% block menu %} <span class=\"label\"> <span class=\"icon\">{{ include('@WebProfiler/Icon/router.svg') }}</span> <strong>Routing</strong> </span> {% endblock %} {% block panel %} {{ render(path('_profiler_router', { token: token })) }} {% endblock %} ", "WebProfilerBundle:Collector:router.html.twig", "/Applications/MAMP/htdocs/Symfony/vendor/symfony/symfony/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Collector/router.html.twig"); } }
mehdiYal/Schoolium
var/cache/dev/twig/9d/9ddcdbb0671c46071f6efb8e5daeec192572165664b16d016f57f2b46b9702b3.php
PHP
mit
8,083
--- --- <!doctype html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Photo - A History of UCSF</title> <link href='http://fonts.googleapis.com/css?family=Gilda+Display%7CPT+Sans+Narrow:300' rel='stylesheet' type='text/css'> <link href="ucsf_history.css" rel="stylesheet" type="text/css" media="all" /> {% include google_analytics.html %} </head> <body> <div id="mainbody"> {% include ucsf_banner.html %} <div class="banner"><h1><a href="/">A History of UCSF</a></h1></div> <div id="insidebody"> <div id="photocopy"> <div id="photocopy_text"><h2 class="title"><span class="title-primary">Photos</span></h2> <div id="subhead">William Searby (1835-1909)</div> <br /> <img src="images/pictures/Searby.jpg" width="550" height="563"/><br /> <br/> <br/><br/> <br/> </div> </div> <div id="sidebar"> <div id="sidenav_inside">{% include search_include.html %}<br /> <div id="sidenavtype"> <a href="story.html" class="sidenavtype"><strong>THE STORY</strong></a><br/> <br/> <a href="special_topics.html" class="sidenavtype"><strong>SPECIAL TOPICS</strong></a><br/><br/> <a href="people.html" class="sidenavtype"><strong>PEOPLE</strong></a><br/> <br/> <div id="sidenav_subnav_header"><strong><a href="photos.html" class="sidenav_subnav_type_visited">PHOTOS</a></strong></div> <br/> <a href="buildings.html" class="sidenavtype"><strong>BUILDINGS</strong></a><br/> <br/> <a href="index.html" class="sidenavtype"><strong>HOME</strong></a></div> </div> </div> </div> {% include footer.html %} </div> {% include bottom_js.html %} </body> </html>
mizejewski/ucsf-history-website
photo_searby.html
HTML
mit
1,731
<div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">Relationships</h3> </div> <div class="panel-body"> <div ng-repeat="relationship in contactGroupMember.Relationships"> <div class="form-group"> <label for="inputRelationship" class="col-sm-2 control-label">Relationship</label> <div class="col-sm-10"> <input type="text" class="form-control" id="inputRelationship" placeholder="Relationship" ng-model="relationship.Name" /> </div> </div> <div class="form-group"> <div class="col-sm-10 col-sm-offset-2"> <button type="button" class="btn btn-default btn-xs" ng-click="contactGroupMember.removeRelationship(relationship)"><span class="glyphicon glyphicon-remove"></span> Remove</button> </div> </div> </div> <div class="form-group"> <div class="col-sm-12"> <button type="button" class="btn btn-default btn-xs" ng-click="contactGroupMember.addRelationship('')"><span class="glyphicon glyphicon-plus"></span> Add a Relationship</button> </div> </div> </div> </div>
ekyoung/contact-repository
Source/Web/Content/ContactGroups/EditContactGroupMemberRelationships.html
HTML
mit
1,261
#!/bin/bash # ./run pixel_inicio pixel_final pixel_paso frecuencia_inicio frecuencia_final # frecuencia_paso resolucion_espacial Rt modelo path COUNTERX=$1 while [ $COUNTERX -le $2 ]; do if [ ! -d "/home/vdelaluz/ARTs/papers/cavity2D/data/SEL05/${COUNTERX}" ]; then # Control will enter here if $DIRECTORY doesn't exist mkdir /home/vdelaluz/ARTs/papers/cavity2D/data/SEL05/${COUNTERX} fi COUNTER=$4 while [ $COUNTER -le $5 ]; do echo Computing $COUNTERX $COUNTER mpiexec -n 1 ./pakal -model $9 -min 1e-40 -r $7 -xy ${COUNTERX} 0 -detail 1 -big 1 -nu ${COUNTER} -Rt $8 -h 7.353e5 -f -7.36e5 -v 10 > /home/vdelaluz/ARTs/papers/cavity2D/data/SEL05/${COUNTERX}/${COUNTER}GHz.dat mv emission_${COUNTERX}_0.dat /home/vdelaluz/ARTs/papers/cavity2D/data/SEL05/${COUNTERX}/${COUNTER}GHz_emission_0_0.dat mv profile_${COUNTERX}_0.dat /home/vdelaluz/ARTs/papers/cavity2D/data/SEL05/${COUNTERX}/${COUNTER}GHz_profile_0_0.dat let COUNTER=COUNTER+$6 done let COUNTERX=COUNTERX+$3 done
itztli/pakal
scripts/run.sh
Shell
mit
1,003
<p> Yo </p> <div *ngFor ="let task of taskList;let i=index;" style="padding:10px;width:100%;"> <input type="checkbox" name="task" value= "xyz" [checked]="task.status!=='N'">{{task.name}} <br> <button (click)="clearTask(task)" style="display:inline-block;">Delete</button> </div> <div> <input type= "text" name ="enterTask" [(ngModel)]="taskName"> <button (click)="addTask()" class="btn-primary">Add</button> </div>
codetheif/toDo
src/do/todo.component.html
HTML
mit
446
<?php if ($_SESSION['manager']==""){ header("Location: admin_login.php"); exit; }; header("Location: admin_index.php"); ?>
ArvoGuo/old
manager/index.php
PHP
mit
147
using UnityEngine; using UnityEditor; using CreateThis.Factory.VR.UI.Button; namespace MMVR.Factory.UI.Button { [CustomEditor(typeof(FileManagerSaveButtonFactory))] [CanEditMultipleObjects] public class FileManagerSaveButtonFactoryEditor : MomentaryButtonFactoryEditor { SerializedProperty fileManager; protected override void OnEnable() { base.OnEnable(); fileManager = serializedObject.FindProperty("fileManager"); } protected override void BuildGenerateButton() { if (GUILayout.Button("Generate")) { if (target.GetType() == typeof(FileManagerSaveButtonFactory)) { FileManagerSaveButtonFactory buttonFactory = (FileManagerSaveButtonFactory)target; buttonFactory.Generate(); } } } protected override void AdditionalProperties() { base.AdditionalProperties(); EditorGUILayout.PropertyField(fileManager); } } }
createthis/mesh_maker_vr
Assets/MMVR/Factory/UI/Button/FileManager/Editor/FileManagerSaveButtonFactoryEditor.cs
C#
mit
1,032
var box, mbox; function demo() { cam ( 0, 20, 40 ); world = new OIMO.World(); world.add({ size:[50, 10, 50], pos:[0,-5,0] }); // ground var options = { type:'box', size:[10, 10, 10], pos:[0,20,0], density:1, move:true } box = world.add( options ); mbox = view.add( options ); // three mesh }; function update () { world.step(); mbox.position.copy( box.getPosition() ); mbox.quaternion.copy( box.getQuaternion() ); }
lo-th/Oimo.js
examples/docs/rigidbody.js
JavaScript
mit
504
class CreateCourses < ActiveRecord::Migration def change create_table :courses do |t| t.string :name t.string :short_name t.string :sisid t.text :description t.integer :department_id t.integer :term_id t.boolean :graded t.boolean :archived t.string :type t.timestamps end end end
JonBriggs/SISteMATIC
db/migrate/20131029185157_create_courses.rb
Ruby
mit
353
// // AppDelegate.h // topController // // Created by 张衡 on 2016/11/18. // Copyright © 2016年 张衡. All rights reserved. // #import <UIKit/UIKit.h> @interface AppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end
RXTeams/topController
topController/AppDelegate.h
C
mit
280
import traceback class EnsureExceptionHandledGuard: """Helper for ensuring that Future's exceptions were handled. This solves a nasty problem with Futures and Tasks that have an exception set: if nobody asks for the exception, the exception is never logged. This violates the Zen of Python: 'Errors should never pass silently. Unless explicitly silenced.' However, we don't want to log the exception as soon as set_exception() is called: if the calling code is written properly, it will get the exception and handle it properly. But we *do* want to log it if result() or exception() was never called -- otherwise developers waste a lot of time wondering why their buggy code fails silently. An earlier attempt added a __del__() method to the Future class itself, but this backfired because the presence of __del__() prevents garbage collection from breaking cycles. A way out of this catch-22 is to avoid having a __del__() method on the Future class itself, but instead to have a reference to a helper object with a __del__() method that logs the traceback, where we ensure that the helper object doesn't participate in cycles, and only the Future has a reference to it. The helper object is added when set_exception() is called. When the Future is collected, and the helper is present, the helper object is also collected, and its __del__() method will log the traceback. When the Future's result() or exception() method is called (and a helper object is present), it removes the the helper object, after calling its clear() method to prevent it from logging. One downside is that we do a fair amount of work to extract the traceback from the exception, even when it is never logged. It would seem cheaper to just store the exception object, but that references the traceback, which references stack frames, which may reference the Future, which references the _EnsureExceptionHandledGuard, and then the _EnsureExceptionHandledGuard would be included in a cycle, which is what we're trying to avoid! As an optimization, we don't immediately format the exception; we only do the work when activate() is called, which call is delayed until after all the Future's callbacks have run. Since usually a Future has at least one callback (typically set by 'yield from') and usually that callback extracts the callback, thereby removing the need to format the exception. PS. I don't claim credit for this solution. I first heard of it in a discussion about closing files when they are collected. """ __slots__ = ['exc', 'tb', 'hndl', 'cls'] def __init__(self, exc, handler): self.exc = exc self.hndl = handler self.cls = type(exc) self.tb = None def activate(self): exc = self.exc if exc is not None: self.exc = None self.tb = traceback.format_exception(exc.__class__, exc, exc.__traceback__) def clear(self): self.exc = None self.tb = None def __del__(self): if self.tb: self.hndl(self.cls, self.tb)
mikhtonyuk/rxpython
concurrent/futures/cooperative/ensure_exception_handled.py
Python
mit
3,261
module GitNetworkitis class Getter include HTTParty include JSONHelper base_uri 'https://api.github.com' attr_accessor :url, :local_options, :query_options LOCAL_KEYS = [:batch, :since] def initialize(url, options={}) @url = url scrub_local_options options @query_options = options end def get local_options[:batch] ? batched_get : single_get end private def scrub_local_options(options={}) @local_options = LOCAL_KEYS.inject({}) {|opts, key| opts[key] = options.delete(key); opts } @local_options[:batch] = true unless @local_options[:since].nil? end def single_get(use_query_options=true) ret = use_query_options ? Getter.get(url, query: query_options) : Getter.get(url) if ret.response.code == "200" return ret else raise "Unable to find Github Repository" end end def batched_get resps = [] links = {next: url} first_batch = true while links[:next] do self.url = links[:next] resp = single_get first_batch resps << resp first_batch = false links = build_links_from_headers resp.headers['link'] end BatchResponse.new resps end # see the json files in spec/vcr_cassettes for examples of what the link headers look like def build_links_from_headers(headers) return {} if headers.nil? links = headers.split(',') links.inject({}) do |rel, link| l = link.strip.split(';') next_link = l.first[1...-1] # [1...-1] because the actual link is enclosed within '<' '>' tags rel_command = l.last.strip.match(/rel=\"(.*)\"/).captures.first.to_sym # e.g. "rel=\"next\"" #=> :next rel.tap {|r| r[rel_command] = next_link } end end end end
jcoutu/gitnetworkitis
lib/gitnetworkitis/getter.rb
Ruby
mit
1,826
<!DOCTYPE html><html><head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=Edge"> <meta name="description"> <meta name="keywords" content="static content generator,static site generator,static site,HTML,web development,.NET,C#,Razor,Markdown,YAML"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="shortcut icon" href="/OpenTl.Schema/assets/img/favicon.ico" type="image/x-icon"> <link rel="icon" href="/OpenTl.Schema/assets/img/favicon.ico" type="image/x-icon"> <title>OpenTl.Schema - API - IChannelDifference Interface</title> <link href="/OpenTl.Schema/assets/css/mermaid.css" rel="stylesheet"> <link href="/OpenTl.Schema/assets/css/highlight.css" rel="stylesheet"> <link href="/OpenTl.Schema/assets/css/bootstrap/bootstrap.css" rel="stylesheet"> <link href="/OpenTl.Schema/assets/css/adminlte/AdminLTE.css" rel="stylesheet"> <link href="/OpenTl.Schema/assets/css/theme/theme.css" rel="stylesheet"> <link href="//fonts.googleapis.com/css?family=Roboto+Mono:400,700|Roboto:400,400i,700,700i" rel="stylesheet"> <link href="/OpenTl.Schema/assets/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <link href="/OpenTl.Schema/assets/css/override.css" rel="stylesheet"> <script src="/OpenTl.Schema/assets/js/jquery-2.2.3.min.js"></script> <script src="/OpenTl.Schema/assets/js/bootstrap.min.js"></script> <script src="/OpenTl.Schema/assets/js/app.min.js"></script> <script src="/OpenTl.Schema/assets/js/highlight.pack.js"></script> <script src="/OpenTl.Schema/assets/js/jquery.slimscroll.min.js"></script> <script src="/OpenTl.Schema/assets/js/jquery.sticky-kit.min.js"></script> <script src="/OpenTl.Schema/assets/js/mermaid.min.js"></script> <!--[if lt IE 9]> <script src="/OpenTl.Schema/assets/js/html5shiv.min.js"></script> <script src="/OpenTl.Schema/assets/js/respond.min.js"></script> <![endif]--> </head> <body class="hold-transition wyam layout-boxed "> <div class="top-banner"></div> <div class="wrapper with-container"> <!-- Header --> <header class="main-header"> <a href="/OpenTl.Schema/" class="logo"> <span>OpenTl.Schema</span> </a> <nav class="navbar navbar-static-top" role="navigation"> <!-- Sidebar toggle button--> <a href="#" class="sidebar-toggle visible-xs-block" data-toggle="offcanvas" role="button"> <span class="sr-only">Toggle side menu</span> <i class="fa fa-chevron-circle-right"></i> </a> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse"> <span class="sr-only">Toggle side menu</span> <i class="fa fa-chevron-circle-down"></i> </button> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse pull-left" id="navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="/OpenTl.Schema/about.html">About This Project</a></li> <li class="active"><a href="/OpenTl.Schema/api">API</a></li> </ul> </div> <!-- /.navbar-collapse --> <!-- Navbar Right Menu --> </nav> </header> <!-- Left side column. contains the logo and sidebar --> <aside class="main-sidebar "> <section class="infobar" data-spy="affix" data-offset-top="60" data-offset-bottom="200"> <div id="infobar-headings"><h6>On This Page</h6><p><a href="#Syntax">Syntax</a></p> <p><a href="#ExtensionMethods">Extension Methods</a></p> <hr class="infobar-hidden"> </div> </section> <section class="sidebar"> <script src="/OpenTl.Schema/assets/js/lunr.min.js"></script> <script src="/OpenTl.Schema/assets/js/searchIndex.js"></script> <div class="sidebar-form"> <div class="input-group"> <input type="text" name="search" id="search" class="form-control" placeholder="Search Types..."> <span class="input-group-btn"> <button class="btn btn-flat"><i class="fa fa-search"></i></button> </span> </div> </div> <div id="search-results"> </div> <script> function runSearch(query){ $("#search-results").empty(); if( query.length < 2 ){ return; } var results = searchModule.search("*" + query + "*"); var listHtml = "<ul class='sidebar-menu'>"; listHtml += "<li class='header'>Type Results</li>"; if(results.length == 0 ){ listHtml += "<li>No results found</li>"; } else { for(var i = 0; i < results.length; ++i){ var res = results[i]; listHtml += "<li><a href='" + res.url + "'>" + htmlEscape(res.title) + "</a></li>"; } } listHtml += "</ul>"; $("#search-results").append(listHtml); } $(document).ready(function(){ $("#search").on('input propertychange paste', function() { runSearch($("#search").val()); }); }); function htmlEscape(html) { return document.createElement('div') .appendChild(document.createTextNode(html)) .parentNode .innerHTML; } </script> <hr> <ul class="sidebar-menu"> <li class="header">Namespace</li> <li><a href="/OpenTl.Schema/api/OpenTl.Schema.Updates">OpenTl<wbr>.Schema<wbr>.Updates</a></li> <li role="separator" class="divider"></li> <li class="header">Class Types</li> <li><a href="/OpenTl.Schema/api/OpenTl.Schema.Updates/RequestGetChannelDifference">Request<wbr>Get<wbr>Channel<wbr>Difference</a></li> <li><a href="/OpenTl.Schema/api/OpenTl.Schema.Updates/RequestGetDifference">RequestGetDifference</a></li> <li><a href="/OpenTl.Schema/api/OpenTl.Schema.Updates/RequestGetState">RequestGetState</a></li> <li><a href="/OpenTl.Schema/api/OpenTl.Schema.Updates/TChannelDifference">TChannelDifference</a></li> <li><a href="/OpenTl.Schema/api/OpenTl.Schema.Updates/TChannelDifferenceEmpty">T<wbr>Channel<wbr>Difference<wbr>Empty</a></li> <li><a href="/OpenTl.Schema/api/OpenTl.Schema.Updates/TChannelDifferenceTooLong">T<wbr>Channel<wbr>Difference<wbr>Too<wbr>Long</a></li> <li><a href="/OpenTl.Schema/api/OpenTl.Schema.Updates/TDifference">TDifference</a></li> <li><a href="/OpenTl.Schema/api/OpenTl.Schema.Updates/TDifferenceEmpty">TDifferenceEmpty</a></li> <li><a href="/OpenTl.Schema/api/OpenTl.Schema.Updates/TDifferenceSlice">TDifferenceSlice</a></li> <li><a href="/OpenTl.Schema/api/OpenTl.Schema.Updates/TDifferenceTooLong">TDifferenceTooLong</a></li> <li><a href="/OpenTl.Schema/api/OpenTl.Schema.Updates/TState">TState</a></li> <li class="header">Interface Types</li> <li class="selected"><a href="/OpenTl.Schema/api/OpenTl.Schema.Updates/IChannelDifference">IChannelDifference</a></li> <li><a href="/OpenTl.Schema/api/OpenTl.Schema.Updates/IChannelDifferenceCommon">I<wbr>Channel<wbr>Difference<wbr>Common</a></li> <li><a href="/OpenTl.Schema/api/OpenTl.Schema.Updates/IDifference">IDifference</a></li> <li><a href="/OpenTl.Schema/api/OpenTl.Schema.Updates/IDifferenceCommon">IDifferenceCommon</a></li> <li><a href="/OpenTl.Schema/api/OpenTl.Schema.Updates/IState">IState</a></li> </ul> </section> </aside> <!-- Content Wrapper. Contains page content --> <div class="content-wrapper"> <section class="content-header"> <h1>IChannelDifference <small>Interface</small></h1> </section> <section class="content"> <div class="panel panel-default"> <div class="panel-body"> <div class="row"> <div class="col-md-6"> <dl class="dl-horizontal"> <dt>Namespace</dt> <dd><a href="/OpenTl.Schema/api/OpenTl.Schema.Updates">OpenTl<wbr>.Schema<wbr>.Updates</a></dd> <dt>Interfaces</dt> <dd> <ul class="list-unstyled"> <li><a href="/OpenTl.Schema/api/OpenTl.Schema/IObject">IObject</a></li> </ul> </dd> <dt>Implementing Types</dt> <dd> <ul class="list-unstyled"> <li><a href="/OpenTl.Schema/api/OpenTl.Schema.Updates/TChannelDifference">TChannelDifference</a></li> <li><a href="/OpenTl.Schema/api/OpenTl.Schema.Updates/TChannelDifferenceEmpty">T<wbr>Channel<wbr>Difference<wbr>Empty</a></li> <li><a href="/OpenTl.Schema/api/OpenTl.Schema.Updates/TChannelDifferenceTooLong">T<wbr>Channel<wbr>Difference<wbr>Too<wbr>Long</a></li> </ul> </dd> </dl> </div> <div class="col-md-6"> <div class="mermaid"> graph TD Interface0["IObject"]-.-&gt;Type click Interface0 "/OpenTl.Schema/api/OpenTl.Schema/IObject" Type["IChannelDifference"] class Type type-node Type-.-&gt;Implementing0["TChannelDifference"] click Implementing0 "/OpenTl.Schema/api/OpenTl.Schema.Updates/TChannelDifference" Type-.-&gt;Implementing1["TChannelDifferenceEmpty"] click Implementing1 "/OpenTl.Schema/api/OpenTl.Schema.Updates/TChannelDifferenceEmpty" Type-.-&gt;Implementing2["TChannelDifferenceTooLong"] click Implementing2 "/OpenTl.Schema/api/OpenTl.Schema.Updates/TChannelDifferenceTooLong" </div> </div> </div> </div> </div> <h1 id="Syntax">Syntax</h1> <pre><code>public interface IChannelDifference : IObject</code></pre> <h1 id="ExtensionMethods">Extension Methods</h1> <div class="box"> <div class="box-body no-padding table-responsive"> <table class="table table-striped table-hover three-cols"> <thead> <tr> <th>Name</th> <th>Value</th> <th>Summary</th> </tr> </thead> <tbody><tr> <td><a href="/OpenTl.Schema/api/OpenTl.Schema/Utils/A1A958DE.html">As<wbr>&lt;T&gt;<wbr><wbr>()<wbr></a></td> <td>T</td> <td> <div></div> <div><small><em>From <a href="/OpenTl.Schema/api/OpenTl.Schema/Utils">Utils</a></em></small></div> </td> </tr> <tr> <td><a href="/OpenTl.Schema/api/OpenTl.Schema/Utils/4941F7D3.html">Is<wbr>&lt;T&gt;<wbr><wbr>()<wbr></a></td> <td>T</td> <td> <div></div> <div><small><em>From <a href="/OpenTl.Schema/api/OpenTl.Schema/Utils">Utils</a></em></small></div> </td> </tr> <tr> <td><a href="/OpenTl.Schema/api/OpenTl.Schema/Utils/CF7043C9.html">IsEmpty<wbr>()<wbr></a></td> <td>bool</td> <td> <div></div> <div><small><em>From <a href="/OpenTl.Schema/api/OpenTl.Schema/Utils">Utils</a></em></small></div> </td> </tr> </tbody></table> </div> </div> </section> </div> <!-- Footer --> <footer class="main-footer"> </footer> </div> <div class="wrapper bottom-wrapper"> <footer class="bottom-footer"> Generated by <a href="https://wyam.io">Wyam</a> </footer> </div> <a href="javascript:" id="return-to-top"><i class="fa fa-chevron-up"></i></a> <script> // Close the sidebar if we select an anchor link $(".main-sidebar a[href^='#']:not('.expand')").click(function(){ $(document.body).removeClass('sidebar-open'); }); $(document).load(function() { mermaid.initialize( { flowchart: { htmlLabels: false, useMaxWidth:false } }); mermaid.init(undefined, ".mermaid") $('svg').addClass('img-responsive'); $('pre code').each(function(i, block) { hljs.highlightBlock(block); }); }); hljs.initHighlightingOnLoad(); // Back to top $(window).scroll(function() { if ($(this).scrollTop() >= 200) { // If page is scrolled more than 50px $('#return-to-top').fadeIn(1000); // Fade in the arrow } else { $('#return-to-top').fadeOut(1000); // Else fade out the arrow } }); $('#return-to-top').click(function() { // When arrow is clicked $('body,html').animate({ scrollTop : 0 // Scroll to top of body }, 500); }); </script> </body></html>
OpenTl/OpenTl.Schema
docs/api/OpenTl.Schema.Updates/IChannelDifference/index.html
HTML
mit
14,007
var fs = require('fs'), cons = require('consolidate'), dust = require('dustjs-linkedin'); var pages = [ 'index', 'contact', 'faq', 'registration', 'sponsors', 'travel', 'visit', 'volunteers' ]; pages.forEach(function(page) { cons.dust('views/'+page+'.dust', { views: __dirname+'/views'}, function(err, html) { if(err) return console.log('error: ', err); fs.writeFile(__dirname+'/dist/'+page+'.html', html, function(err) { if(err) return console.log('error saving file: ', page, err); console.log('create page: ', page); }); }); });
selfcontained/mini-cassia-turkey-trot
generate.js
JavaScript
mit
563
__package__ = 'archivebox.core'
pirate/bookmark-archiver
archivebox/core/__init__.py
Python
mit
32
package com.team2502.robot2017.command.autonomous; import edu.wpi.first.wpilibj.command.CommandGroup; public class ShinyFollow extends CommandGroup { /** * Does a follow */ public ShinyFollow() { addSequential(new AutoVisionCommand(200, 0.3)); } }
Team-2502/UpdatedRobotCode2017
src/com/team2502/robot2017/command/autonomous/ShinyFollow.java
Java
mit
267
package br.com.caelum.rest.server; import javax.servlet.http.HttpServletRequest; public class SimpleAction implements Action { public String getUri() { return uri; } public String getRel() { return rel; } private final String uri; private final String rel; public SimpleAction(String rel, String uri) { this.rel = rel; this.uri = uri; } public SimpleAction(String rel, HttpServletRequest request, String uri) { this.rel = rel; this.uri = "http://restful-server.appspot.com" + uri; // this.uri = "http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + uri; } }
caelum/rest-client
rest-server-gae/src/br/com/caelum/rest/server/SimpleAction.java
Java
mit
638
body { font-family: 'Rancho', cursive; font-weight: bold; margin: auto; padding: 5%; background-color: #F49D37; } .score, .game { color: #0A1128; font-size: 28px; } #board { width: 450px; height: 450px; } #board .square { width: 33.333333333%; height: 33.333333333%; background-color: #496DDB; float: left; text-align: center; line-height: 155px; } .square { font-size: 170px; color: #2E4052; border: 2px dashed #F49D37; } .topRow { border-top: none; } .right { border-right: none; } .botRow { border-bottom: none; } .left { border-left: none; } .topRow.right { border-radius: 0 10% 0 0; } .topRow.left { border-radius: 10% 0 0 0; } .botRow.right { border-radius: 0 0 10% 0; } .botRow.left { border-radius: 0 0 0 10%; } #data-bottom, #data-top { width: 450px; } .btnText { color: #0A1128; font-size: 50px; }
delamoe/fcc-tic-tac-toe
ttt.css
CSS
mit
911
<!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>Couch411 | Login</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css"/> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js"></script> <link rel="stylesheet" type="text/css" href="/semantic-ui/dist/semantic.min.css"> <script src="semantic-ui/dist/semantic.min.js"></script> <link href="./ng-cropper/dist/ngCropper.all.css" rel="stylesheet"> <script src="./ng-cropper/dist/ngCropper.all.js"></script> <script src="./js/picture.js"></script> <!--<script src="ng-flow-standalone.js"></script> <script src="ng-img-crop.js"></script> <link rel="stylesheet" type="text/css" href="ng-img-crop.css"/>--> </head> <body ng-app="picture" ng-controller="pictureController" ng-init="printSessionStorage()"> <h4 class = "text-center"> My Profile </h4> <button class="ui button">Follow</button> <script type="text/javascript"> $(window).load(function(){ $('#myModal').modal('show'); }); var closemodal = function() { $('#myModal').modal('hide'); }; </script> <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <form id = "uploadForm" action="/api/uploadAttempt" method="post" enctype="multipart/form-data"> <div class="modal-header"> <!--<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>--> <h4 class="modal-title" id="myModalLabel">Upload Profile Picture</h4> </div> <div class="modal-body"> <input type="file" onchange="angular.element(this).scope().onFile(this.files[0])" name="userPhoto" accept="image/*"> <button class="btn btn-default" ng-click="preview()">Show preview</button> <button class="btn btn-default" ng-click="scale(200)">Scale to 200px width</button> <label>Disabled <input type="checkbox" ng-model="options.disabled"></label> <br /> <div ng-if="dataUrl" class="img-container"> <img ng-if="dataUrl" ng-src="{{dataUrl}}" width="300" ng-cropper ng-cropper-show="showEvent" ng-cropper-hide="hideEvent" ng-cropper-options="options"> </div> <div class="preview-container"> <img ng-if="preview.dataUrl" ng-src="{{preview.dataUrl}}"> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">No Thanks</button> <input type="hidden" value="{{session.sessionID}}" name="sessionID" > <input type="hidden" value="{{cropDim}}" name="cropDim" > <input ng-click="finalCropCheck();" onclick="closemodal();" type="submit" value="Upload Picture" name="submit" class="btn btn-primary"> </div> </form> </div> </div> </div> <button class="btn btn-default" ng-click="publishTry()">Make Post</button> <button class = "btn btn-primary" ng-click="getMyProfile()"> Get My Profile </button> <span>{{myData.changed}}</span> <img width="100" height="100" ng-src="{{myData.changed.users.picSRC}}"></img> </body>
couchbaselabs/touchbase
TouchbaseModular/public/deprecated/pictureUpload.html
HTML
mit
3,981
package com.ms.meizinewsapplication.features.meizi.model; import android.content.Context; import com.ms.meizinewsapplication.features.base.pojo.ImgItem; import com.ms.retrofitlibrary.web.MyOkHttpClient; import org.loader.model.OnModelListener; import java.util.List; import rx.Observable; import rx.Subscription; /** * Created by 啟成 on 2016/3/15. */ public class DbGroupBreastModel extends DbGroupModel { private String pager_offset; public Subscription loadWeb(Context context, OnModelListener<List<ImgItem>> listener, String pager_offset) { this.pager_offset = pager_offset; return loadWeb(context, listener); } @Override protected Subscription reSubscription(Context context, OnModelListener<List<ImgItem>> listener) { Observable<String> dbGroupBreast = getDbGroup().RxDbGroupBreast( MyOkHttpClient.getCacheControl(context), pager_offset ); return rxDbGroup(dbGroupBreast, listener); } }
qq137712630/MeiZiNews
app/src/main/java/com/ms/meizinewsapplication/features/meizi/model/DbGroupBreastModel.java
Java
mit
1,004
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("12_RectangleProperties")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("12_RectangleProperties")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("efacbe98-13fb-4c4d-b368-04e2f314a249")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
nellypeneva/SoftUniProjects
01_ProgrFundamentalsMay/11_Data-Types-Exercises/12_RectangleProperties/Properties/AssemblyInfo.cs
C#
mit
1,420
import logging.handlers import os _pabotlog = logging.getLogger('PABot') _pabotlog.setLevel(logging.DEBUG) _logPath = os.path.abspath("./logging/pabot.log") _formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(name)s - %(message)s') _consoleStreamHandler = logging.StreamHandler() _consoleStreamHandler.setLevel(logging.DEBUG) _consoleStreamHandler.setFormatter(_formatter) _symLogRotFileHandler = logging.handlers.RotatingFileHandler(_logPath, maxBytes=2000000, backupCount=5) _symLogRotFileHandler.setLevel(logging.DEBUG) _symLogRotFileHandler.setFormatter(_formatter) _pabotlog.addHandler(_consoleStreamHandler) _pabotlog.addHandler(_symLogRotFileHandler) def LogPABotMessage(message): _pabotlog.info(message) def LogPABotError(message): _pabotlog.error(message)
KevinJMcGrath/Symphony-Ares
modules/plugins/PABot/logging.py
Python
mit
796
{# ------------------------------------------------------- #} {# INDIVIDUAL VIEW FOR EACH storycontributor #} {# This page can use any data from http:localhost:2000/cms/#/form/storycontributor/ #} {# Webhook uses the SWIG.js (like Djagno/Twig) templating system. Their documentation is here: #} {# http://paularmstrong.github.io/swig/docs/tags/ #} {# Learn about calling data into Webhook pages here: #} {# http://www.webhook.com/docs/template-rules-and-filters/ #} {# ------------------------------------------------------- #} {# Confused what extends and blocks do? Watch a primer: #} {# http://www.webhook.com/docs/template-inheritance-blocks/ #} {% extends "templates/partials/base.html" %} {# This sets our page <title>. It will append this storycontributor's name to the site title defined in base.html #} {% block title %}{% parent %} - {{ item.name }}{% endblock %} {% block content %} <p><a href="{{ url('storycontributor') }}">View a list of all storycontributor</a></p> <h1>{{ item.name }}</h1> <ul> <li> <strong>Name: </strong> {{ item.name }} </li> <li> <strong>Create Date: </strong> {# Format the date. You can use PHP's date function to format as needed. http://php.net/manual/en/function.date.php #} {{ item.create_date|date('F d Y') }} </li> <li> <strong>Last Updated: </strong> {# Format the date. You can use PHP's date function to format as needed. http://php.net/manual/en/function.date.php #} {{ item.last_updated|date('F d Y') }} </li> <li> <strong>Publish Date: </strong> {# Format the date. You can use PHP's date function to format as needed. http://php.net/manual/en/function.date.php #} {{ item.publish_date|date('F d Y') }} </li> <li> <strong>First Name: </strong> {{ item.first_name }} </li> <li> <strong>Last Name: </strong> {{ item.last_name }} </li> <li> <strong>Title: </strong> {{ item.title }} </li> <li> <strong>Company: </strong> {{ item.company }} </li> <li> <strong>Bio - Short: </strong> {{ item.bio__short }} </li> <li> <strong>Bio - Full: </strong> {{ item.bio__full|safe }} </li> <li> <strong>Avatar: </strong> {# You can pull out a lot more information from the image property. Info here: #} {# http://www.webhook.com/docs/widget-template-reference/#image #} <img src="{{ item.avatar|imageSize(200) }}" /> </li> <li> <strong>Website: </strong> {{ item.website }} </li> <li> <strong>Twitter: </strong> {{ item.twitter }} </li> <li> <strong>LinkedIn: </strong> {{ item.linkedin }} </li> <li> <strong>Preview URL: </strong> {{ item.preview_url }} </li> <li> <strong>Slug: </strong> {{ item.slug }} </li> <li> <strong>Story (Contributor - Primary): </strong> {# Relations require some special code. More info about relations here: #} {# http://www.webhook.com/docs/template-rules-and-filters/#getitem #} {% for relation in item.story_contributor__primary %} {# You can ouput more than just the name. Feel free to output more fields from the CMS. #} <a href="{{ url(relation) }}">{{ relation.name }}</a>{% if not loop.last %},{% endif %} {% endfor %} </li> <li> <strong>Story (Contributor - Additional): </strong> {# Relations require some special code. More info about relations here: #} {# http://www.webhook.com/docs/template-rules-and-filters/#getitem #} {% for relation in item.story_contributor__additional %} {# You can ouput more than just the name. Feel free to output more fields from the CMS. #} <a href="{{ url(relation) }}">{{ relation.name }}</a>{% if not loop.last %},{% endif %} {% endfor %} </li> </ul> {% endblock %}
ericwebster/project-crayfish
templates/storycontributor/individual.html
HTML
mit
4,116
// // BBBClockViewController.h // BBBLayer // // Created by LinBin on 16/7/23. // Copyright © 2016年 LinBin. All rights reserved. // #import <UIKit/UIKit.h> @interface BBBClockViewController : UIViewController @end
0bin/Project-collection
BBBLayer/BBBLayer/BBBClockViewController.h
C
mit
224
<?php namespace Phpmvc\Comment; /** * To attach comments-flow to a page or some content. * */ class CommentController implements \Anax\DI\IInjectionAware { use \Anax\DI\TInjectable; /** * View all comments. * * @return void */ public function viewAction($page) { $comments = new \Phpmvc\Comment\CommentsInSession(); $comments->setDI($this->di); $all = $comments->findAll($page); $this->views->add('comment/comments', [ 'comments' => $all, ]); } /** * Add a comment. * * @return void */ public function addAction() { $isPosted = $this->request->getPost('doCreate'); if (!$isPosted) { $this->response->redirect($this->request->getPost('redirect')); } $comment = [ 'page' => $this->request->getPost('page'), 'content' => $this->request->getPost('content'), 'name' => $this->request->getPost('name'), 'web' => $this->request->getPost('web'), 'mail' => $this->request->getPost('mail'), 'timestamp' => time(), 'ip' => $this->request->getServer('REMOTE_ADDR'), ]; $comments = new \Phpmvc\Comment\CommentsInSession(); $comments->setDI($this->di); $comments->add($comment); $this->response->redirect($this->request->getPost('redirect')); } /** * Remove all comments. * * @return void */ public function removeAllAction() { $isPosted = $this->request->getPost('doRemoveAll'); if (!$isPosted) { $this->response->redirect($this->request->getPost('redirect')); } $comments = new \Phpmvc\Comment\CommentsInSession(); $comments->setDI($this->di); $comments->deleteAll(); $this->response->redirect($this->request->getPost('redirect')); } public function removeAction($id) { // $isPosted = $this->request->getPost('doRemove'); //doRemove måste lägga till i formulär i tpl. // if (!$isPosted) { // $this->response->redirect($this->request->getPost('redirect')); // } $comments = new \Phpmvc\Comment\CommentsInSession(); $comments->setDI($this->di); $comments->delete($id); $this->response->redirect($this->request->getPost('redirect')); } public function editFormAction($id) { $comments = new \Phpmvc\Comment\CommentsInSession(); $comments->setDI($this->di); $all = $comments->findAll(); $i = 0; foreach($all as $comment){ if($comment['id'] == $id){ break; } $i++; } $this->views->add('comment/editComment', [ 'comment' => $all[$i], ]); } public function editAction($id) { $isPosted = $this->request->getPost('doEdit'); if (!$isPosted) { $this->response->redirect($this->request->getPost('redirect')); } $comment = [ 'page' => $this->request->getPost('page'), 'content' => $this->request->getPost('content'), 'name' => $this->request->getPost('name'), 'web' => $this->request->getPost('web'), 'mail' => $this->request->getPost('mail'), 'timestamp' => $this->request->getPost('timestamp'), 'ip' => $this->request->getServer('REMOTE_ADDR'), 'id' => $id, 'edited' => time(), ]; $comments = new \Phpmvc\Comment\CommentsInSession(); $comments->setDI($this->di); $comments->edit($comment, $id); $this->response->redirect($this->request->getPost('redirect')); } }
frjf14/Projekt
vendor/phpmvc/comment/src/Comment/CommentController.php
PHP
mit
3,878
#!/bin/bash # Exit immediately if any commands return non-zero set -e # Output the commands we run set -x # This is a modified version of the Cloud Foundry Blue/Green deployment guide: # https://docs.pivotal.io/pivotalcf/devguide/deploy-apps/blue-green.html test $URL # Update the blue app cf unmap-route citizenship-appointment-blue $URL cf push citizenship-appointment-blue -b https://github.com/AusDTO/java-buildpack.git --no-hostname --no-manifest --no-route -p build/libs/citizenship-appointments-0.0.1.jar -i 1 -m 512M cf map-route citizenship-appointment-blue $URL # Update the green app cf unmap-route citizenship-appointment-green $URL cf push citizenship-appointment-green -b https://github.com/AusDTO/java-buildpack.git --no-hostname --no-manifest --no-route -p build/libs/citizenship-appointments-0.0.1.jar -i 1 -m 512M cf map-route citizenship-appointment-green $URL
AusDTO/citizenship-appointment-server
bin/cideploy.sh
Shell
mit
886
import ast import heisenberg.library.heisenberg_dynamics_context import heisenberg.library.orbit_plot import heisenberg.option_parser import heisenberg.plot import heisenberg.util import matplotlib import numpy as np import sys # https://github.com/matplotlib/matplotlib/issues/5907 says this should fix "Exceeded cell block limit" problems matplotlib.rcParams['agg.path.chunksize'] = 10000 dynamics_context = heisenberg.library.heisenberg_dynamics_context.Numeric() op = heisenberg.option_parser.OptionParser(module=heisenberg.plot) # Add the subprogram-specific options here. op.add_option( '--initial-preimage', dest='initial_preimage', type='string', help='Specifies the preimage of the initial conditions with respect to the embedding map specified by the --embedding-dimension and --embedding-solution-sheet-index option values. Should have the form [x_1,...,x_n], where n is the embedding dimension and x_i is a floating point literal for each i.' ) op.add_option( '--initial', dest='initial', type='string', help='Specifies the initial conditions [x,y,z,p_x,p_y,p_z], where each of x,y,z,p_x,p_y,p_z are floating point literals.' ) op.add_option( '--optimization-iterations', dest='optimization_iterations', default=1000, type='int', help='Specifies the number of iterations to run the optimization for (if applicable). Default is 1000.' ) op.add_option( '--optimize-initial', dest='optimize_initial', action='store_true', default=False, help='Indicates that the specified initial condition (via whichever of the --initial... options) should be used as the starting point for an optimization to attempt to close the orbit. Default value is False.' ) op.add_option( '--output-dir', dest='output_dir', default='.', help='Specifies the directory to write plot images and data files to. Default is current directory.' ) op.add_option( '--disable-plot-initial', dest='disable_plot_initial', action='store_true', default=False, help='Disables plotting the initial curve; only has effect if --optimize-initial is specified.' ) options,args = op.parse_argv_and_validate() if options is None: sys.exit(-1) num_initial_conditions_specified = sum([ options.initial_preimage is not None, options.initial is not None, ]) if num_initial_conditions_specified != 1: print('Some initial condition option must be specified; --initial-preimage, --initial. However, {0} of those were specified.'.format(num_initial_conditions_specified)) op.print_help() sys.exit(-1) # Validate subprogram-specific options here. # Attempt to parse initial conditions. Upon success, the attribute options.qp_0 should exist. if options.initial_preimage is not None: try: options.initial_preimage = np.array(ast.literal_eval(options.initial_preimage)) expected_shape = (options.embedding_dimension,) if options.initial_preimage.shape != expected_shape: raise ValueError('--initial-preimage value had the wrong number of components (got {0} but expected {1}).'.format(options.initial_preimage.shape, expected_shape)) options.qp_0 = dynamics_context.embedding(N=options.embedding_dimension, sheet_index=options.embedding_solution_sheet_index)(options.initial_preimage) except Exception as e: print('error parsing --initial-preimage value; error was {0}'.format(e)) op.print_help() sys.exit(-1) elif options.initial is not None: try: options.initial = heisenberg.util.csv_as_ndarray(heisenberg.util.pop_brackets_off_of(options.initial), float) expected_shape = (6,) if options.initial.shape != expected_shape: raise ValueError('--initial value had the wrong number of components (got {0} but expected {1}).'.format(options.initial.shape, expected_shape)) options.qp_0 = options.initial.reshape(2,3) except ValueError as e: print('error parsing --initial value: {0}'.format(str(e))) op.print_help() sys.exit(-1) else: assert False, 'this should never happen because of the check with num_initial_conditions_specified' rng = np.random.RandomState(options.seed) heisenberg.plot.plot(dynamics_context, options, rng=rng)
vdods/heisenberg
heisenberg/plot/__main__.py
Python
mit
4,283
<?php namespace Ooxif\LaravelSpecSchema\SqlServer; trait BlueprintTrait { }
ooxif/laravel-spec-schema
src/Ooxif/LaravelSpecSchema/SqlServer/BlueprintTrait.php
PHP
mit
77
def load_keys(filepath): """ Loads the Twitter API keys into a dict. :param filepath: file path to config file with Twitter API keys. :return: keys_dict :raise: IOError """ try: keys_file = open(filepath, 'rb') keys = {} for line in keys_file: key, value = line.split('=') keys[key.strip()] = value.strip() except IOError: message = ('File {} cannot be opened.' ' Check that it exists and is binary.') print message.format(filepath) raise except: print "Error opening or unpickling file." raise return keys
nhatbui/LebronCoin
lebroncoin/key_loader.py
Python
mit
654
// Copyright (c) 2009 Satoshi Nakamoto // Distributed under the MIT/X11 software license, see the accompanying // file license.txt or http://www.opensource.org/licenses/mit-license.php. // // Why base-58 instead of standard base-64 encoding? // - Don't want 0OIl characters that look the same in some fonts and // could be used to create visually identical looking account numbers. // - A string with non-alphanumeric characters is not as easily accepted as an account number. // - E-mail usually won't line-break if there's no punctuation to break at. // - Doubleclicking selects the whole number as one word if it's all alphanumeric. // static const char* pszBase58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; inline string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend) { CAutoBN_CTX pctx; CBigNum bn58 = 58; CBigNum bn0 = 0; // Convert big endian data to little endian // Extra zero at the end make sure bignum will interpret as a positive number vector<unsigned char> vchTmp(pend-pbegin+1, 0); reverse_copy(pbegin, pend, vchTmp.begin()); // Convert little endian data to bignum CBigNum bn; bn.setvch(vchTmp); // Convert bignum to string string str; str.reserve((pend - pbegin) * 138 / 100 + 1); CBigNum dv; CBigNum rem; while (bn > bn0) { if (!BN_div(&dv, &rem, &bn, &bn58, pctx)) throw bignum_error("EncodeBase58 : BN_div failed"); bn = dv; unsigned int c = rem.getulong(); str += pszBase58[c]; } // Leading zeroes encoded as base58 zeros for (const unsigned char* p = pbegin; p < pend && *p == 0; p++) str += pszBase58[0]; // Convert little endian string to big endian reverse(str.begin(), str.end()); return str; } inline string EncodeBase58(const vector<unsigned char>& vch) { return EncodeBase58(&vch[0], &vch[0] + vch.size()); } inline bool DecodeBase58(const char* psz, vector<unsigned char>& vchRet) { CAutoBN_CTX pctx; vchRet.clear(); CBigNum bn58 = 58; CBigNum bn = 0; CBigNum bnChar; while (isspace(*psz)) psz++; // Convert big endian string to bignum for (const char* p = psz; *p; p++) { const char* p1 = strchr(pszBase58, *p); if (p1 == NULL) { while (isspace(*p)) p++; if (*p != '\0') return false; break; } bnChar.setulong(p1 - pszBase58); if (!BN_mul(&bn, &bn, &bn58, pctx)) throw bignum_error("DecodeBase58 : BN_mul failed"); bn += bnChar; } // Get bignum as little endian data vector<unsigned char> vchTmp = bn.getvch(); // Trim off sign byte if present if (vchTmp.size() >= 2 && vchTmp.end()[-1] == 0 && vchTmp.end()[-2] >= 0x80) vchTmp.erase(vchTmp.end()-1); // Restore leading zeros int nLeadingZeros = 0; for (const char* p = psz; *p == pszBase58[0]; p++) nLeadingZeros++; vchRet.assign(nLeadingZeros + vchTmp.size(), 0); // Convert little endian data to big endian reverse_copy(vchTmp.begin(), vchTmp.end(), vchRet.end() - vchTmp.size()); return true; } inline bool DecodeBase58(const string& str, vector<unsigned char>& vchRet) { return DecodeBase58(str.c_str(), vchRet); } inline string EncodeBase58Check(const vector<unsigned char>& vchIn) { // add 4-byte hash check to the end vector<unsigned char> vch(vchIn); uint256 hash = Hash(vch.begin(), vch.end()); vch.insert(vch.end(), (unsigned char*)&hash, (unsigned char*)&hash + 4); return EncodeBase58(vch); } inline bool DecodeBase58Check(const char* psz, vector<unsigned char>& vchRet) { if (!DecodeBase58(psz, vchRet)) return false; if (vchRet.size() < 4) { vchRet.clear(); return false; } uint256 hash = Hash(vchRet.begin(), vchRet.end()-4); if (memcmp(&hash, &vchRet.end()[-4], 4) != 0) { vchRet.clear(); return false; } vchRet.resize(vchRet.size()-4); return true; } inline bool DecodeBase58Check(const string& str, vector<unsigned char>& vchRet) { return DecodeBase58Check(str.c_str(), vchRet); } static const unsigned char ADDRESSVERSION = 0; inline string Hash160ToAddress(uint160 hash160) { // add 1-byte version number to the front vector<unsigned char> vch(1, ADDRESSVERSION); vch.insert(vch.end(), UBEGIN(hash160), UEND(hash160)); return EncodeBase58Check(vch); } inline bool AddressToHash160(const char* psz, uint160& hash160Ret) { vector<unsigned char> vch; if (!DecodeBase58Check(psz, vch)) return false; if (vch.empty()) return false; unsigned char nVersion = vch[0]; if (vch.size() != sizeof(hash160Ret) + 1) return false; memcpy(&hash160Ret, &vch[1], sizeof(hash160Ret)); return (nVersion <= ADDRESSVERSION); } inline bool AddressToHash160(const string& str, uint160& hash160Ret) { return AddressToHash160(str.c_str(), hash160Ret); } inline bool IsValidBitcoinAddress(const char* psz) { uint160 hash160; return AddressToHash160(psz, hash160); } inline bool IsValidBitcoinAddress(const string& str) { return IsValidBitcoinAddress(str.c_str()); } inline string PubKeyToAddress(const vector<unsigned char>& vchPubKey) { return Hash160ToAddress(Hash160(vchPubKey)); }
originalbitcoin/original-bitcoin-client-0.1.0
base58.h
C
mit
5,438
"""Main entry points for scripts.""" from __future__ import print_function, division from argparse import ArgumentParser from collections import OrderedDict from copy import copy from datetime import datetime import glob import json import logging import math import os import scipy.stats import numpy as np from .version import __version__ from .psffuncs import gaussian_moffat_psf from .psf import TabularPSF, GaussianMoffatPSF from .io import read_datacube, write_results, read_results from .fitting import (guess_sky, fit_galaxy_single, fit_galaxy_sky_multi, fit_position_sky, fit_position_sky_sn_multi, RegularizationPenalty) from .utils import yxbounds from .extern import ADR, Hyper_PSF3D_PL __all__ = ["cubefit", "cubefit_subtract", "cubefit_plot"] MODEL_SHAPE = (32, 32) SPAXEL_SIZE = 0.43 MIN_NMAD = 2.5 # Minimum Number of Median Absolute Deviations above # the minimum spaxel value in fit_position LBFGSB_FACTOR = 1e10 REFWAVE = 5000. # reference wavelength in Angstroms for PSF params and ADR POSITION_BOUND = 3. # Bound on fitted positions relative in initial positions def snfpsf(wave, psfparams, header, psftype): """Create a 3-d PSF based on SNFactory-specific parameterization of Gaussian + Moffat PSF parameters and ADR.""" # Get Gaussian+Moffat parameters at each wavelength. relwave = wave / REFWAVE - 1.0 ellipticity = abs(psfparams[0]) * np.ones_like(wave) alpha = np.abs(psfparams[1] + psfparams[2] * relwave + psfparams[3] * relwave**2) # correlated parameters (coefficients determined externally) sigma = 0.545 + 0.215 * alpha # Gaussian parameter beta = 1.685 + 0.345 * alpha # Moffat parameter eta = 1.040 + 0.0 * alpha # gaussian ampl. / moffat ampl. # Atmospheric differential refraction (ADR): Because of ADR, # the center of the PSF will be different at each wavelength, # by an amount that we can determine (pretty well) from the # atmospheric conditions and the pointing and angle of the # instrument. We calculate the offsets here as a function of # observation and wavelength and input these to the model. # Correction to parallactic angle and airmass for 2nd-order effects # such as MLA rotation, mechanical flexures or finite-exposure # corrections. These values have been trained on faint-std star # exposures. # # `predict_adr_params` uses 'AIRMASS', 'PARANG' and 'CHANNEL' keys # in input dictionary. delta, theta = Hyper_PSF3D_PL.predict_adr_params(header) # check for crazy values of pressure and temperature, and assign default # values. pressure = header.get('PRESSURE', 617.) if not 550. < pressure < 650.: pressure = 617. temp = header.get('TEMP', 2.) if not -20. < temp < 20.: temp = 2. adr = ADR(pressure, temp, lref=REFWAVE, delta=delta, theta=theta) adr_refract = adr.refract(0, 0, wave, unit=SPAXEL_SIZE) # adr_refract[0, :] corresponds to x, adr_refract[1, :] => y xctr, yctr = adr_refract if psftype == 'gaussian-moffat': return GaussianMoffatPSF(sigma, alpha, beta, ellipticity, eta, yctr, xctr, MODEL_SHAPE, subpix=3) elif psftype == 'tabular': A = gaussian_moffat_psf(sigma, alpha, beta, ellipticity, eta, yctr, xctr, MODEL_SHAPE, subpix=3) return TabularPSF(A) else: raise ValueError("unknown psf type: " + repr(psftype)) def setup_logging(loglevel, logfname=None): # if loglevel isn't an integer, parse it as "debug", "info", etc: if not isinstance(loglevel, int): loglevel = getattr(logging, loglevel.upper(), None) if not isinstance(loglevel, int): print('Invalid log level: %s' % loglevel) exit(1) # remove logfile if it already exists if logfname is not None and os.path.exists(logfname): os.remove(logfname) logging.basicConfig(filename=logfname, format="%(levelname)s %(message)s", level=loglevel) def cubefit(argv=None): DESCRIPTION = "Fit SN + galaxy model to SNFactory data cubes." parser = ArgumentParser(prog="cubefit", description=DESCRIPTION) parser.add_argument("configfile", help="configuration file name (JSON format)") parser.add_argument("outfile", help="Output file name (FITS format)") parser.add_argument("--dataprefix", default="", help="path prepended to data file names; default is " "empty string") parser.add_argument("--logfile", help="Write log to this file " "(default: print to stdout)", default=None) parser.add_argument("--loglevel", default="info", help="one of: debug, info, warning (default is info)") parser.add_argument("--diagdir", default=None, help="If given, write intermediate diagnostic results " "to this directory") parser.add_argument("--refitgal", default=False, action="store_true", help="Add an iteration where galaxy model is fit " "using all epochs and then data/SN positions are " "refit") parser.add_argument("--mu_wave", default=0.07, type=float, help="Wavelength regularization parameter. " "Default is 0.07.") parser.add_argument("--mu_xy", default=0.001, type=float, help="Spatial regularization parameter. " "Default is 0.001.") parser.add_argument("--psftype", default="gaussian-moffat", help="Type of PSF: 'gaussian-moffat' or 'tabular'. " "Currently, tabular means generate a tabular PSF from " "gaussian-moffat parameters.") args = parser.parse_args(argv) setup_logging(args.loglevel, logfname=args.logfile) # record start time tstart = datetime.now() logging.info("cubefit v%s started at %s", __version__, tstart.strftime("%Y-%m-%d %H:%M:%S")) tsteps = OrderedDict() # finish time of each step. logging.info("parameters: mu_wave={:.3g} mu_xy={:.3g} refitgal={}" .format(args.mu_wave, args.mu_xy, args.refitgal)) logging.info(" psftype={}".format(args.psftype)) logging.info("reading config file") with open(args.configfile) as f: cfg = json.load(f) # basic checks on config contents. assert (len(cfg["filenames"]) == len(cfg["xcenters"]) == len(cfg["ycenters"]) == len(cfg["psf_params"])) # ------------------------------------------------------------------------- # Load data cubes from the list of FITS files. nt = len(cfg["filenames"]) logging.info("reading %d data cubes", nt) cubes = [] for fname in cfg["filenames"]: logging.debug(" reading %s", fname) cubes.append(read_datacube(os.path.join(args.dataprefix, fname))) wave = cubes[0].wave nw = len(wave) # assign some local variables for convenience refs = cfg["refs"] master_ref = cfg["master_ref"] if master_ref not in refs: raise ValueError("master ref choice must be one of the final refs (" + " ".join(refs.astype(str)) + ")") nonmaster_refs = [i for i in refs if i != master_ref] nonrefs = [i for i in range(nt) if i not in refs] # Ensure that all cubes have the same wavelengths. if not all(np.all(cubes[i].wave == wave) for i in range(1, nt)): raise ValueError("all data must have same wavelengths") # ------------------------------------------------------------------------- # PSF for each observation logging.info("setting up PSF for all %d epochs", nt) psfs = [snfpsf(wave, cfg["psf_params"][i], cubes[i].header, args.psftype) for i in range(nt)] # ------------------------------------------------------------------------- # Initialize all model parameters to be fit yctr0 = np.array(cfg["ycenters"]) xctr0 = np.array(cfg["xcenters"]) galaxy = np.zeros((nw, MODEL_SHAPE[0], MODEL_SHAPE[1]), dtype=np.float64) sn = np.zeros((nt, nw), dtype=np.float64) # SN spectrum at each epoch skys = np.zeros((nt, nw), dtype=np.float64) # Sky spectrum at each epoch yctr = yctr0.copy() xctr = xctr0.copy() snctr = (0., 0.) # For writing out to FITS modelwcs = {"CRVAL1": -SPAXEL_SIZE * (MODEL_SHAPE[0] - 1) / 2., "CRPIX1": 1, "CDELT1": SPAXEL_SIZE, "CRVAL2": -SPAXEL_SIZE * (MODEL_SHAPE[1] - 1) / 2., "CRPIX2": 1, "CDELT2": SPAXEL_SIZE, "CRVAL3": cubes[0].header["CRVAL3"], "CRPIX3": cubes[0].header["CRPIX3"], "CDELT3": cubes[0].header["CDELT3"]} # ------------------------------------------------------------------------- # Position bounds # Bounds on data position: shape=(nt, 2) xctrbounds = np.vstack((xctr - POSITION_BOUND, xctr + POSITION_BOUND)).T yctrbounds = np.vstack((yctr - POSITION_BOUND, yctr + POSITION_BOUND)).T snctrbounds = (-POSITION_BOUND, POSITION_BOUND) # For data positions, check that bounds do not extend # past the edge of the model and adjust the minbound and maxbound. # This doesn't apply to SN position. gshape = galaxy.shape[1:3] # model shape for i in range(nt): dshape = cubes[i].data.shape[1:3] (yminabs, ymaxabs), (xminabs, xmaxabs) = yxbounds(gshape, dshape) yctrbounds[i, 0] = max(yctrbounds[i, 0], yminabs) yctrbounds[i, 1] = min(yctrbounds[i, 1], ymaxabs) xctrbounds[i, 0] = max(xctrbounds[i, 0], xminabs) xctrbounds[i, 1] = min(xctrbounds[i, 1], xmaxabs) # ------------------------------------------------------------------------- # Guess sky logging.info("guessing sky for all %d epochs", nt) for i, cube in enumerate(cubes): skys[i, :] = guess_sky(cube, npix=30) # ------------------------------------------------------------------------- # Regularization penalty parameters # Calculate rough average galaxy spectrum from all final refs. spectra = np.zeros((len(refs), len(wave)), dtype=np.float64) for j, i in enumerate(refs): avg_spec = np.average(cubes[i].data, axis=(1, 2)) - skys[i] mean_spec, bins, bn = scipy.stats.binned_statistic(wave, avg_spec, bins=len(wave)/10) spectra[j] = np.interp(wave, bins[:-1] + np.diff(bins)[0]/2., mean_spec) mean_gal_spec = np.average(spectra, axis=0) # Ensure that there won't be any negative or tiny values in mean: mean_floor = 0.1 * np.median(mean_gal_spec) mean_gal_spec[mean_gal_spec < mean_floor] = mean_floor galprior = np.zeros((nw, MODEL_SHAPE[0], MODEL_SHAPE[1]), dtype=np.float64) regpenalty = RegularizationPenalty(galprior, mean_gal_spec, args.mu_xy, args.mu_wave) tsteps["setup"] = datetime.now() # ------------------------------------------------------------------------- # Fit just the galaxy model to just the master ref. data = cubes[master_ref].data - skys[master_ref, :, None, None] weight = cubes[master_ref].weight logging.info("fitting galaxy to master ref [%d]", master_ref) galaxy = fit_galaxy_single(galaxy, data, weight, (yctr[master_ref], xctr[master_ref]), psfs[master_ref], regpenalty, LBFGSB_FACTOR) if args.diagdir: fname = os.path.join(args.diagdir, 'step1.fits') write_results(galaxy, skys, sn, snctr, yctr, xctr, yctr0, xctr0, yctrbounds, xctrbounds, cubes, psfs, modelwcs, fname) tsteps["fit galaxy to master ref"] = datetime.now() # ------------------------------------------------------------------------- # Fit the positions of the other final refs # # Here we only use spaxels where the *model* has significant flux. # We define "significant" as some number of median absolute deviations # (MAD) above the minimum flux in the model. We (temporarily) set the # weight of "insignificant" spaxels to zero during this process, then # restore the original weight after we're done. # # If there are less than 20 "significant" spaxels, we do not attempt to # fit the position, but simply leave it as is. logging.info("fitting position of non-master refs %s", nonmaster_refs) for i in nonmaster_refs: cube = cubes[i] # Evaluate galaxy on this epoch for purpose of masking spaxels. gal = psfs[i].evaluate_galaxy(galaxy, (cube.ny, cube.nx), (yctr[i], xctr[i])) # Set weight of low-valued spaxels to zero. gal2d = gal.sum(axis=0) # Sum of gal over wavelengths mad = np.median(np.abs(gal2d - np.median(gal2d))) mask = gal2d > np.min(gal2d) + MIN_NMAD * mad if mask.sum() < 20: continue weight = cube.weight * mask[None, :, :] fctr, fsky = fit_position_sky(galaxy, cube.data, weight, (yctr[i], xctr[i]), psfs[i], (yctrbounds[i], xctrbounds[i])) yctr[i], xctr[i] = fctr skys[i, :] = fsky tsteps["fit positions of other refs"] = datetime.now() # ------------------------------------------------------------------------- # Redo model fit, this time including all final refs. datas = [cubes[i].data for i in refs] weights = [cubes[i].weight for i in refs] ctrs = [(yctr[i], xctr[i]) for i in refs] psfs_refs = [psfs[i] for i in refs] logging.info("fitting galaxy to all refs %s", refs) galaxy, fskys = fit_galaxy_sky_multi(galaxy, datas, weights, ctrs, psfs_refs, regpenalty, LBFGSB_FACTOR) # put fitted skys back in `skys` for i,j in enumerate(refs): skys[j, :] = fskys[i] if args.diagdir: fname = os.path.join(args.diagdir, 'step2.fits') write_results(galaxy, skys, sn, snctr, yctr, xctr, yctr0, xctr0, yctrbounds, xctrbounds, cubes, psfs, modelwcs, fname) tsteps["fit galaxy to all refs"] = datetime.now() # ------------------------------------------------------------------------- # Fit position of data and SN in non-references # # Now we think we have a good galaxy model. We fix this and fit # the relative position of the remaining epochs (which presumably # all have some SN light). We simultaneously fit the position of # the SN itself. logging.info("fitting position of all %d non-refs and SN position", len(nonrefs)) if len(nonrefs) > 0: datas = [cubes[i].data for i in nonrefs] weights = [cubes[i].weight for i in nonrefs] psfs_nonrefs = [psfs[i] for i in nonrefs] fyctr, fxctr, snctr, fskys, fsne = fit_position_sky_sn_multi( galaxy, datas, weights, yctr[nonrefs], xctr[nonrefs], snctr, psfs_nonrefs, LBFGSB_FACTOR, yctrbounds[nonrefs], xctrbounds[nonrefs], snctrbounds) # put fitted results back in parameter lists. yctr[nonrefs] = fyctr xctr[nonrefs] = fxctr for i,j in enumerate(nonrefs): skys[j, :] = fskys[i] sn[j, :] = fsne[i] tsteps["fit positions of nonrefs & SN"] = datetime.now() # ------------------------------------------------------------------------- # optional step(s) if args.refitgal and len(nonrefs) > 0: if args.diagdir: fname = os.path.join(args.diagdir, 'step3.fits') write_results(galaxy, skys, sn, snctr, yctr, xctr, yctr0, xctr0, yctrbounds, xctrbounds, cubes, psfs, modelwcs, fname) # --------------------------------------------------------------------- # Redo fit of galaxy, using ALL epochs, including ones with SN # light. We hold the SN "fixed" simply by subtracting it from the # data and fitting the remainder. # # This is slightly dangerous: any errors in the original SN # determination, whether due to an incorrect PSF or ADR model # or errors in the galaxy model will result in residuals. The # galaxy model will then try to compensate for these. # # We should look at the galaxy model at the position of the SN # before and after this step to see if there is a bias towards # the galaxy flux increasing. logging.info("fitting galaxy using all %d epochs", nt) datas = [cube.data for cube in cubes] weights = [cube.weight for cube in cubes] ctrs = [(yctr[i], xctr[i]) for i in range(nt)] # subtract SN from non-ref cubes. for i in nonrefs: s = psfs[i].point_source(snctr, datas[i].shape[1:3], ctrs[i]) # do *not* use in-place operation (-=) here! datas[i] = cubes[i].data - sn[i, :, None, None] * s galaxy, fskys = fit_galaxy_sky_multi(galaxy, datas, weights, ctrs, psfs, regpenalty, LBFGSB_FACTOR) for i in range(nt): skys[i, :] = fskys[i] # put fitted skys back in skys if args.diagdir: fname = os.path.join(args.diagdir, 'step4.fits') write_results(galaxy, skys, sn, snctr, yctr, xctr, yctr0, xctr0, yctrbounds, xctrbounds, cubes, psfs, modelwcs, fname) # --------------------------------------------------------------------- # Repeat step before last: fit position of data and SN in # non-references logging.info("re-fitting position of all %d non-refs and SN position", len(nonrefs)) if len(nonrefs) > 0: datas = [cubes[i].data for i in nonrefs] weights = [cubes[i].weight for i in nonrefs] psfs_nonrefs = [psfs[i] for i in nonrefs] fyctr, fxctr, snctr, fskys, fsne = fit_position_sky_sn_multi( galaxy, datas, weights, yctr[nonrefs], xctr[nonrefs], snctr, psfs_nonrefs, LBFGSB_FACTOR, yctrbounds[nonrefs], xctrbounds[nonrefs], snctrbounds) # put fitted results back in parameter lists. yctr[nonrefs] = fyctr xctr[nonrefs] = fxctr for i, j in enumerate(nonrefs): skys[j, :] = fskys[i] sn[j, :] = fsne[i] # ------------------------------------------------------------------------- # Write results logging.info("writing results to %s", args.outfile) write_results(galaxy, skys, sn, snctr, yctr, xctr, yctr0, xctr0, yctrbounds, xctrbounds, cubes, psfs, modelwcs, args.outfile) # time info logging.info("step times:") maxlen = max(len(key) for key in tsteps) fmtstr = " %2dm%02ds - %-" + str(maxlen) + "s" tprev = tstart for key, tstep in tsteps.items(): t = (tstep - tprev).seconds logging.info(fmtstr, t//60, t%60, key) tprev = tstep tfinish = datetime.now() logging.info("finished at %s", tfinish.strftime("%Y-%m-%d %H:%M:%S")) t = (tfinish - tstart).seconds logging.info("took %3dm%2ds", t // 60, t % 60) return 0 def cubefit_subtract(argv=None): DESCRIPTION = \ """Subtract model determined by cubefit from the original data. The "outnames" key in the supplied configuration file is used to determine the output FITS file names. The input FITS header is passed unaltered to the output file, with the following additions: (1) A `HISTORY` entry. (2) `CBFT_SNX` and `CBFT_SNY` records giving the cubefit-determined position of the SN relative to the center of the data array (at the reference wavelength). This script also writes fitted SN spectra to individual FITS files. The "sn_outnames" configuration field determines the output filenames. """ import shutil import fitsio prog_name = "cubefit-subtract" prog_name_ver = "{} v{}".format(prog_name, __version__) parser = ArgumentParser(prog=prog_name, description=DESCRIPTION) parser.add_argument("configfile", help="configuration file name " "(JSON format), same as cubefit input.") parser.add_argument("resultfile", help="Result FITS file from cubefit") parser.add_argument("--dataprefix", default="", help="path prepended to data file names; default is " "empty string") parser.add_argument("--outprefix", default="", help="path prepended to output file names; default is " "empty string") args = parser.parse_args(argv) setup_logging("info") # get input & output filenames with open(args.configfile) as f: cfg = json.load(f) fnames = [os.path.join(args.dataprefix, fname) for fname in cfg["filenames"]] outfnames = [os.path.join(args.outprefix, fname) for fname in cfg["outnames"]] # load results results = read_results(args.resultfile) epochs = results["epochs"] sny, snx = results["snctr"] if not len(epochs) == len(fnames) == len(outfnames): raise RuntimeError("number of epochs in result file not equal to " "number of input and output files in config file") # subtract and write out. for fname, outfname, epoch in zip(fnames, outfnames, epochs): logging.info("writing %s", outfname) shutil.copy(fname, outfname) f = fitsio.FITS(outfname, "rw") data = f[0].read() data -= epoch["galeval"] f[0].write(data) f[0].write_history("galaxy subtracted by " + prog_name_ver) f[0].write_key("CBFT_SNX", snx - epoch['xctr'], comment="SN x offset from center at {:.0f} A [spaxels]" .format(REFWAVE)) f[0].write_key("CBFT_SNY", sny - epoch['yctr'], comment="SN y offset from center at {:.0f} A [spaxels]" .format(REFWAVE)) f.close() # output SN spectra to separate files. sn_outnames = [os.path.join(args.outprefix, fname) for fname in cfg["sn_outnames"]] header = {"CRVAL1": results["header"]["CRVAL3"], "CRPIX1": results["header"]["CRPIX3"], "CDELT1": results["header"]["CDELT3"]} for outfname, epoch in zip(sn_outnames, epochs): logging.info("writing %s", outfname) if os.path.exists(outfname): # avoid warning from clobber=True os.remove(outfname) with fitsio.FITS(outfname, "rw") as f: f.write(epoch["sn"], extname="sn", header=header) f[0].write_history("created by " + prog_name_ver) return 0 def cubefit_plot(argv=None): DESCRIPTION = """Plot results and diagnostics from cubefit""" from .plotting import plot_timeseries, plot_epoch, plot_sn, plot_adr # arguments are the same as cubefit except an output parser = ArgumentParser(prog="cubefit-plot", description=DESCRIPTION) parser.add_argument("configfile", help="configuration filename") parser.add_argument("resultfile", help="Result filename from cubefit") parser.add_argument("outprefix", help="output prefix") parser.add_argument("--dataprefix", default="", help="path prepended to data file names; default is " "empty string") parser.add_argument('-b', '--band', help='timeseries band (U, B, V). ' 'Default is a 1000 A wide band in middle of cube.', default=None, dest='band') parser.add_argument('--idrfiles', nargs='+', default=None, help='Prefix of IDR. If given, the cubefit SN ' 'spectra are plotted against the production values.') parser.add_argument("--diagdir", default=None, help="If given, read intermediate diagnostic " "results from this directory and include in plot(s)") parser.add_argument("--plotepochs", default=False, action="store_true", help="Make diagnostic plots for each epoch") args = parser.parse_args(argv) # Read in data with open(args.configfile) as f: cfg = json.load(f) cubes = [read_datacube(os.path.join(args.dataprefix, fname), scale=False) for fname in cfg["filenames"]] results = OrderedDict() # Diagnostic results at each step if args.diagdir is not None: fnames = sorted(glob.glob(os.path.join(args.diagdir, "step*.fits"))) for fname in fnames: name = os.path.basename(fname).split(".")[0] results[name] = read_results(fname) # Final result (don't fail if not available) if os.path.exists(args.resultfile): results["final"] = read_results(args.resultfile) # plot time series plot_timeseries(cubes, results, band=args.band, fname=(args.outprefix + '_timeseries.png')) # Plot wave slices and sn, galaxy and sky spectra for all epochs. if 'final' in results and args.plotepochs: for i_t in range(len(cubes)): plot_epoch(cubes[i_t], results['final']['epochs'][i_t], fname=(args.outprefix + '_epoch%02d.png' % i_t)) # Plot result spectra against IDR spectra. if 'final' in results and args.idrfiles is not None: plot_sn(cfg['filenames'], results['final']['epochs']['sn'], results['final']['wave'], args.idrfiles, args.outprefix + '_sn.png') # Plot the x-y coordinates of the adr versus wavelength # (Skip this for now; contains no interesting information) #plot_adr(cubes, cubes[0].wave, fname=(args.outprefix + '_adr.png')) return 0
snfactory/cubefit
cubefit/main.py
Python
mit
26,267
--- title: "Aggregates" description: "Reference documentation for Sensu Named Aggregates." product: "Sensu Core" version: "1.8" weight: 4 menu: sensu-core-1.8: parent: reference --- ## Reference documentation - [What is a Sensu named aggregate?](#what-is-a-check-aggregate) - [When should named aggregates be used?](#when-should-check-aggregates-be-used) - [How do named aggregates work?](#how-do-check-aggregates-work) - [Example aggregated check result](#example-aggregated-check-result) - [Aggregate configuration](#aggregate-configuration) - [Example aggregate definition](#example-aggregate-definition) - [Aggregate definition specification](#aggregate-definition-specification) - [Aggregate `check` attributes](#aggregate-check-attributes) ## What is a Sensu named aggregate? {#what-is-a-check-aggregate} Sensu named aggregates are collections of [check results][1], accessible via the [Aggregates API][2]. Check aggregates make it possible to treat the results of multiple disparate check results &ndash; executed across multiple disparate systems &ndash; as a single result. ### When should named aggregates be used? {#when-should-check-aggregates-be-used} Check aggregates are extremely useful in dynamic environments and/or environments that have a reasonable tolerance for failure. Check aggregates should be used when a service can be considered healthy as long as a minimum threshold is satisfied (e.g. are at least 5 healthy web servers? are at least 70% of N processes healthy?). ## How do named aggregates work? {#how-do-check-aggregates-work} Check results are included in an aggregate when a check definition includes the [`aggregate` definition attribute][3]. Check results that provide an `"aggregate": "example_aggregate"` are aggregated under the corresponding name (e.g. `example_aggregate`), effectively capturing multiple check results as a single aggregate. ### Example aggregated check result Aggregated check results are available from the [Aggregates API][2], via the `/aggregates/:name` API endpoint. An aggregate check result provides a set of counters indicating the total number of client members, checks, and check results collected, with a breakdown of how many results were recorded per status (i.e. `ok`, `warning`, `critical`, and `unknown`). {{< code json >}} { "clients": 15, "checks": 2, "results": { "ok": 18, "warning": 0, "critical": 1, "unknown": 0, "total": 19, "stale": 0 } } {{< /code >}} Additional aggregate data is available from the Aggregates API, including Sensu client members of a named aggregate, and the corresponding checks which are included in the aggregate: {{< code shell >}} $ curl -s http://localhost:4567/aggregates/elasticsearch/clients | jq . [ { "name": "i-424242", "checks": [ "elasticsearch_service", "elasticsearch_cluster_health" ] }, { "name": "1-424243", "checks": [ "elasticsearch_service" ] }, ] {{< /code >}} Aggregate data may also be fetched per check that is a member of the named aggregate, along with the corresponding clients that are producing results for said check: {{< code shell >}} $ curl -s http://localhost:4567/aggregates/elasticsearch/checks | jq . [ { "name": "elasticsearch_service", "clients": [ "i-424242", "i-424243" ] }, { "name": "elasticsearch_cluster_health", "clients": [ "i-424242" ] } ] {{< /code >}} ## Aggregate configuration ### Example aggregate definition The following is an example [check definition][6], a JSON configuration file located at `/etc/sensu/conf.d/check_aggregate_example.json`. {{< code shell >}} { "checks": { "example_check_aggregate": { "command": "do_something.rb -o option", "aggregate": "example_aggregate", "interval": 60, "subscribers": [ "my_aggregate" ], "handle": false } } }{{< /code >}} ### Aggregate definition specification _NOTE: aggregates are created via the [`aggregate` Sensu `check` definition attribute][4]. The configuration example(s) provided above, and the "specification" provided here are for clarification and convenience only (i.e. this "specification" is just a subset of the [check definition specification][5], and not a definition of a distinct Sensu primitive)._ #### Aggregate `check` attributes aggregate | -------------|------ description | Create a named aggregate for the check. Check result data will be aggregated and exposed via the [Sensu Aggregates API][2]. required | false type | String example | {{< code shell >}}"aggregate": "elasticsearch"{{< /code >}} aggregates | -------------|------ description | An array of strings defining one or more named aggregates (described above). required | false type | Array example | {{< code shell >}}"aggregates": [ "webservers", "production" ]{{< /code >}} handle | -------------|------ description | If events created by the check should be handled. required | false type | Boolean default | true example | {{< code shell >}}"handle": false{{< /code >}}_NOTE: although there are cases when it may be helpful to aggregate check results **and** handle individual check results, it is typically recommended to set `"handle": false` when aggregating check results, as the [purpose of the aggregation][8] should be to act on the state of the aggregated result(s) rather than the individual check result(s)._ [1]: ../checks#check-results [2]: ../../api/aggregates [3]: ../checks#check-definition-specification [4]: ../checks#check-attributes [5]: ../checks#check-definition-specification [6]: ../checks#check-configuration [7]: ../checks#standalone-checks [8]: #when-should-check-aggregates-be-used [9]: ../checks#how-are-checks-scheduled
sensu/sensu-docs
archived/sensu-core/1.8/reference/aggregates.md
Markdown
mit
5,864
module IncomeTax module Countries class Morocco < Models::Progressive register 'Morocco', 'MA', 'MAR' currency 'MAD' level 30_000, '0%' level 50_000, '10%' level 60_000, '20%' level 80_000, '30%' level 180_000, '34%' remainder '38%' end end end
askl56/income-tax
lib/income_tax/countries/morocco.rb
Ruby
mit
310
<!DOCTYPE html> <html> <head lang="ru"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>Template</title> <link href="http://themesanytime.com/startui/demo/img/favicon.144x144.png" rel="apple-touch-icon" type="image/png" sizes="144x144"> <link href="http://themesanytime.com/startui/demo/img/favicon.114x114.png" rel="apple-touch-icon" type="image/png" sizes="114x114"> <link href="http://themesanytime.com/startui/demo/img/favicon.72x72.png" rel="apple-touch-icon" type="image/png" sizes="72x72"> <link href="http://themesanytime.com/startui/demo/img/favicon.57x57.png" rel="apple-touch-icon" type="image/png"> <link href="http://themesanytime.com/startui/demo/img/favicon.png" rel="icon" type="image/png"> <link href="http://themesanytime.com/startui/demo/img/favicon.ico" rel="shortcut icon"> <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> <script src="js/plugins.js"></script> <script src="js/app.js"></script> <link rel="stylesheet" href="css/lib/font-awesome/font-awesome.min.css"> <link rel="stylesheet" href="css/main.css"> </head> <body> <header class="site-header"> <div class="container-fluid"> <a href="profile.html#" class="site-logo"> <img class="hidden-md-down" src="img/logo-2.png" alt=""> <img class="hidden-lg-up" src="img/logo-2-mob.png" alt=""> </a> <button class="hamburger hamburger--htla"> <span>toggle menu</span> </button> <div class="site-header-content"> <div class="site-header-content-in"> <div class="site-header-shown"> <div class="dropdown dropdown-notification notif"> <a href="profile.html#" class="header-alarm dropdown-toggle active" id="dd-notification" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <i class="font-icon-alarm"></i> </a> <div class="dropdown-menu dropdown-menu-right dropdown-menu-notif" aria-labelledby="dd-notification"> <div class="dropdown-menu-notif-header"> Notifications <span class="label label-pill label-danger">4</span> </div> <div class="dropdown-menu-notif-list"> <div class="dropdown-menu-notif-item"> <div class="photo"> <img src="img/photo-64-1.jpg" alt=""> </div> <div class="dot"></div> <a href="profile.html#">Morgan</a> was bothering about something <div class="color-blue-grey-lighter">7 hours ago</div> </div> <div class="dropdown-menu-notif-item"> <div class="photo"> <img src="img/photo-64-2.jpg" alt=""> </div> <div class="dot"></div> <a href="profile.html#">Lioneli</a> had commented on this <a href="profile.html#">Super Important Thing</a> <div class="color-blue-grey-lighter">7 hours ago</div> </div> <div class="dropdown-menu-notif-item"> <div class="photo"> <img src="img/photo-64-3.jpg" alt=""> </div> <div class="dot"></div> <a href="profile.html#">Xavier</a> had commented on the <a href="profile.html#">Movie title</a> <div class="color-blue-grey-lighter">7 hours ago</div> </div> <div class="dropdown-menu-notif-item"> <div class="photo"> <img src="img/photo-64-4.jpg" alt=""> </div> <a href="profile.html#">Lionely</a> wants to go to <a href="profile.html#">Cinema</a> with you to see <a href="profile.html#">This Movie</a> <div class="color-blue-grey-lighter">7 hours ago</div> </div> </div> <div class="dropdown-menu-notif-more"> <a href="profile.html#">See more</a> </div> </div> </div> <div class="dropdown dropdown-notification messages"> <a href="profile.html#" class="header-alarm dropdown-toggle active" id="dd-messages" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <i class="font-icon-mail"></i> </a> <div class="dropdown-menu dropdown-menu-right dropdown-menu-messages" aria-labelledby="dd-messages"> <div class="dropdown-menu-messages-header"> <ul class="nav" role="tablist"> <li class="nav-item"> <a class="nav-link active" data-toggle="tab" href="profile.html#tab-incoming" role="tab"> Inbox <span class="label label-pill label-danger">8</span> </a> </li> <li class="nav-item"> <a class="nav-link" data-toggle="tab" href="profile.html#tab-outgoing" role="tab">Outbox</a> </li> </ul> <!--<button type="button" class="create"> <i class="font-icon font-icon-pen-square"></i> </button>--> </div> <div class="tab-content"> <div class="tab-pane active" id="tab-incoming" role="tabpanel"> <div class="dropdown-menu-messages-list"> <a href="profile.html#" class="mess-item"> <span class="avatar-preview avatar-preview-32"><img src="img/photo-64-2.jpg" alt=""></span> <span class="mess-item-name">Tim Collins</span> <span class="mess-item-txt">Morgan was bothering about something!</span> </a> <a href="profile.html#" class="mess-item"> <span class="avatar-preview avatar-preview-32"><img src="img/avatar-2-64.png" alt=""></span> <span class="mess-item-name">Christian Burton</span> <span class="mess-item-txt">Morgan was bothering about something! Morgan was bothering about something.</span> </a> <a href="profile.html#" class="mess-item"> <span class="avatar-preview avatar-preview-32"><img src="img/photo-64-2.jpg" alt=""></span> <span class="mess-item-name">Tim Collins</span> <span class="mess-item-txt">Morgan was bothering about something!</span> </a> <a href="profile.html#" class="mess-item"> <span class="avatar-preview avatar-preview-32"><img src="img/avatar-2-64.png" alt=""></span> <span class="mess-item-name">Christian Burton</span> <span class="mess-item-txt">Morgan was bothering about something...</span> </a> </div> </div> <div class="tab-pane" id="tab-outgoing" role="tabpanel"> <div class="dropdown-menu-messages-list"> <a href="profile.html#" class="mess-item"> <span class="avatar-preview avatar-preview-32"><img src="img/avatar-2-64.png" alt=""></span> <span class="mess-item-name">Christian Burton</span> <span class="mess-item-txt">Morgan was bothering about something! Morgan was bothering about something...</span> </a> <a href="profile.html#" class="mess-item"> <span class="avatar-preview avatar-preview-32"><img src="img/photo-64-2.jpg" alt=""></span> <span class="mess-item-name">Tim Collins</span> <span class="mess-item-txt">Morgan was bothering about something! Morgan was bothering about something.</span> </a> <a href="profile.html#" class="mess-item"> <span class="avatar-preview avatar-preview-32"><img src="img/avatar-2-64.png" alt=""></span> <span class="mess-item-name">Christian Burtons</span> <span class="mess-item-txt">Morgan was bothering about something!</span> </a> <a href="profile.html#" class="mess-item"> <span class="avatar-preview avatar-preview-32"><img src="img/photo-64-2.jpg" alt=""></span> <span class="mess-item-name">Tim Collins</span> <span class="mess-item-txt">Morgan was bothering about something!</span> </a> </div> </div> </div> <div class="dropdown-menu-notif-more"> <a href="profile.html#">See more</a> </div> </div> </div> <div class="dropdown dropdown-lang"> <button class="dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <span class="flag-icon flag-icon-us"></span> </button> <div class="dropdown-menu dropdown-menu-right"> <div class="dropdown-menu-col"> <a class="dropdown-item" href="profile.html#"><span class="flag-icon flag-icon-ru"></span>Русский</a> <a class="dropdown-item" href="profile.html#"><span class="flag-icon flag-icon-de"></span>Deutsch</a> <a class="dropdown-item" href="profile.html#"><span class="flag-icon flag-icon-it"></span>Italiano</a> <a class="dropdown-item" href="profile.html#"><span class="flag-icon flag-icon-es"></span>Español</a> <a class="dropdown-item" href="profile.html#"><span class="flag-icon flag-icon-pl"></span>Polski</a> <a class="dropdown-item" href="profile.html#"><span class="flag-icon flag-icon-li"></span>Lietuviu</a> </div> <div class="dropdown-menu-col"> <a class="dropdown-item current" href="profile.html#"><span class="flag-icon flag-icon-us"></span>English</a> <a class="dropdown-item" href="profile.html#"><span class="flag-icon flag-icon-fr"></span>Français</a> <a class="dropdown-item" href="profile.html#"><span class="flag-icon flag-icon-by"></span>Беларускi</a> <a class="dropdown-item" href="profile.html#"><span class="flag-icon flag-icon-ua"></span>Українська</a> <a class="dropdown-item" href="profile.html#"><span class="flag-icon flag-icon-cz"></span>Česky</a> <a class="dropdown-item" href="profile.html#"><span class="flag-icon flag-icon-ch"></span>中國</a> </div> </div> </div> <div class="dropdown user-menu"> <button class="dropdown-toggle" id="dd-user-menu" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <img src="img/avatar-2-64.png" alt=""> </button> <div class="dropdown-menu dropdown-menu-right" aria-labelledby="dd-user-menu"> <a class="dropdown-item" href="profile.html#"><span class="font-icon glyphicon glyphicon-user"></span>Profile</a> <a class="dropdown-item" href="profile.html#"><span class="font-icon glyphicon glyphicon-cog"></span>Settings</a> <a class="dropdown-item" href="profile.html#"><span class="font-icon glyphicon glyphicon-question-sign"></span>Help</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="profile.html#"><span class="font-icon glyphicon glyphicon-log-out"></span>Logout</a> </div> </div> <button type="button" class="burger-right"> <i class="font-icon-menu-addl"></i> </button> </div><!--.site-header-shown--> <div class="mobile-menu-right-overlay"></div> <div class="site-header-collapsed"> <div class="site-header-collapsed-in"> <div class="dropdown dropdown-typical"> <a class="dropdown-toggle" id="dd-header-sales" data-target="#" href="http://example.com" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <span class="font-icon font-icon-wallet"></span> <span class="lbl">Sales</span> </a> <div class="dropdown-menu" aria-labelledby="dd-header-sales"> <a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-home"></span>Quant and Verbal</a> <a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-cart"></span>Real Gmat Test</a> <a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-speed"></span>Prep Official App</a> <a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-users"></span>CATprer Test</a> <a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-comments"></span>Third Party Test</a> </div> </div> <div class="dropdown dropdown-typical"> <a class="dropdown-toggle" id="dd-header-marketing" data-target="#" href="http://example.com" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <span class="font-icon font-icon-cogwheel"></span> <span class="lbl">Marketing automation</span> </a> <div class="dropdown-menu" aria-labelledby="dd-header-marketing"> <a class="dropdown-item" href="profile.html#">Current Search</a> <a class="dropdown-item" href="profile.html#">Search for Issues</a> <div class="dropdown-divider"></div> <div class="dropdown-header">Recent issues</div> <a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-home"></span>Quant and Verbal</a> <a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-cart"></span>Real Gmat Test</a> <a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-speed"></span>Prep Official App</a> <a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-users"></span>CATprer Test</a> <a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-comments"></span>Third Party Test</a> <div class="dropdown-more"> <div class="dropdown-more-caption padding">more...</div> <div class="dropdown-more-sub"> <div class="dropdown-more-sub-in"> <a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-home"></span>Quant and Verbal</a> <a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-cart"></span>Real Gmat Test</a> <a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-speed"></span>Prep Official App</a> <a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-users"></span>CATprer Test</a> <a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-comments"></span>Third Party Test</a> </div> </div> </div> <div class="dropdown-divider"></div> <a class="dropdown-item" href="profile.html#">Import Issues from CSV</a> <div class="dropdown-divider"></div> <div class="dropdown-header">Filters</div> <a class="dropdown-item" href="profile.html#">My Open Issues</a> <a class="dropdown-item" href="profile.html#">Reported by Me</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="profile.html#">Manage filters</a> <div class="dropdown-divider"></div> <div class="dropdown-header">Timesheet</div> <a class="dropdown-item" href="profile.html#">Subscribtions</a> </div> </div> <div class="dropdown dropdown-typical"> <a class="dropdown-toggle" id="dd-header-social" data-target="#" href="http://example.com" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <span class="font-icon font-icon-share"></span> <span class="lbl">Social media</span> </a> <div class="dropdown-menu" aria-labelledby="dd-header-social"> <a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-home"></span>Quant and Verbal</a> <a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-cart"></span>Real Gmat Test</a> <a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-speed"></span>Prep Official App</a> <a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-users"></span>CATprer Test</a> <a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-comments"></span>Third Party Test</a> </div> </div> <div class="dropdown dropdown-typical"> <a href="profile.html#" class="dropdown-toggle no-arr"> <span class="font-icon font-icon-page"></span> <span class="lbl">Projects</span> <span class="label label-pill label-danger">35</span> </a> </div> <div class="dropdown dropdown-typical"> <a class="dropdown-toggle" id="dd-header-form-builder" data-target="#" href="http://example.com" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <span class="font-icon font-icon-pencil"></span> <span class="lbl">Form builder</span> </a> <div class="dropdown-menu" aria-labelledby="dd-header-form-builder"> <a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-home"></span>Quant and Verbal</a> <a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-cart"></span>Real Gmat Test</a> <a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-speed"></span>Prep Official App</a> <a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-users"></span>CATprer Test</a> <a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-comments"></span>Third Party Test</a> </div> </div> <div class="dropdown"> <button class="btn btn-rounded dropdown-toggle" id="dd-header-add" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Add </button> <div class="dropdown-menu" aria-labelledby="dd-header-add"> <a class="dropdown-item" href="profile.html#">Quant and Verbal</a> <a class="dropdown-item" href="profile.html#">Real Gmat Test</a> <a class="dropdown-item" href="profile.html#">Prep Official App</a> <a class="dropdown-item" href="profile.html#">CATprer Test</a> <a class="dropdown-item" href="profile.html#">Third Party Test</a> </div> </div> <div class="help-dropdown"> <button type="button"> <i class="font-icon font-icon-help"></i> </button> <div class="help-dropdown-popup"> <div class="help-dropdown-popup-side"> <ul> <li><a href="profile.html#">Getting Started</a></li> <li><a href="profile.html#" class="active">Creating a new project</a></li> <li><a href="profile.html#">Adding customers</a></li> <li><a href="profile.html#">Settings</a></li> <li><a href="profile.html#">Importing data</a></li> <li><a href="profile.html#">Exporting data</a></li> </ul> </div> <div class="help-dropdown-popup-cont"> <div class="help-dropdown-popup-cont-in"> <div class="jscroll"> <a href="profile.html#" class="help-dropdown-popup-item"> Lorem Ipsum is simply <span class="describe">Lorem Ipsum has been the industry's standard dummy text </span> </a> <a href="profile.html#" class="help-dropdown-popup-item"> Contrary to popular belief <span class="describe">Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC</span> </a> <a href="profile.html#" class="help-dropdown-popup-item"> The point of using Lorem Ipsum <span class="describe">Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text</span> </a> <a href="profile.html#" class="help-dropdown-popup-item"> Lorem Ipsum <span class="describe">There are many variations of passages of Lorem Ipsum available</span> </a> <a href="profile.html#" class="help-dropdown-popup-item"> Lorem Ipsum is simply <span class="describe">Lorem Ipsum has been the industry's standard dummy text </span> </a> <a href="profile.html#" class="help-dropdown-popup-item"> Contrary to popular belief <span class="describe">Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC</span> </a> <a href="profile.html#" class="help-dropdown-popup-item"> The point of using Lorem Ipsum <span class="describe">Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text</span> </a> <a href="profile.html#" class="help-dropdown-popup-item"> Lorem Ipsum <span class="describe">There are many variations of passages of Lorem Ipsum available</span> </a> <a href="profile.html#" class="help-dropdown-popup-item"> Lorem Ipsum is simply <span class="describe">Lorem Ipsum has been the industry's standard dummy text </span> </a> <a href="profile.html#" class="help-dropdown-popup-item"> Contrary to popular belief <span class="describe">Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC</span> </a> <a href="profile.html#" class="help-dropdown-popup-item"> The point of using Lorem Ipsum <span class="describe">Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text</span> </a> <a href="profile.html#" class="help-dropdown-popup-item"> Lorem Ipsum <span class="describe">There are many variations of passages of Lorem Ipsum available</span> </a> </div> </div> </div> </div> </div><!--.help-dropdown--> <div class="site-header-search-container"> <form class="site-header-search closed"> <input type="text" placeholder="Search"/> <button type="submit"> <span class="font-icon-search"></span> </button> <div class="overlay"></div> </form> </div> </div><!--.site-header-collapsed-in--> </div><!--.site-header-collapsed--> </div><!--site-header-content-in--> </div><!--.site-header-content--> </div><!--.container-fluid--> </header><!--.site-header--> <div class="page-content"> <div class="container-fluid"> <div class="row"> <div class="col-lg-6 col-lg-push-3 col-md-12"> <form class="box-typical"> <input type="text" class="write-something" placeholder="Write Something..."/> <div class="box-typical-footer"> <div class="tbl"> <div class="tbl-row"> <div class="tbl-cell"> <button type="button" class="btn-icon"> <i class="font-icon font-icon-earth"></i> </button> <button type="button" class="btn-icon"> <i class="font-icon font-icon-picture"></i> </button> <button type="button" class="btn-icon"> <i class="font-icon font-icon-calend"></i> </button> <button type="button" class="btn-icon"> <i class="font-icon font-icon-video-fill"></i> </button> </div> <div class="tbl-cell tbl-cell-action"> <button type="submit" class="btn btn-rounded">Send</button> </div> </div> </div> </div> </form><!--.box-typical--> <section class="box-typical"> <header class="box-typical-header-sm"> Posts <div class="slider-arrs"> <button type="button" class="posts-slider-prev"> <i class="font-icon font-icon-arrow-left"></i> </button> <button type="button" class="posts-slider-next"> <i class="font-icon font-icon-arrow-right"></i> </button> </div> </header> <div class="posts-slider"> <div class="slide"> <article class="post-announce"> <div class="post-announce-pic"> <a href="profile.html#"> <img src="img/post-1.jpeg" alt=""> </a> </div> <div class="post-announce-title"> <a href="profile.html#">3 Myths That Confuse the D Myths That Confuse the D Myths That Confuse the D</a> </div> <div class="post-announce-date">Februrary 19, 2016</div> <ul class="post-announce-meta"> <li> <i class="font-icon font-icon-eye"></i> 18 </li> <li> <i class="font-icon font-icon-heart"></i> 5K </li> <li> <i class="font-icon font-icon-comment"></i> 3K </li> </ul> </article> </div><!--.slide--> <div class="slide"> <article class="post-announce"> <div class="post-announce-pic"> <a href="profile.html#"> <img src="img/post-2.jpg" alt=""> </a> </div> <div class="post-announce-title"> <a href="profile.html#">How Much Do We Spend on How Much Do We Spend on How Much Do We Spend on </a> </div> <div class="post-announce-date">January 21, 2016</div> <ul class="post-announce-meta"> <li> <i class="font-icon font-icon-eye"></i> 18 </li> <li> <i class="font-icon font-icon-heart"></i> 5K </li> <li> <i class="font-icon font-icon-comment"></i> 3K </li> </ul> </article> </div><!--.slide--> <div class="slide"> <article class="post-announce"> <div class="post-announce-pic"> <a href="profile.html#"> <img src="img/post-3.jpeg" alt=""> </a> </div> <div class="post-announce-title"> <a href="profile.html#">Good News You Might Have Good News You Might Have Good News You Might Have </a> </div> <div class="post-announce-date">December 30, 2016</div> <ul class="post-announce-meta"> <li> <i class="font-icon font-icon-eye"></i> 18 </li> <li> <i class="font-icon font-icon-heart"></i> 5K </li> <li> <i class="font-icon font-icon-comment"></i> 3K </li> </ul> </article> </div><!--.slide--> <div class="slide"> <article class="post-announce"> <div class="post-announce-pic"> <a href="profile.html#"> <img src="img/post-1.jpeg" alt=""> </a> </div> <div class="post-announce-title"> <a href="profile.html#">3 Myths That Confuse the D Myths That Confuse the D Myths That Confuse the D</a> </div> <div class="post-announce-date">Februrary 19, 2016</div> <ul class="post-announce-meta"> <li> <i class="font-icon font-icon-eye"></i> 18 </li> <li> <i class="font-icon font-icon-heart"></i> 5K </li> <li> <i class="font-icon font-icon-comment"></i> 3K </li> </ul> </article> </div><!--.slide--> <div class="slide"> <article class="post-announce"> <div class="post-announce-pic"> <a href="profile.html#"> <img src="img/post-2.jpg" alt=""> </a> </div> <div class="post-announce-title"> <a href="profile.html#">How Much Do We Spend on How Much Do We Spend on How Much Do We Spend on </a> </div> <div class="post-announce-date">January 21, 2016</div> <ul class="post-announce-meta"> <li> <i class="font-icon font-icon-eye"></i> 18 </li> <li> <i class="font-icon font-icon-heart"></i> 5K </li> <li> <i class="font-icon font-icon-comment"></i> 3K </li> </ul> </article> </div><!--.slide--> <div class="slide"> <article class="post-announce"> <div class="post-announce-pic"> <a href="profile.html#"> <img src="img/post-3.jpeg" alt=""> </a> </div> <div class="post-announce-title"> <a href="profile.html#">Good News You Might Have Good News You Might Have Good News You Might Have </a> </div> <div class="post-announce-date">December 30, 2016</div> <ul class="post-announce-meta"> <li> <i class="font-icon font-icon-eye"></i> 18 </li> <li> <i class="font-icon font-icon-heart"></i> 5K </li> <li> <i class="font-icon font-icon-comment"></i> 3K </li> </ul> </article> </div><!--.slide--> </div><!--.posts-slider--> </section><!--.box-typical--> <section class="box-typical"> <header class="box-typical-header-sm">Background</header> <article class="profile-info-item"> <header class="profile-info-item-header"> <i class="font-icon font-icon-notebook-bird"></i> Summary </header> <div class="text-block text-block-typical"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> <p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. </p> </div> </article><!--.profile-info-item--> <article class="profile-info-item"> <header class="profile-info-item-header"> <i class="font-icon font-icon-case"></i> Experience </header> <ul class="exp-timeline"> <li class="exp-timeline-item"> <div class="dot"></div> <div class="tbl"> <div class="tbl-row"> <div class="tbl-cell"> <div class="exp-timeline-range">2000 President</div> <div class="exp-timeline-status">Co-founder, Chairman</div> <div class="exp-timeline-location"><a href="profile.html#">Company</a></div> </div> <div class="tbl-cell tbl-cell-logo"> <img src="img/logo-2.png" alt=""> </div> </div> </div> </li> <li class="exp-timeline-item"> <div class="dot"></div> <div class="tbl"> <div class="tbl-row"> <div class="tbl-cell"> <div class="exp-timeline-range">1992–1999</div> <div class="exp-timeline-status">Senior Developer</div> <div class="exp-timeline-location"><a href="profile.html#">YouTube</a></div> </div> <div class="tbl-cell tbl-cell-logo"> <img src="img/logo-2.png" alt=""> </div> </div> </div> </li> <li class="exp-timeline-item"> <div class="dot"></div> <div class="tbl"> <div class="tbl-row"> <div class="tbl-cell"> <div class="exp-timeline-range">2000 President</div> <div class="exp-timeline-status">Co-founder, Chairman</div> <div class="exp-timeline-location"><a href="profile.html#">Company</a></div> </div> <div class="tbl-cell tbl-cell-logo"> <img src="img/logo-2.png" alt=""> </div> </div> </div> </li> </ul> </article><!--.profile-info-item--> <article class="profile-info-item"> <header class="profile-info-item-header"> <i class="font-icon font-icon-award"></i> Edication </header> <ul class="exp-timeline"> <li class="exp-timeline-item"> <div class="dot"></div> <div class="tbl"> <div class="tbl-row"> <div class="tbl-cell"> <div class="exp-timeline-range">1973 – 1975</div> <div class="exp-timeline-status">Harvard University</div> <div class="exp-timeline-location"><a href="profile.html#">BS Computer Science</a></div> </div> <div class="tbl-cell tbl-cell-logo"> <img src="img/logo-2.png" alt=""> </div> </div> </div> </li> <li class="exp-timeline-item"> <div class="dot"></div> <div class="tbl"> <div class="tbl-row"> <div class="tbl-cell"> <div class="exp-timeline-range">1960 – 1973</div> <div class="exp-timeline-status">Lakeside Scool, Seattle</div> </div> <div class="tbl-cell tbl-cell-logo"> <img src="img/logo-2.png" alt=""> </div> </div> </div> </li> </ul> </article><!--.profile-info-item--> <article class="profile-info-item"> <header class="profile-info-item-header"> <i class="font-icon font-icon-lamp"></i> Skills </header> <section class="skill-item tbl"> <div class="tbl-row"> <div class="tbl-cell tbl-cell-num"> <div class="skill-circle skill-circle-num">74</div> </div> <div class="tbl-cell tbl-cell-txt">Social Media Marketing</div> <div class="tbl-cell tbl-cell-users"> <img class="skill-user-photo" src="img/avatar-1-64.png" alt=""/> <img class="skill-user-photo" src="img/photo-64-3.jpg" alt=""/> <img class="skill-user-photo" src="img/photo-64-4.jpg" alt=""/> <div class="skill-circle skill-circle-users">+74</div> </div> </div> </section><!--.skill-item--> <section class="skill-item tbl"> <div class="tbl-row"> <div class="tbl-cell tbl-cell-num"> <div class="skill-circle skill-circle-num">67</div> </div> <div class="tbl-cell tbl-cell-txt">Web Development</div> <div class="tbl-cell tbl-cell-users"> <img class="skill-user-photo" src="img/avatar-2-64.png" alt=""/> <img class="skill-user-photo" src="img/photo-64-2.jpg" alt=""/> <img class="skill-user-photo" src="img/photo-64-3.jpg" alt=""/> <div class="skill-circle skill-circle-users">+82</div> </div> </div> </section><!--.skill-item--> <section class="skill-item tbl"> <div class="tbl-row"> <div class="tbl-cell tbl-cell-num"> <div class="skill-circle skill-circle-num">25</div> </div> <div class="tbl-cell tbl-cell-txt">Search Engine Optimization</div> <div class="tbl-cell tbl-cell-users"> <img class="skill-user-photo" src="img/avatar-3-64.png" alt=""/> <img class="skill-user-photo" src="img/photo-64-1.jpg" alt=""/> <img class="skill-user-photo" src="img/photo-64-2.jpg" alt=""/> <div class="skill-circle skill-circle-users">+4</div> </div> </div> </section><!--.skill-item--> <section class="skill-item tbl"> <div class="tbl-row"> <div class="tbl-cell tbl-cell-num"> <div class="skill-circle skill-circle-num">20</div> </div> <div class="tbl-cell tbl-cell-txt">User Experience Design</div> <div class="tbl-cell tbl-cell-users"> <img class="skill-user-photo" src="img/photo-64-3.jpg" alt=""/> <img class="skill-user-photo" src="img/photo-64-4.jpg" alt=""/> <img class="skill-user-photo" src="img/photo-64-1.jpg" alt=""/> <div class="skill-circle skill-circle-users">+13</div> </div> </div> </section><!--.skill-item--> </article><!--.profile-info-item--> <article class="profile-info-item"> <header class="profile-info-item-header"> <i class="font-icon font-icon-star"></i> More interest </header> <div class="profile-interests"> <a href="profile.html#" class="label label-light-grey">Interest</a> <a href="profile.html#" class="label label-light-grey">Example</a> <a href="profile.html#" class="label label-light-grey">One more</a> <a href="profile.html#" class="label label-light-grey">Here is example interest</a> <a href="profile.html#" class="label label-light-grey">Interest</a> <a href="profile.html#" class="label label-light-grey">Example</a> <a href="profile.html#" class="label label-light-grey">One more</a> <a href="profile.html#" class="label label-light-grey">Here is example interest</a> <a href="profile.html#" class="label label-light-grey">Interest</a> <a href="profile.html#" class="label label-light-grey">Example</a> <a href="profile.html#" class="label label-light-grey">One more</a> <a href="profile.html#" class="label label-light-grey">Here is example interest</a> </div> </article><!--.profile-info-item--> </section><!--.box-typical--> <section class="box-typical"> <header class="box-typical-header-sm"> Recomendations <div class="slider-arrs"> <button type="button" class="recomendations-slider-prev"> <i class="font-icon font-icon-arrow-left"></i> </button> <button type="button" class="recomendations-slider-next"> <i class="font-icon font-icon-arrow-right"></i> </button> </div> </header> <div class="recomendations-slider"> <div class="slide"> <div class="citate-speech-bubble"> <i class="font-icon-quote"></i> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. </div> <div class="user-card-row"> <div class="tbl-row"> <div class="tbl-cell tbl-cell-photo"> <a href="profile.html#"> <img src="img/photo-64-3.jpg" alt=""> </a> </div> <div class="tbl-cell"> <p class="user-card-row-name"><a href="profile.html#">Molly Bridjet</a></p> <p class="user-card-row-status"><a href="profile.html#">PatchworkLabs</a></p> </div> </div> </div> </div><!--.slide--> <div class="slide"> <div class="citate-speech-bubble"> <i class="font-icon-quote"></i> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. </div> <div class="user-card-row"> <div class="tbl-row"> <div class="tbl-cell tbl-cell-photo"> <a href="profile.html#"> <img src="img/photo-64-1.jpg" alt=""> </a> </div> <div class="tbl-cell"> <p class="user-card-row-name"><a href="profile.html#">Molly Bridjet</a></p> <p class="user-card-row-status"><a href="profile.html#">PatchworkLabs</a></p> </div> </div> </div> </div><!--.slide--> <div class="slide"> <div class="citate-speech-bubble"> <i class="font-icon-quote"></i> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. </div> <div class="user-card-row"> <div class="tbl-row"> <div class="tbl-cell tbl-cell-photo"> <a href="profile.html#"> <img src="img/photo-64-2.jpg" alt=""> </a> </div> <div class="tbl-cell"> <p class="user-card-row-name"><a href="profile.html#">Molly Bridjet</a></p> <p class="user-card-row-status"><a href="profile.html#">PatchworkLabs</a></p> </div> </div> </div> </div><!--.slide--> <div class="slide"> <div class="citate-speech-bubble"> <i class="font-icon-quote"></i> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. </div> <div class="user-card-row"> <div class="tbl-row"> <div class="tbl-cell tbl-cell-photo"> <a href="profile.html#"> <img src="img/photo-64-4.jpg" alt=""> </a> </div> <div class="tbl-cell"> <p class="user-card-row-name"><a href="profile.html#">Molly Bridjet</a></p> <p class="user-card-row-status"><a href="profile.html#">PatchworkLabs</a></p> </div> </div> </div> </div><!--.slide--> <div class="slide"> <div class="citate-speech-bubble"> <i class="font-icon-quote"></i> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. </div> <div class="user-card-row"> <div class="tbl-row"> <div class="tbl-cell tbl-cell-photo"> <a href="profile.html#"> <img src="img/photo-64-2.jpg" alt=""> </a> </div> <div class="tbl-cell"> <p class="user-card-row-name"><a href="profile.html#">Molly Bridjet</a></p> <p class="user-card-row-status"><a href="profile.html#">PatchworkLabs</a></p> </div> </div> </div> </div><!--.slide--> <div class="slide"> <div class="citate-speech-bubble"> <i class="font-icon-quote"></i> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. </div> <div class="user-card-row"> <div class="tbl-row"> <div class="tbl-cell tbl-cell-photo"> <a href="profile.html#"> <img src="img/photo-64-4.jpg" alt=""> </a> </div> <div class="tbl-cell"> <p class="user-card-row-name"><a href="profile.html#">Molly Bridjet</a></p> <p class="user-card-row-status"><a href="profile.html#">PatchworkLabs</a></p> </div> </div> </div> </div><!--.slide--> </div><!--.recomendations-slider--> </section><!--.box-typical--> <section class="box-typical"> <header class="box-typical-header-sm">Following</header> <div class="profile-following"> <div class="profile-following-grid"> <div class="col"> <article class="follow-group"> <div class="follow-group-logo"> <a href="profile.html#" class="follow-group-logo-in"><img src="img/logo-2.png" alt=""></a> </div> <div class="follow-group-name"> <a href="profile.html#">KIPP Foundation</a> </div> <div class="follow-group-link"> <a href="profile.html#"> <span class="plus-link-circle"><span>&plus;</span></span> Follow </a> </div> </article> </div> <div class="col"> <article class="follow-group"> <div class="follow-group-logo"> <a href="profile.html#" class="follow-group-logo-in"><img src="img/logo-2.png" alt=""></a> </div> <div class="follow-group-name"> <a href="profile.html#">KIPP Foundation</a> </div> <div class="follow-group-link"> <a href="profile.html#"> <span class="plus-link-circle"><span>&plus;</span></span> Follow </a> </div> </article> </div> <div class="col"> <article class="follow-group"> <div class="follow-group-logo"> <a href="profile.html#" class="follow-group-logo-in"><img src="img/logo-2.png" alt=""></a> </div> <div class="follow-group-name"> <a href="profile.html#">KIPP Foundation</a> </div> <div class="follow-group-link"> <a href="profile.html#"> <span class="plus-link-circle"><span>&plus;</span></span> Follow </a> </div> </article> </div> <div class="col"> <article class="follow-group"> <div class="follow-group-logo"> <a href="profile.html#" class="follow-group-logo-in"><img src="img/logo-2.png" alt=""></a> </div> <div class="follow-group-name"> <a href="profile.html#">KIPP Foundation</a> </div> <div class="follow-group-link"> <a href="profile.html#"> <span class="plus-link-circle"><span>&plus;</span></span> Follow </a> </div> </article> </div> </div> <a href="profile.html#" class="btn btn-rounded btn-primary-outline">See all (20)</a> </div><!--.profile-following--> </section><!--.box-typical--> </div><!--.col- --> <div class="col-lg-3 col-lg-pull-6 col-md-6 col-sm-6"> <section class="box-typical"> <div class="profile-card"> <div class="profile-card-photo"> <img src="img/photo-220-1.jpg" alt=""/> </div> <div class="profile-card-name">Sarah Sanchez</div> <div class="profile-card-status">Company Founder</div> <div class="profile-card-location">Greater Seattle Area</div> <button type="button" class="btn btn-rounded">Follow</button> <div class="btn-group"> <button type="button" class="btn btn-rounded btn-primary-outline dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Connect </button> <div class="dropdown-menu"> <a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-home"></span>Quant and Verbal</a> <a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-cart"></span>Real Gmat Test</a> <a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-speed"></span>Prep Official App</a> <a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-users"></span>CATprer Test</a> <a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-comments"></span>Third Party Test</a> </div> </div> </div><!--.profile-card--> <div class="profile-statistic tbl"> <div class="tbl-row"> <div class="tbl-cell"> <b>200</b> Connections </div> <div class="tbl-cell"> <b>1.9M</b> Followers </div> </div> </div> <ul class="profile-links-list"> <li class="nowrap"> <i class="font-icon font-icon-earth-bordered"></i> <a href="profile.html#">example.com</a> </li> <li class="nowrap"> <i class="font-icon font-icon-fb-fill"></i> <a href="profile.html#">facebook.com/example</a> </li> <li class="nowrap"> <i class="font-icon font-icon-vk-fill"></i> <a href="profile.html#">vk.com/example</a> </li> <li class="nowrap"> <i class="font-icon font-icon-in-fill"></i> <a href="profile.html#">linked.in/example</a> </li> <li class="nowrap"> <i class="font-icon font-icon-tw-fill"></i> <a href="profile.html#">twitter.com/example</a> </li> <li class="divider"></li> <li> <i class="font-icon font-icon-pdf-fill"></i> <a href="profile.html#">Export page as PDF</a> </li> </ul> </section><!--.box-typical--> <section class="box-typical"> <header class="box-typical-header-sm"> Friends &nbsp; <a href="profile.html#" class="full-count">268</a> </header> <div class="friends-list"> <article class="friends-list-item"> <div class="user-card-row"> <div class="tbl-row"> <div class="tbl-cell tbl-cell-photo"> <a href="profile.html#"> <img src="img/photo-64-2.jpg" alt=""> </a> </div> <div class="tbl-cell"> <p class="user-card-row-name status-online"><a href="profile.html#">Dan Cederholm</a></p> <p class="user-card-row-location">New York</p> </div> </div> </div> </article> <article class="friends-list-item"> <div class="user-card-row"> <div class="tbl-row"> <div class="tbl-cell tbl-cell-photo"> <a href="profile.html#"> <img src="img/photo-64-1.jpg" alt=""> </a> </div> <div class="tbl-cell"> <p class="user-card-row-name"><a href="profile.html#">Oykun Yilmaz</a></p> <p class="user-card-row-location">Los Angeles</p> </div> </div> </div> </article> <article class="friends-list-item"> <div class="user-card-row"> <div class="tbl-row"> <div class="tbl-cell tbl-cell-photo"> <a href="profile.html#"> <img src="img/photo-64-3.jpg" alt=""> </a> </div> <div class="tbl-cell"> <p class="user-card-row-name"><a href="profile.html#">Bill S Kenney</a></p> <p class="user-card-row-location">Cardiff</p> </div> </div> </div> </article> <article class="friends-list-item"> <div class="user-card-row"> <div class="tbl-row"> <div class="tbl-cell tbl-cell-photo"> <a href="profile.html#"> <img src="img/photo-64-4.jpg" alt=""> </a> </div> <div class="tbl-cell"> <p class="user-card-row-name"><a href="profile.html#">Maggy Smith</a></p> <p class="user-card-row-location">Dusseldorf</p> </div> </div> </div> </article> <article class="friends-list-item"> <div class="user-card-row"> <div class="tbl-row"> <div class="tbl-cell tbl-cell-photo"> <a href="profile.html#"> <img src="img/photo-64-2.jpg" alt=""> </a> </div> <div class="tbl-cell"> <p class="user-card-row-name"><a href="profile.html#">Dan Cederholm</a></p> <p class="user-card-row-location">New York</p> </div> </div> </div> </article> </div> </section><!--.box-typical--> </div><!--.col- --> <div class="col-lg-3 col-md-6 col-sm-6"> <section class="box-typical"> <header class="box-typical-header-sm">People also viewed</header> <div class="friends-list stripped"> <article class="friends-list-item"> <div class="user-card-row"> <div class="tbl-row"> <div class="tbl-cell tbl-cell-photo"> <a href="profile.html#"> <img src="img/photo-64-2.jpg" alt=""> </a> </div> <div class="tbl-cell"> <p class="user-card-row-name status-online"><a href="profile.html#">Dan Cederholm</a></p> <p class="user-card-row-status">Co-founder of <a href="profile.html#">Company</a></p> </div> <div class="tbl-cell tbl-cell-action"> <a href="profile.html#" class="plus-link-circle"><span>&plus;</span></a> </div> </div> </div> </article> <article class="friends-list-item"> <div class="user-card-row"> <div class="tbl-row"> <div class="tbl-cell tbl-cell-photo"> <a href="profile.html#"> <img src="img/photo-64-1.jpg" alt=""> </a> </div> <div class="tbl-cell"> <p class="user-card-row-name"><a href="profile.html#">Oykun Yilmaz</a></p> <p class="user-card-row-status">Co-founder of <a href="profile.html#">Company</a></p> </div> <div class="tbl-cell tbl-cell-action"> <a href="profile.html#" class="plus-link-circle"><span>&plus;</span></a> </div> </div> </div> </article> <article class="friends-list-item"> <div class="user-card-row"> <div class="tbl-row"> <div class="tbl-cell tbl-cell-photo"> <a href="profile.html#"> <img src="img/photo-64-3.jpg" alt=""> </a> </div> <div class="tbl-cell"> <p class="user-card-row-name"><a href="profile.html#">Bill S Kenney</a></p> <p class="user-card-row-status">Co-founder of <a href="profile.html#">Company</a></p> </div> <div class="tbl-cell tbl-cell-action"> <a href="profile.html#" class="plus-link-circle"><span>&plus;</span></a> </div> </div> </div> </article> <article class="friends-list-item"> <div class="user-card-row"> <div class="tbl-row"> <div class="tbl-cell tbl-cell-photo"> <a href="profile.html#"> <img src="img/photo-64-4.jpg" alt=""> </a> </div> <div class="tbl-cell"> <p class="user-card-row-name"><a href="profile.html#">Maggy Smith</a></p> <p class="user-card-row-status">Co-founder of <a href="profile.html#">Company</a></p> </div> <div class="tbl-cell tbl-cell-action"> <a href="profile.html#" class="plus-link-circle"><span>&plus;</span></a> </div> </div> </div> </article> <article class="friends-list-item"> <div class="user-card-row"> <div class="tbl-row"> <div class="tbl-cell tbl-cell-photo"> <a href="profile.html#"> <img src="img/photo-64-2.jpg" alt=""> </a> </div> <div class="tbl-cell"> <p class="user-card-row-name"><a href="profile.html#">Susan Andrews</a></p> <p class="user-card-row-status">Co-founder of <a href="profile.html#">Company</a></p> </div> <div class="tbl-cell tbl-cell-action"> <a href="profile.html#" class="plus-link-circle"><span>&plus;</span></a> </div> </div> </div> </article> </div> <div class="see-all"> <a href="profile.html#">See All (300)</a> </div> <section> <header class="box-typical-header-sm">More Influencer</header> <div class="profile-card-slider"> <div class="slide"> <div class="profile-card"> <div class="profile-card-photo"> <img src="img/photo-220-1.jpg" alt=""/> </div> <div class="profile-card-name">Jackie Tran</div> <div class="profile-card-status">Company Founder</div> <button type="button" class="btn btn-rounded btn-primary-outline">Follow</button> </div><!--.profile-card--> </div><!--.slide--> <div class="slide"> <div class="profile-card"> <div class="profile-card-photo"> <img src="img/avatar-1-256.png" alt=""/> </div> <div class="profile-card-name">Jackie Tran</div> <div class="profile-card-status">Company Founder</div> <button type="button" class="btn btn-rounded btn-primary-outline">Follow</button> </div><!--.profile-card--> </div><!--.slide--> <div class="slide"> <div class="profile-card"> <div class="profile-card-photo"> <img src="img/avatar-2-256.png" alt=""/> </div> <div class="profile-card-name">Sarah Sanchez</div> <div class="profile-card-status">Longnameexample<br/>corporation</div> <button type="button" class="btn btn-rounded btn-primary-outline">Follow</button> </div><!--.profile-card--> </div><!--.slide--> <div class="slide"> <div class="profile-card"> <div class="profile-card-photo"> <img src="img/avatar-3-256.png" alt=""/> </div> <div class="profile-card-name">Sarah Sanchez</div> <div class="profile-card-status">Longnameexample<br/>corporation</div> <button type="button" class="btn btn-rounded btn-primary-outline">Follow</button> </div><!--.profile-card--> </div><!--.slide--> </div><!--.profile-card-slider--> </section> </section><!--.box-typical--> <section class="box-typical"> <header class="box-typical-header-sm">People you may know</header> <div class="people-rel-list"> <div class="people-rel-list-name"><a href="profile.html#">Jackie Tran Anh</a> / Designer</div> <ul class="people-rel-list-photos"> <li><a href="profile.html#"><img src="img/photo-92-1.jpg" alt=""></a></li> <li><a href="profile.html#"><img src="img/photo-92-2.jpg" alt=""></a></li> <li><a href="profile.html#"><img src="img/photo-92-3.jpg" alt=""></a></li> <li><a href="profile.html#"><img src="img/avatar-1-128.png" alt=""></a></li> <li><a href="profile.html#"><img src="img/photo-92-2.jpg" alt=""></a></li> <li><a href="profile.html#"><img src="img/avatar-2-128.png" alt=""></a></li> <li><a href="profile.html#"><img src="img/photo-92-1.jpg" alt=""></a></li> <li><a href="profile.html#"><img src="img/avatar-3-128.png" alt=""></a></li> <li><a href="profile.html#"><img src="img/photo-92-3.jpg" alt=""></a></li> <li><a href="profile.html#"><img src="img/photo-92-1.jpg" alt=""></a></li> <li><a href="profile.html#"><img src="img/photo-92-2.jpg" alt=""></a></li> <li><a href="profile.html#"><img src="img/photo-92-3.jpg" alt=""></a></li> <li><a href="profile.html#"><img src="img/photo-92-1.jpg" alt=""></a></li> <li><a href="profile.html#"><img src="img/photo-92-2.jpg" alt=""></a></li> <li><a href="profile.html#"><img src="img/photo-92-3.jpg" alt=""></a></li> <li><a href="profile.html#"><img src="img/photo-92-1.jpg" alt=""></a></li> </ul> <form class="site-header-search"> <input type="text" placeholder="Search for people"/> <button type="submit"> <span class="font-icon-search"></span> </button> <div class="overlay"></div> </form> </div> </section><!--.box-typical--> </div><!--.col- --> </div><!--.row--> </div><!--.container-fluid--> </div><!--.page-content--> <!--Progress bar--> <!--<div class="circle-progress-bar pieProgress" role="progressbar" data-goal="100" data-barcolor="#ac6bec" data-barsize="10" aria-valuemin="0" aria-valuemax="100">--> <!--<span class="pie_progress__number">0%</span>--> <!--</div>--> </body> </html>
racerx2000/ne_stenka
application/demo/profile.html
HTML
mit
69,361
using System; namespace sep20v1.Areas.HelpPage { /// <summary> /// This represents a preformatted text sample on the help page. There's a display template named TextSample associated with this class. /// </summary> public class TextSample { public TextSample(string text) { if (text == null) { throw new ArgumentNullException("text"); } Text = text; } public string Text { get; private set; } public override bool Equals(object obj) { TextSample other = obj as TextSample; return other != null && Text == other.Text; } public override int GetHashCode() { return Text.GetHashCode(); } public override string ToString() { return Text; } } }
peteratseneca/dps907fall2013
Week_03/sep20v1/sep20v1/Areas/HelpPage/SampleGeneration/TextSample.cs
C#
mit
883
<?php namespace YB\Bundle\RemoteTranslationsBundle\Tests\Translation\Loader; use PHPUnit_Framework_TestCase; /** * Class AwsS3LoaderTest * @package YB\Bundle\RemoteTranslationsBundle\Tests\Translation\Loader */ class AwsS3LoaderTest extends PHPUnit_Framework_TestCase { /** * @param mixed $expected * @param mixed $result * * @dataProvider getExamples */ public function testIndex($expected, $result) { $this->assertSame($expected, $result); } /** * @return \Generator */ public function getExamples() { yield ['Lorem Ipsum', 'Lorem Ipsum']; } }
yurijbogdanov/symfony-remote-translations-bundle
Tests/Translation/Loader/AwsS3LoaderTest.php
PHP
mit
636
package com.syncano.android.lib.modules.users; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import com.syncano.android.lib.modules.Params; import com.syncano.android.lib.modules.Response; /** * Params to create new user. */ public class ParamsUserNew extends Params { /** Name of user */ @Expose @SerializedName(value = "user_name") private String userName; /** Nickname of user */ @Expose private String nick; /** Avatar base64 for user */ @Expose private String avatar; /** User's password. */ @Expose @SerializedName(value = "password") private String password; /** * @param userName * User name defining user. Can be <code>null</code>. */ public ParamsUserNew(String userName) { setUserName(userName); } @Override public String getMethodName() { return "user.new"; } public Response instantiateResponse() { return new ResponseUserNew(); } /** * @return user name */ public String getUserName() { return userName; } /** * Sets user name * * @param user_name * user name */ public void setUserName(String userName) { this.userName = userName; } /** * @return user nickname */ public String getNick() { return nick; } /** * Sets user nickname * * @param nick * nickname */ public void setNick(String nick) { this.nick = nick; } /** * @return avatar base64 */ public String getAvatar() { return avatar; } /** * Sets avatar base64 * * @param avatar * avatar base64 */ public void setAvatar(String avatar) { this.avatar = avatar; } /** * @return password */ public String getPassword() { return password; } /** * @param Sets * user password */ public void setPassword(String password) { this.password = password; } }
Syncano/syncano-android-demo
Eclipse/SyncanoLib/src/com/syncano/android/lib/modules/users/ParamsUserNew.java
Java
mit
1,864
XHCyclicReuseScrollView ======================= XHCyclicReuseScrollView is an extensible, reusable, recyclable rolling scrollView element.
RyanTech/XHCyclicReuseScrollView
README.md
Markdown
mit
140
<!DOCTYPE html> <!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang="en" > <!--<![endif]--> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>[POJ] 1276. Cash Machine &mdash; amoshyc&#39;s CPsolution 1.0 documentation</title> <link rel="stylesheet" href="../_static/css/theme.css" type="text/css" /> <link rel="stylesheet" href="../_static/css/mine.css" type="text/css" /> <link rel="index" title="Index" href="../genindex.html"/> <link rel="search" title="Search" href="../search.html"/> <link rel="top" title="amoshyc&#39;s CPsolution 1.0 documentation" href="../index.html"/> <link rel="up" title="3. POJ" href="poj.html"/> <link rel="next" title="[POJ] 1308. Is It A Tree?" href="p1308.html"/> <link rel="prev" title="[POJ] 1151. Atlantis" href="p1151.html"/> <script src="../_static/js/modernizr.min.js"></script> </head> <body class="wy-body-for-nav" role="document"> <div class="wy-grid-for-nav"> <nav data-toggle="wy-nav-shift" class="wy-nav-side"> <div class="wy-side-scroll"> <div class="wy-side-nav-search"> <a href="../index.html" class="icon icon-home"> amoshyc's CPsolution </a> <div class="version"> 1.0 </div> <div role="search"> <form id="rtd-search-form" class="wy-form" action="../search.html" method="get"> <input type="text" name="q" placeholder="Search docs" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> </div> <div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation"> <ul class="current"> <li class="toctree-l1"><a class="reference internal" href="../tutorials/tutorials.html">1. 常用演算法教學</a></li> <li class="toctree-l1"><a class="reference internal" href="../cf/cf.html">2. CF</a></li> <li class="toctree-l1 current"><a class="reference internal" href="poj.html">3. POJ</a><ul class="current"> <li class="toctree-l2"><a class="reference internal" href="p1151.html">[POJ] 1151. Atlantis</a></li> <li class="toctree-l2 current"><a class="current reference internal" href="#">[POJ] 1276. Cash Machine</a><ul> <li class="toctree-l3"><a class="reference internal" href="#id2">題目</a></li> <li class="toctree-l3"><a class="reference internal" href="#specification">Specification</a></li> <li class="toctree-l3"><a class="reference internal" href="#id3">分析</a></li> <li class="toctree-l3"><a class="reference internal" href="#ac-code">AC Code</a></li> </ul> </li> <li class="toctree-l2"><a class="reference internal" href="p1308.html">[POJ] 1308. Is It A Tree?</a></li> <li class="toctree-l2"><a class="reference internal" href="p1330.html">[POJ] 1330. Nearest Common Ancestors</a></li> <li class="toctree-l2"><a class="reference internal" href="p1442.html">[POJ] 1442. Black Box</a></li> <li class="toctree-l2"><a class="reference internal" href="p1769.html">[POJ] 1769. Minimizing maximizer</a></li> <li class="toctree-l2"><a class="reference internal" href="p1984.html">[POJ] 1984. Navigation Nightmare</a></li> <li class="toctree-l2"><a class="reference internal" href="p1988.html">[POJ] 1988. Cube Stacking</a></li> <li class="toctree-l2"><a class="reference internal" href="p1990.html">[POJ] 1990. MooFest</a></li> <li class="toctree-l2"><a class="reference internal" href="p2104.html">[POJ] 2104. K-th Number</a></li> <li class="toctree-l2"><a class="reference internal" href="p2135.html">[POJ] 2135. Farm Tour</a></li> <li class="toctree-l2"><a class="reference internal" href="p2186.html">[POJ] 2186. Popular Cows</a></li> <li class="toctree-l2"><a class="reference internal" href="p2230.html">[POJ] 2230. Watchcow</a></li> <li class="toctree-l2"><a class="reference internal" href="p2349.html">[POJ] 2349. Arctic Network</a></li> <li class="toctree-l2"><a class="reference internal" href="p2441.html">[POJ] 2441. Arrange the Bulls</a></li> <li class="toctree-l2"><a class="reference internal" href="p2686.html">[POJ] 2686. Traveling by Stagecoach</a></li> <li class="toctree-l2"><a class="reference internal" href="p2836.html">[POJ] 2836. Rectangular Covering</a></li> <li class="toctree-l2"><a class="reference internal" href="p2891.html">[POJ] 2891. Strange Way to Express Integers</a></li> <li class="toctree-l2"><a class="reference internal" href="p3041.html">[POJ] 3041. Asteroids</a></li> <li class="toctree-l2"><a class="reference internal" href="p3045.html">[POJ] 3045. Cow Acrobats</a></li> <li class="toctree-l2"><a class="reference internal" href="p3057.html">[POJ] 3057. Evacuation</a></li> <li class="toctree-l2"><a class="reference internal" href="p3171.html">[POJ] 3171. Cleaning Shifts</a></li> <li class="toctree-l2"><a class="reference internal" href="p3233.html">[POJ] 3233. Matrix Power Series</a></li> <li class="toctree-l2"><a class="reference internal" href="p3254.html">[POJ] 3254. Corn Fields</a></li> <li class="toctree-l2"><a class="reference internal" href="p3258.html">[POJ] 3258. River Hopscotch</a></li> <li class="toctree-l2"><a class="reference internal" href="p3264.html">[POJ] 3264. Balanced Lineup</a></li> <li class="toctree-l2"><a class="reference internal" href="p3273.html">[POJ] 3273. Monthly Expense</a></li> <li class="toctree-l2"><a class="reference internal" href="p3281.html">[POJ] 3281. Dining</a></li> <li class="toctree-l2"><a class="reference internal" href="p3321.html">[POJ] 3321. Apple Tree</a></li> <li class="toctree-l2"><a class="reference internal" href="p3368.html">[POJ] 3368. Frequent values</a></li> <li class="toctree-l2"><a class="reference internal" href="p3420.html">[POJ] 3420. Quad Tiling</a></li> <li class="toctree-l2"><a class="reference internal" href="p3468.html">[POJ] 3468. A Simple Problem with Integers</a></li> <li class="toctree-l2"><a class="reference internal" href="p3469.html">[POJ] 3469. Dual Core CPU</a></li> <li class="toctree-l2"><a class="reference internal" href="p3565.html">[POJ] 3565. Ants</a></li> <li class="toctree-l2"><a class="reference internal" href="p3580.html">[POJ] 3580. SuperMemo</a></li> <li class="toctree-l2"><a class="reference internal" href="p3686.html">[POJ] 3686. The Windy’s</a></li> <li class="toctree-l2"><a class="reference internal" href="p3734.html">[POJ] 3734. Blocks</a></li> <li class="toctree-l2"><a class="reference internal" href="p3735.html">[POJ] 3735. Training little cats</a></li> <li class="toctree-l2"><a class="reference internal" href="p3977.html">[POJ] 3977. Subset</a></li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="../uva/uva.html">4. UVA</a></li> <li class="toctree-l1"><a class="reference internal" href="../ptc/ptc.html">5. PTC</a></li> <li class="toctree-l1"><a class="reference internal" href="../other/other.html">6. Other</a></li> <li class="toctree-l1"><a class="reference internal" href="../template/template.html">7. Template</a></li> <li class="toctree-l1"><a class="reference internal" href="../tags.html">8. Tags</a></li> <li class="toctree-l1"><a class="reference internal" href="../cheatsheet.html">9. Cheatsheet</a></li> </ul> </div> </div> </nav> <section data-toggle="wy-nav-shift" class="wy-nav-content-wrap"> <nav class="wy-nav-top" role="navigation" aria-label="top navigation"> <i data-toggle="wy-nav-top" class="fa fa-bars"></i> <a href="../index.html">amoshyc's CPsolution</a> </nav> <div class="wy-nav-content"> <div class="rst-content"> <div role="navigation" aria-label="breadcrumbs navigation"> <ul class="wy-breadcrumbs"> <li><a href="../index.html">Docs</a> &raquo;</li> <li><a href="poj.html">3. POJ</a> &raquo;</li> <li>[POJ] 1276. Cash Machine</li> <li class="wy-breadcrumbs-aside"> <a href="../_sources/poj/p1276.rst.txt" rel="nofollow"> View page source</a> </li> </ul> <hr/> </div> <div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article"> <div itemprop="articleBody"> <div class="section" id="poj-1276-cash-machine"> <h1><a class="toc-backref" href="#id4">[POJ] 1276. Cash Machine</a><a class="headerlink" href="#poj-1276-cash-machine" title="Permalink to this headline">¶</a></h1> <div class="sidebar"> <p class="first sidebar-title">Tags</p> <ul class="last simple"> <li><code class="docutils literal"><span class="pre">tag_dp</span></code></li> </ul> </div> <div class="contents topic" id="toc"> <p class="topic-title first">TOC</p> <ul class="simple"> <li><a class="reference internal" href="#poj-1276-cash-machine" id="id4">[POJ] 1276. Cash Machine</a><ul> <li><a class="reference internal" href="#id2" id="id5">題目</a></li> <li><a class="reference internal" href="#specification" id="id6">Specification</a></li> <li><a class="reference internal" href="#id3" id="id7">分析</a></li> <li><a class="reference internal" href="#ac-code" id="id8">AC Code</a></li> </ul> </li> </ul> </div> <div class="section" id="id2"> <h2><a class="reference external" href="http://poj.org/problem?id=1276">題目</a><a class="headerlink" href="#id2" title="Permalink to this headline">¶</a></h2> <p>給定 N 個數字 D[i],第 i 個數字有 n[i] 個。 請問在 M 以下(含 M)所能組出的最大總和是多少?</p> </div> <div class="section" id="specification"> <h2><a class="toc-backref" href="#id6">Specification</a><a class="headerlink" href="#specification" title="Permalink to this headline">¶</a></h2> <div class="highlight-default"><div class="highlight"><pre><span></span><span class="mi">1</span> <span class="o">&lt;=</span> <span class="n">N</span> <span class="o">&lt;=</span> <span class="mi">10</span> <span class="mi">1</span> <span class="o">&lt;=</span> <span class="n">M</span> <span class="o">&lt;=</span> <span class="mi">10</span><span class="o">^</span><span class="mi">5</span> <span class="mi">1</span> <span class="o">&lt;=</span> <span class="n">n</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">&lt;=</span> <span class="mi">10</span><span class="o">^</span><span class="mi">3</span> <span class="mi">1</span> <span class="o">&lt;=</span> <span class="n">D</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">&lt;=</span> <span class="mi">10</span><span class="o">^</span><span class="mi">3</span> </pre></div> </div> </div> <div class="section" id="id3"> <h2><a class="toc-backref" href="#id7">分析</a><a class="headerlink" href="#id3" title="Permalink to this headline">¶</a></h2> <div class="admonition note"> <p class="first admonition-title">Note</p> <p class="last">多重背包轉零一背包</p> </div> <p>重量與價值是相同值,多重背包裸題。 須二進制拆解轉零一背包加速。</p> </div> <div class="section" id="ac-code"> <h2><a class="toc-backref" href="#id8">AC Code</a><a class="headerlink" href="#ac-code" title="Permalink to this headline">¶</a></h2> <div class="highlight-cpp"><table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45</pre></div></td><td class="code"><div class="highlight"><pre><span></span><span class="c1">// #include &lt;bits/stdc++.h&gt;</span> <span class="cp">#include</span> <span class="cpf">&lt;cstdio&gt;</span><span class="cp"></span> <span class="cp">#include</span> <span class="cpf">&lt;vector&gt;</span><span class="cp"></span> <span class="cp">#include</span> <span class="cpf">&lt;algorithm&gt;</span><span class="cp"></span> <span class="k">using</span> <span class="k">namespace</span> <span class="n">std</span><span class="p">;</span> <span class="k">typedef</span> <span class="kt">long</span> <span class="kt">long</span> <span class="n">ll</span><span class="p">;</span> <span class="k">struct</span> <span class="n">Item</span> <span class="p">{</span> <span class="n">ll</span> <span class="n">v</span><span class="p">,</span> <span class="n">w</span><span class="p">;</span> <span class="p">};</span> <span class="k">const</span> <span class="kt">int</span> <span class="n">MAX_W</span> <span class="o">=</span> <span class="mi">100000</span><span class="p">;</span> <span class="n">ll</span> <span class="n">dp</span><span class="p">[</span><span class="n">MAX_W</span> <span class="o">+</span> <span class="mi">1</span><span class="p">];</span> <span class="n">ll</span> <span class="nf">knapsack01</span><span class="p">(</span><span class="k">const</span> <span class="n">vector</span><span class="o">&lt;</span><span class="n">Item</span><span class="o">&gt;&amp;</span> <span class="n">items</span><span class="p">,</span> <span class="kt">int</span> <span class="n">W</span><span class="p">)</span> <span class="p">{</span> <span class="n">fill</span><span class="p">(</span><span class="n">dp</span><span class="p">,</span> <span class="n">dp</span> <span class="o">+</span> <span class="n">W</span> <span class="o">+</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">0ll</span><span class="p">);</span> <span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="kt">int</span><span class="p">(</span><span class="n">items</span><span class="p">.</span><span class="n">size</span><span class="p">());</span> <span class="n">i</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span> <span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">j</span> <span class="o">=</span> <span class="n">W</span><span class="p">;</span> <span class="n">j</span> <span class="o">&gt;=</span> <span class="n">items</span><span class="p">[</span><span class="n">i</span><span class="p">].</span><span class="n">w</span><span class="p">;</span> <span class="n">j</span><span class="o">--</span><span class="p">)</span> <span class="p">{</span> <span class="n">dp</span><span class="p">[</span><span class="n">j</span><span class="p">]</span> <span class="o">=</span> <span class="n">max</span><span class="p">(</span><span class="n">dp</span><span class="p">[</span><span class="n">j</span><span class="p">],</span> <span class="n">dp</span><span class="p">[</span><span class="n">j</span> <span class="o">-</span> <span class="n">items</span><span class="p">[</span><span class="n">i</span><span class="p">].</span><span class="n">w</span><span class="p">]</span> <span class="o">+</span> <span class="n">items</span><span class="p">[</span><span class="n">i</span><span class="p">].</span><span class="n">v</span><span class="p">);</span> <span class="p">}</span> <span class="p">}</span> <span class="k">return</span> <span class="n">dp</span><span class="p">[</span><span class="n">W</span><span class="p">];</span> <span class="p">}</span> <span class="kt">int</span> <span class="nf">main</span><span class="p">()</span> <span class="p">{</span> <span class="n">ll</span> <span class="n">W</span><span class="p">;</span> <span class="kt">int</span> <span class="n">N</span><span class="p">;</span> <span class="k">while</span> <span class="p">(</span><span class="n">scanf</span><span class="p">(</span><span class="s">&quot;%lld %d&quot;</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">W</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">N</span><span class="p">)</span> <span class="o">!=</span> <span class="n">EOF</span><span class="p">)</span> <span class="p">{</span> <span class="n">vector</span><span class="o">&lt;</span><span class="n">Item</span><span class="o">&gt;</span> <span class="n">items</span><span class="p">;</span> <span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="n">N</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span> <span class="n">ll</span> <span class="n">val</span><span class="p">,</span> <span class="n">num</span><span class="p">;</span> <span class="n">scanf</span><span class="p">(</span><span class="s">&quot;%lld %lld&quot;</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">num</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">val</span><span class="p">);</span> <span class="k">for</span> <span class="p">(</span><span class="n">ll</span> <span class="n">k</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span> <span class="n">k</span> <span class="o">&lt;=</span> <span class="n">num</span><span class="p">;</span> <span class="n">k</span> <span class="o">*=</span> <span class="mi">2</span><span class="p">)</span> <span class="p">{</span> <span class="n">items</span><span class="p">.</span><span class="n">push_back</span><span class="p">((</span><span class="n">Item</span><span class="p">)</span> <span class="p">{</span><span class="n">k</span> <span class="o">*</span> <span class="n">val</span><span class="p">,</span> <span class="n">k</span> <span class="o">*</span> <span class="n">val</span><span class="p">});</span> <span class="n">num</span> <span class="o">-=</span> <span class="n">k</span><span class="p">;</span> <span class="p">}</span> <span class="k">if</span> <span class="p">(</span><span class="n">num</span> <span class="o">&gt;</span> <span class="mi">0</span><span class="p">)</span> <span class="p">{</span> <span class="n">items</span><span class="p">.</span><span class="n">push_back</span><span class="p">((</span><span class="n">Item</span><span class="p">)</span> <span class="p">{</span><span class="n">num</span> <span class="o">*</span> <span class="n">val</span><span class="p">,</span> <span class="n">num</span> <span class="o">*</span> <span class="n">val</span><span class="p">});</span> <span class="p">}</span> <span class="p">}</span> <span class="n">printf</span><span class="p">(</span><span class="s">&quot;%lld</span><span class="se">\n</span><span class="s">&quot;</span><span class="p">,</span> <span class="n">knapsack01</span><span class="p">(</span><span class="n">items</span><span class="p">,</span> <span class="n">W</span><span class="p">));</span> <span class="p">}</span> <span class="k">return</span> <span class="mi">0</span><span class="p">;</span> <span class="p">}</span> </pre></div> </td></tr></table></div> </div> </div> </div> <div class="articleComments"> </div> </div> <footer> <div class="rst-footer-buttons" role="navigation" aria-label="footer navigation"> <a href="p1308.html" class="btn btn-neutral float-right" title="[POJ] 1308. Is It A Tree?" accesskey="n" rel="next">Next <span class="fa fa-arrow-circle-right"></span></a> <a href="p1151.html" class="btn btn-neutral" title="[POJ] 1151. Atlantis" accesskey="p" rel="prev"><span class="fa fa-arrow-circle-left"></span> Previous</a> </div> <hr/> <div role="contentinfo"> <p> &copy; Copyright 2016, amoshyc. </p> </div> Built with <a href="http://sphinx-doc.org/">Sphinx</a> using a <a href="https://github.com/snide/sphinx_rtd_theme">theme</a> provided by <a href="https://readthedocs.org">Read the Docs</a>. </footer> </div> </div> </section> </div> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT:'../', VERSION:'1.0', COLLAPSE_INDEX:false, FILE_SUFFIX:'.html', HAS_SOURCE: true, SOURCELINK_SUFFIX: '.txt' }; </script> <script type="text/javascript" src="../_static/jquery.js"></script> <script type="text/javascript" src="../_static/underscore.js"></script> <script type="text/javascript" src="../_static/doctools.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script> <script type="text/javascript" src="../_static/js/theme.js"></script> <script type="text/javascript"> jQuery(function () { SphinxRtdTheme.StickyNav.enable(); }); </script> </body> </html>
amoshyc/CPsolution
docs/poj/p1276.html
HTML
mit
21,542
class BeachApiCore::TeamUpdate include Interactor def call if context.team.update context.params context.status = :ok else context.status = :bad_request context.fail! message: context.team.errors.full_messages end end end
beachio/beach-api-core
app/interactors/beach_api_core/team_update.rb
Ruby
mit
259
#include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <sys/wait.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <signal.h> #include <errno.h> #include <sys/stat.h> #include <sys/mman.h> #include <fcntl.h> #include "server.h" #include "rio.h" int writeTo(int fd, char * string) { return write(fd, string, strlen(string)); } void err_dump(int fd, int status, char * err_msg) { char line[LINE_SIZE]; snprintf(line, LINE_SIZE, "HTTP/1.1 %d %s\r\n\r\n", status, err_msg); writeTo(fd, line); snprintf(line, LINE_SIZE, "ERROR: %d\r\n", status); writeTo(fd, line); snprintf(line, LINE_SIZE, "ERROR MESSAGE: %s\r\n\r\n", err_msg); writeTo(fd, line); } void sig_int(int signo) { exit(0); } void sig_child(int signo) { signal(SIGCHLD, sig_child); while (waitpid(-1, NULL, WNOHANG) > 0) ; } void initServer() { /* 忽略 sigpipe 信号 */ signal(SIGPIPE, SIG_IGN); signal(SIGINT, sig_int); signal(SIGCHLD, sig_child); } /* 打开监听 */ int open_listenfd(int port) { int sockfd, res; struct sockaddr_in addr; /* 创建socket */ sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) { fprintf(stderr, "socket error\n"); exit(1); } printf("创建socket成功\n"); /* 初始化地址 */ addr.sin_family = AF_INET; addr.sin_port = htons(PORT); addr.sin_addr.s_addr = htonl(INADDR_ANY); printf("初始化地址成功\n"); /* 绑定地址 */ res = bind(sockfd, (const struct sockaddr *)&addr, sizeof(addr)); if (res < 0) { fprintf(stderr, "bind error\n"); exit(1); } printf("绑定地址 %s:%d 成功\n", inet_ntoa(addr.sin_addr), PORT); /* 监听 */ res = listen(sockfd, 50); if (res < 0) { fprintf(stderr, "listen error\n"); exit(1); } printf("监听成功\n"); return sockfd; } void handleUri(int fd, const char * uri) { char whole_uri[URI_LEN] = DOCUMENT_ROOT; int ffd; /* 文件描述符 */ struct stat f_statue; char * buf; if (uri[0] == '/') { uri += 1; } strncat(whole_uri, uri, URI_LEN); if (stat(whole_uri, &f_statue) < 0) { err_dump(fd, 404, "Not Found"); return; } if (! S_ISREG(f_statue.st_mode)) { err_dump(fd, 403, "Not Regular File"); return; } if ((ffd = open(whole_uri, O_RDONLY)) < 0) { err_dump(fd, 403, "Forbidden"); return; } buf = (char *)mmap((void *)0, f_statue.st_size, PROT_READ, MAP_PRIVATE, ffd, 0); if (buf == MAP_FAILED) { err_dump(fd, 501, "Mmap Error"); return; } writeTo(fd, "HTTP/1.1 200 OK\r\n\r\n"); writeTo(fd, buf); } void doit(int fd) { char line[LINE_SIZE]; char method[10], uri[URI_LEN], version[10]; rio_t rio; rio_init(&rio, fd); if (rio_readline(&rio, line, LINE_SIZE) <= 0) { err_dump(fd, 400, "Bad Request"); return; } if (sscanf(line, "%s %s %s", method, uri, version) != 3) { err_dump(fd, 400, "Bad Request"); return; } while(rio_readline(&rio, line, LINE_SIZE) > 0) { if (strcmp(line, "\r\n") == 0) { break; } } if (strcmp(method, "GET") != 0) { err_dump(fd, 501, "No Method"); return; } handleUri(fd, uri); } int main() { int fd, sockfd, pid, num; socklen_t client_len; struct sockaddr_in client_addr; char * client_ip; initServer(); sockfd = open_listenfd(PORT); num = 0; /* 等待请求 */ while (1) { while ((fd = accept(sockfd, (struct sockaddr *)&client_addr, &client_len)) < 0) { if (errno != EINTR) { /* 不是被信号处理函数中断 */ fprintf(stderr, "accept error\n"); exit(1); } } ++num; client_ip = inet_ntoa(client_addr.sin_addr); printf("请求 %d: %s\n", num, client_ip); if ((pid = fork()) < 0) { fprintf(stderr, "fork error\n"); exit(1); } else if (pid == 0) { /* child */ close(sockfd); doit(fd); printf("结束 %d: %s\n", num, client_ip); exit(0); } close(fd); } return 0; }
cheniison/Experiment
OS/WebServer/server.c
C
mit
4,428
# -*- coding: utf-8 -*- def calc_note(count, value): qnt = 0 if count >= value: qnt = int(count) / value print '%d nota(s) de R$ %d.00' % (qnt, value) return count - qnt * value n = float(raw_input()) print 'NOTAS:' n = calc_note(n, 100) n = calc_note(n, 50) n = calc_note(n, 20) n = calc_note(n, 10) n = calc_note(n, 5) n = calc_note(n, 2) print 'MOEDAS:' print '%d moeda(s) de R$ 1.00' % int(n) n -= int(n) m50 = n / 0.50 print '%d moeda(s) de R$ 0.50' % m50 n -= int(m50) * 0.50 m25 = n / 0.25 print '%d moeda(s) de R$ 0.25' % m25 n -= int(m25) * 0.25 m10 = n / 0.10 print '%d moeda(s) de R$ 0.10' % m10 n -= int(m10) * 0.10 if round(n, 2) >= 0.05: print '1 moeda(s) de R$ 0.05' m1 = (n - 0.05) * 100 else: print '0 moeda(s) de R$ 0.05' m1 = round(n, 2) * 100 if round(m1, 0): print '%.0f moeda(s) de R$ 0.01' % m1 else: print '0 moeda(s) de R$ 0.01'
vicenteneto/online-judge-solutions
URI/1-Beginner/1021.py
Python
mit
907
## PostCSS 插件列表 [![npm version](https://img.shields.io/npm/v/postcss-plugins.svg)](https://www.npmjs.com/package/postcss-plugins) [![contributors](https://img.shields.io/github/contributors/himynameisdave/postcss-plugins.svg)](https://github.com/himynameisdave/postcss-plugins/blob/master/docs/authors.md) 开箱即用型"官方和非官方"综合[PostCSS](https://github.com/postcss/postcss) 插件 <img align="right" width="100" height="100" title="Philosopher’s stone, logo of PostCSS" src="http://postcss.github.io/postcss/logo.svg"> ### 目的 这里有 [超过数百人的优秀开发者](https://github.com/himynameisdave/postcss-plugins/blob/master/docs/authors.md) 正在构建令人惊叹的 PostCSS 插件。插件运行列表增长速度非常块,而且已经在很多地方投入使用了。通过 [**@mxstbr**](https://github.com/mxstbr) 构建的 [postcss.parts](http://postcss.parts) 可以搜索到。另一个是 [**@chrisopedia**](https://github.com/chrisopedia) 创建的 [PostCSS Alfred Workflow](https://github.com/chrisopedia/alfred-postcss-workflow)。对于开发者来说,这些是非常的好的资源用来查找和使用,而且这个列表会持续更新。 目的尽可能简洁明了但仍然会向开发者提供一些插件相关的数据 **简而言之** 这是一个包含大量 PostCSS 插件的源数据列表 ### 安装 **使用 yarn** ``` yarn add postcss-plugins ``` **使用 npm** ``` npm i postcss-plugins ``` ### 使用 ```javascript const plugins = require('postcss-plugins'); // 基本用法: 获取数据集里面的每个插件名 const namesOfEveryPlugin = plugins.map(plugin => plugin.name); // 基本用法: 获取star数最多的插件 const mostStarredPlugin = plugins.reduce((a, p) => a.stars && p.stars > a.stars ? p : a, { stars: 0 }); // 基本用法: 看看 himynameisdave 已经写了多少个插件 const himynameisdavesPlugins = plugins.reduce((a, p) => p.author === 'himynameisdave' ? ++a : a, 0) ``` ### 提交一个新的插件 欢迎所有插件,只要符合 [PostCSS Plugin Guidelines](https://github.com/postcss/postcss/blob/master/docs/guidelines/plugin.md) 的插件指南。 这些脚本可以让添加插件变得像回答一些关于它的问题一样简单。 **步骤**: 1. [Fork 这个仓库](https://github.com/himynameisdave/postcss-plugins#fork-destination-box). 1. 运行 `yarn install` / `npm install` 快速安装 [脚本](https://github.com/himynameisdave/postcss-plugins/tree/master/scripts) 所依赖的依赖项。 1. 运行 `yarn run add` / `npm run add`。 然后系统会提示你输入有关插件的信息,按照提示操作即可。 1. 然后将你的插件添加到 [`plugins.json`](https://github.com/himynameisdave/postcss-plugins/blob/master/plugins.json) 和 你的插件名 到 [`authors.md`](https://github.com/himynameisdave/postcss-plugins/blob/master/docs/authors.md) 列表中。 1. 提交并推送变更,然后提交 pull request. 1. [别着急](http://i.imgur.com/dZzkNc7.gif) **请注意** `plugins.json` 和 `authors.md` **都不要直接编辑**。 反而,请按照上面的步骤确保你的拉取请求能够及时合并。 同时, 不用操心 Github start 数量,因为这是维护人员定期完成的。 ### 更新日志 有关发布、更改和更新的列表,请参见[更新日志](https://github.com/himynameisdave/postcss-plugins/blob/master/CHANGELOG.md)。
himynameisdave/postcss-plugins
README-zh_CN.md
Markdown
mit
3,442
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.6.0_18) on Thu Dec 18 17:18:35 PST 2014 --> <title>Uses of Interface java.net.SocketImplFactory (Java Platform SE 7 )</title> <meta name="date" content="2014-12-18"> <link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Interface java.net.SocketImplFactory (Java Platform SE 7 )"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../java/net/SocketImplFactory.html" title="interface in java.net">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-files/index-1.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><em><strong>Java&trade;&nbsp;Platform<br>Standard&nbsp;Ed.&nbsp;7</strong></em></div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../index.html?java/net/class-use/SocketImplFactory.html" target="_top">Frames</a></li> <li><a href="SocketImplFactory.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Interface java.net.SocketImplFactory" class="title">Uses of Interface<br>java.net.SocketImplFactory</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../java/net/SocketImplFactory.html" title="interface in java.net">SocketImplFactory</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#java.net">java.net</a></td> <td class="colLast"> <div class="block">Provides the classes for implementing networking applications.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="java.net"> <!-- --> </a> <h3>Uses of <a href="../../../java/net/SocketImplFactory.html" title="interface in java.net">SocketImplFactory</a> in <a href="../../../java/net/package-summary.html">java.net</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../java/net/package-summary.html">java.net</a> with parameters of type <a href="../../../java/net/SocketImplFactory.html" title="interface in java.net">SocketImplFactory</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>static void</code></td> <td class="colLast"><span class="strong">ServerSocket.</span><code><strong><a href="../../../java/net/ServerSocket.html#setSocketFactory(java.net.SocketImplFactory)">setSocketFactory</a></strong>(<a href="../../../java/net/SocketImplFactory.html" title="interface in java.net">SocketImplFactory</a>&nbsp;fac)</code> <div class="block">Sets the server socket implementation factory for the application.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static void</code></td> <td class="colLast"><span class="strong">Socket.</span><code><strong><a href="../../../java/net/Socket.html#setSocketImplFactory(java.net.SocketImplFactory)">setSocketImplFactory</a></strong>(<a href="../../../java/net/SocketImplFactory.html" title="interface in java.net">SocketImplFactory</a>&nbsp;fac)</code> <div class="block">Sets the client socket implementation factory for the application.</div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../java/net/SocketImplFactory.html" title="interface in java.net">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-files/index-1.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><em><strong>Java&trade;&nbsp;Platform<br>Standard&nbsp;Ed.&nbsp;7</strong></em></div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../index.html?java/net/class-use/SocketImplFactory.html" target="_top">Frames</a></li> <li><a href="SocketImplFactory.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small><font size="-1"> <a href="http://bugreport.sun.com/bugreport/">Submit a bug or feature</a> <br>For further API reference and developer documentation, see <a href="http://docs.oracle.com/javase/7/docs/index.html" target="_blank">Java SE Documentation</a>. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.<br> <a href="../../../../legal/cpyr.html">Copyright</a> &#x00a9; 1993, 2015, Oracle and/or its affiliates. All rights reserved. </font></small></p> </body> </html>
fbiville/annotation-processing-ftw
doc/java/jdk7/java/net/class-use/SocketImplFactory.html
HTML
mit
7,301
'use strict'; module.exports = function (grunt) { var exec = require('child_process').exec; grunt.registerMultiTask('install-dependencies', 'Installs npm dependencies.', function () { var cb, options, cp; cb = this.async(); options = this.options({ cwd: '', stdout: true, stderr: true, failOnError: true, isDevelopment: false }); var cmd = "npm install"; if(!options.isDevelopment ) cmd += " -production"; cp = exec(cmd, {cwd: options.cwd}, function (err, stdout, stderr) { if (err && options.failOnError) { grunt.warn(err); } cb(); }); grunt.verbose.writeflags(options, 'Options'); if (options.stdout || grunt.option('verbose')) { console.log("Running npm install in: " + options.cwd); cp.stdout.pipe(process.stdout); } if (options.stderr || grunt.option('verbose')) { cp.stderr.pipe(process.stderr); } }); };
justhamade/grunt-install-dependencies
tasks/install-dependencies.js
JavaScript
mit
949
// Copyright slx7R4GDZM // Distributed under the terms of the MIT License. // Refer to the License.txt file for details. #pragma once #include "Common-Things.h" const string BRIGHTNESS_OPTIONS[] = { "BRIGHTNESS 15", "BRIGHTNESS 12", "BRIGHTNESS 7", "BRIGHTNESS 0" }; const string GLOBAL_SCALE_OPTIONS[] = { "GLOBAL SCALE (*2)", "GLOBAL SCALE (*1)", "GLOBAL SCALE (/2)", "GLOBAL SCALE (/4)" }; const string VCTR_OPTIONS[] = { "LOCAL SCALE UP", "LOCAL SCALE DOWN", "LOCAL SCALE (/512)", "LOCAL SCALE (*1)" }; const string LABS_OPTIONS[] = { "GLOBAL SCALE UP", "GLOBAL SCALE DOWN", "GLOBAL SCALE (*1)", "GLOBAL SCALE (/2)" }; const string SVEC_OPTIONS[] = { "LOCAL SCALE UP", "LOCAL SCALE DOWN", "LOCAL SCALE (*2)", "LOCAL SCALE (*16)" }; const string SHIP_CREATOR_OPTIONS[] = { "BRIGHTNESS UP", "BRIGHTNESS DOWN", "BRIGHTNESS 0", "BRIGHTNESS 12" }; ///////////////// const array<string, 5> MAIN_MENU_CHOICES = { "EDIT VECTOR OBJECT", "EDIT TEXT", "EDIT SHIP", "EDIT SHIP THRUST", "TOGGLE VECTORS" }; const array<string, 3> INSTRUCTION_MENU_CHOICES = { "DRAW LONG VECTOR", "LOAD ABSOLUTE", "DRAW SHORT VECTOR" }; const array<string, 5> VECTOR_OBJECT_MENU_CHOICES = { "ADD INSTRUCTION", "REMOVE INSTRUCTION", "SET GLOBAL SCALE", "OUTPUT VECTOR OBJECT", "CLEAR VECTOR OBJECT" }; const array<string, 4> SHIP_MENU_CHOICES = { "ADD INSTRUCTION", "REMOVE INSTRUCTION", "OUTPUT SHIP", "CLEAR SHIP" }; const array<string, 4> THRUST_MENU_CHOICES = { "ADD INSTRUCTION", "REMOVE INSTRUCTION", "OUTPUT SHIP THRUST", "CLEAR SHIP THRUST" }; const array<string, 3> TOGGLE_VECTORS_MENU_CHOICES = { "BOX", "VECTOR OBJECT", "SHIP AND THRUST" }; const string DEFAULT_SETTINGS = R"(# Lines starting with # are ignored by the program #============================================================================== # List of Available Keys #============================================================================== # Escape F1 F2 F3 F4 F5 F6 F7 F8 F9 F10 F11 F12 F13 F14 F15 Pause # Tilde Num1 Num2 Num3 Num4 Num5 Num6 Num7 Num8 Num9 Num0 Hyphen Equal # Tab Q W E R T Y U I O P LBracket RBracket Backslash Backspace # A S D F G H J K L Semicolon Quote Enter # LShift Z X C V B N M Comma Period Slash RShift # LControl LSystem LAlt Space RAlt RSystem Menu RControl # Insert Home PageUp Divide Multiply Subtract # Delete End PageDown Numpad7 Numpad8 Numpad9 Add # Numpad4 Numpad5 Numpad6 # Up Numpad1 Numpad2 Numpad3 # Left Down Right Numpad0 #============================================================================== # Button Settings #============================================================================== B-Confirm E B-Cancel F B-Up W B-Down S B-Left A B-Right D B-Options Q B-Toggle-Fullscreen F11 B-Exit Escape #============================================================================== # Window Settings #============================================================================== ## Which mode to start the window with # 0 = Normal window (default) # 1 = Borderless window # 2 = Exclusive fullscreen Starting-Window-Mode 0 ## Starting window resolution Starting-X-Resolution 1024 Starting-Y-Resolution 790 ## Starting position for the program window # -1 = Don't set the starting position (default) Start-Window-Position-X -1 Start-Window-Position-Y -1 ## What to do when the window isn't focused # 0 = Pause the program (default) # 1 = Run in background without input # 2 = Run in background with input Inactive-Mode 0 #============================================================================== # Graphics Settings #============================================================================== ## The x:y ratio to crop the image to # < 1 = Crops the image starting with the left and right sides # 1.0 = Scales the image to the lower resolution axis # > 1 = Crops the image starting with the top and bottom (default) Crop-Ratio 1.2962025 ## MSAA toggle and quality setting # 0 = Off # 1 = 2x # 2 = 4x # 3 = 8x (default) MSAA-Quality 3 ## Gamma correction Gamma-Correction 1.0 ## Vertical synchronization # 0 = Disabled (default) # 1 = Enabled V-Sync-Enabled 0 ## Whether to use busy waiting or sleeping to limit FPS # 0 = Use sleeping (default) # 1 = Use busy waiting; this has high CPU usage, but it's consistent Frame-Limit-Mode 0 )";
slx7R4GDZM/Sine-Toolkit
Source/Other/Text.h
C
mit
4,630
<?php ini_set('display_errors', 1); ini_set('error_reporting', -1); $loader = require __DIR__ . '/../vendor/autoload.php'; $loader->add('ThisPageCannotBeFound', __DIR__);
thispagecannotbefound/php-signals
tests/bootstrap.php
PHP
mit
173