code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
/*************************************************************************** * Project file: NPlugins - NTalk - TimedFilter.java * * Full Class name: fr.ribesg.bukkit.ntalk.filter.bean.TimedFilter * * * * Copyright (c) 2012-2015 Ribesg - www.ribesg.fr * * This file is under GPLv3 -> http://www.gnu.org/licenses/gpl-3.0.txt * * Please contact me at ribesg[at]yahoo.fr if you improve this file! * ***************************************************************************/ package fr.ribesg.bukkit.ntalk.filter.bean; import fr.ribesg.bukkit.ntalk.filter.ChatFilterResult; import java.util.Map; /** * @author Ribesg */ public abstract class TimedFilter extends Filter { private final long duration; protected TimedFilter(final String outputString, final String filteredString, final boolean regex, final ChatFilterResult responseType, final long duration) { super(outputString, filteredString, regex, responseType); this.duration = duration; } public long getDuration() { return this.duration; } // ############ // // ## Saving ## // // ############ // @Override public Map<String, Object> getConfigMap() { final Map<String, Object> map = super.getConfigMap(); map.put("duration", this.duration); return map; } }
Ribesg/NPlugins
NTalk/src/main/java/fr/ribesg/bukkit/ntalk/filter/bean/TimedFilter.java
Java
gpl-3.0
1,459
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package net.projectzombie.regionrotation.modules; import com.sk89q.worldguard.bukkit.WGBukkit; import com.sk89q.worldedit.LocalWorld; import com.sk89q.worldguard.protection.managers.RegionManager; import org.bukkit.Bukkit; import org.bukkit.World; import java.util.UUID; /** * Parent class for modules to store their world and respective WorldGuard * region manager. * * @author Jesse Bannon (jmbannon@uw.edu) */ public abstract class RegionWorld { private final UUID worldUID; private final boolean isValid; protected RegionWorld(final UUID worldUID) { this.worldUID = worldUID; this.isValid = this.getWorld() != null && getRegionManager() != null; } /** @return Whether the object is valid for use or not. */ protected boolean isValid() { return this.isValid; } protected UUID getWorldUID() { return this.worldUID; } protected World getWorld() { return Bukkit.getWorld(worldUID); } protected LocalWorld getLocalWorld() { return com.sk89q.worldedit.bukkit.BukkitUtil.getLocalWorld(this.getWorld()); } protected RegionManager getRegionManager() { return WGBukkit.getRegionManager(getWorld()); } }
jmbannon/RegionRotation
src/main/java/net/projectzombie/regionrotation/modules/RegionWorld.java
Java
gpl-3.0
1,404
package com.plutomc.power.common.blocks; import com.plutomc.core.common.blocks.BlockMetal; import com.plutomc.power.Power; import com.plutomc.power.common.tileentities.TileEntityCombustionEngine; import com.plutomc.power.init.BlockRegistry; import com.plutomc.power.init.GuiHandler; import net.minecraft.block.ITileEntityProvider; import net.minecraft.block.properties.PropertyDirection; import net.minecraft.block.state.BlockStateContainer; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.InventoryHelper; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import javax.annotation.Nonnull; import javax.annotation.Nullable; /** * plutomc_power * Copyright (C) 2016 Kevin Boxhoorn * * plutomc_power is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * plutomc_power is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with plutomc_power. If not, see <http://www.gnu.org/licenses/>. */ public class BlockCombustionEngine extends BlockMetal implements ITileEntityProvider { public static final PropertyDirection FACING = PropertyDirection.create("facing", EnumFacing.Plane.HORIZONTAL); public BlockCombustionEngine() { super(BlockRegistry.Data.COMBUSTION_ENGINE); setDefaultState(blockState.getBaseState().withProperty(FACING, EnumFacing.NORTH)); } @Nonnull @Override protected BlockStateContainer createBlockState() { return new BlockStateContainer(this, FACING); } @Nonnull @Override public IBlockState getStateForPlacement(World world, BlockPos pos, EnumFacing facing, float hitX, float hitY, float hitZ, int meta, EntityLivingBase placer, EnumHand hand) { return getDefaultState().withProperty(FACING, placer.getHorizontalFacing().getOpposite()); } @Nonnull @Override public IBlockState getStateFromMeta(int meta) { return getDefaultState().withProperty(FACING, EnumFacing.getFront(meta)); } @Override public int getMetaFromState(IBlockState state) { return state.getValue(FACING).getIndex(); } @Nullable @Override public TileEntity createNewTileEntity(World worldIn, int meta) { return new TileEntityCombustionEngine(); } @Override public void breakBlock(World worldIn, BlockPos pos, IBlockState state) { TileEntity tileEntity = worldIn.getTileEntity(pos); if (tileEntity instanceof TileEntityCombustionEngine) { InventoryHelper.dropInventoryItems(worldIn, pos, (TileEntityCombustionEngine) tileEntity); worldIn.updateComparatorOutputLevel(pos, this); } super.breakBlock(worldIn, pos, state); } @Override public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) { if (!worldIn.isRemote) { playerIn.openGui(Power.instance(), GuiHandler.ENGINE_COMBUSTION, worldIn, pos.getX(), pos.getY(), pos.getZ()); } return true; } @Override public void onBlockPlacedBy(World worldIn, BlockPos pos, IBlockState state, EntityLivingBase placer, ItemStack stack) { TileEntity tileEntity = worldIn.getTileEntity(pos); if (tileEntity instanceof TileEntityCombustionEngine) { ((TileEntityCombustionEngine) tileEntity).setCustomName(stack.getDisplayName()); } } }
plutomc/power
src/main/java/com/plutomc/power/common/blocks/BlockCombustionEngine.java
Java
gpl-3.0
3,925
<?php /** * @author YIThemes * @package WooCommerce/Templates * @version 1.6.4 */ global $post; echo '<div class="options_group">'; // Active custom onsale $active = get_post_meta($post->ID, '_active_custom_onsale', true); woocommerce_wp_checkbox( array( 'id' => '_active_custom_onsale', 'label' => __('Active custom onsale icon', 'yit'), 'cbvalue' => 'yes', 'value' => $active ) ); // Choose a preset $field = array( 'id' => '_preset_onsale_icon', 'label' => __('Choose a preset', 'yit') ); $preset = get_post_meta($post->ID, $field['id'], true); ?> <p class="form-field <?php echo $field['id'] ?>_field"> <b><?php echo $field['label'] ?></b><br /> <label for="<?php echo $field['id'] ?>_onsale">On Sale!<input type="radio" name="<?php echo $field['id'] ?>" id="<?php echo $field['id'] ?>_onsale" value="onsale"<?php checked($preset, 'onsale'); ?> /></label><br /> <label for="<?php echo $field['id'] ?>_50">-50%<input type="radio" name="<?php echo $field['id'] ?>" id="<?php echo $field['id'] ?>_50" value="-50%"<?php checked($preset, '-50%'); ?> /></label><br /> <label for="<?php echo $field['id'] ?>_25">-25%<input type="radio" name="<?php echo $field['id'] ?>" id="<?php echo $field['id'] ?>_25" value="-25%"<?php checked($preset, '-25%'); ?> /></label><br /> <label for="<?php echo $field['id'] ?>_10">-10%<input type="radio" name="<?php echo $field['id'] ?>" id="<?php echo $field['id'] ?>_10" value="-10%"<?php checked($preset, '-10%'); ?> /></label><br /> <label for="<?php echo $field['id'] ?>_custom"><?php _e( 'Custom', 'yit' ) ?><input type="radio" name="<?php echo $field['id'] ?>" id="<?php echo $field['id'] ?>_custom" value="custom"<?php checked($preset, 'custom'); ?> /></label><br /> <small><?php _e( '(if you have choosen "Custom", upload your image in the option below, suggested size: 75x75px)', 'yit' ) ?></small> </p> <?php // Upload custom onsale icon $field = array( 'id' => '_custom_onsale_icon', 'label' => __('Custom onsale icon URL', 'yit') ); $file_path = get_post_meta($post->ID, $field['id'], true); echo '<p class="form-field"><label for="'.$field['id'].'">'.$field['label'].':</label> <input type="text" class="short custom_onsale" name="'.$field['id'].'" id="'.$field['id'].'" value="'.$file_path.'" placeholder="'.__('File path/URL', 'yit').'" /> <input type="button" class="upload_custom_onsale button" value="' . __( 'Choose a file', 'yit' ) . '" title="' . __( 'Upload', 'yit' ) . '" data-choose="' . __( 'Choose a file', 'woocommerce' ) . '" data-update="' . __( 'Insert file URL', 'woocommerce' ) . '" value="' . __( 'Choose a file', 'woocommerce' ) . '" /> </p>'; do_action('woocommerce_product_options_custom_onsale'); echo '</div>'; ?> <script type="text/javascript"> jQuery( function($){ var downloadable_file_frame; jQuery(document).on( 'click', '.upload_custom_onsale', function( event ){ var $el = $(this); var $file_path_field = $el.parent().find('.custom_onsale'); var file_paths = $file_path_field.val(); event.preventDefault(); // If the media frame already exists, reopen it. if ( downloadable_file_frame ) { downloadable_file_frame.open(); return; } var downloadable_file_states = [ // Main states. new wp.media.controller.Library({ library: wp.media.query(), multiple: false, title: $el.data('choose'), priority: 20, filterable: 'uploaded', }) ]; // Create the media frame. downloadable_file_frame = wp.media.frames.downloadable_file = wp.media({ // Set the title of the modal. title: $el.data('choose'), library: { type: '' }, button: { text: $el.data('update'), }, multiple: true, states: downloadable_file_states, }); // When an image is selected, run a callback. downloadable_file_frame.on( 'select', function() { var selection = downloadable_file_frame.state().get('selection'); selection.map( function( attachment ) { attachment = attachment.toJSON(); if ( attachment.url ) file_paths = file_paths ? file_paths + "\n" + attachment.url : attachment.url } ); $file_path_field.val( file_paths ); }); // Set post to 0 and set our custom type downloadable_file_frame.on( 'ready', function() { downloadable_file_frame.uploader.options.uploader.params = { type: 'downloadable_product' }; }); // Finally, open the modal. downloadable_file_frame.open(); }); }); </script>
zgomotos/Bazar
woocommerce/admin/custom-onsale.php
PHP
gpl-3.0
4,599
package nl.jappieklooster; import java.util.logging.ConsoleHandler; import java.util.logging.Level; import java.util.logging.Logger; /** * Wraps arround the java.util.logging.Logger, just to save some typing time. & it makes all the * loging go trough here so sutting it down is easy * * @author jappie */ public class Log { private static final Logger LOGGER = Logger.getLogger("Logger"); private static final Level LOG_LEVEL = Level.FINER; static { LOGGER.setLevel(LOG_LEVEL); ConsoleHandler handler = new ConsoleHandler(); // PUBLISH this level handler.setLevel(LOG_LEVEL); LOGGER.addHandler(handler); } // no initilization of this class allowed private Log() { } private static void write(Level severity, String message, Object... params) { LOGGER.log(severity, message, params); } private static void write(Level severity, String message) { LOGGER.log(severity, message); } private static void write(String message) { write(Level.INFO, message); } public static void debug(String message) { write(Level.FINER, message); } public static void verbose(String message) { write(Level.FINEST, message); } public static void write(String message, Object... params) { write(Level.INFO, message, params); } public static void debug(String message, Object... params) { write(Level.FINER, message, params); } public static void verbose(String message, Object... params) { write(Level.FINEST, message, params); } public static void panic(String message, Object... params) { write(Level.SEVERE, message, params); } public static void panic(String message) { write(Level.SEVERE, message); } public static void warn(String message, Object... params) { write(Level.WARNING, message, params); } public static void warn(String message) { write(Level.WARNING, message); } }
jappeace/hw-isad2gp-groovy
src/nl/jappieklooster/Log.java
Java
gpl-3.0
1,848
#ifndef SHRIMPS_EVENT_GENERATOR_BASE_H #define SHRIMPS_EVENT_GENERATOR_BASE_H #include "SHRiMPS/Eikonals/Omega_ik.H" namespace SHRIMPS { class Event_Generator_Base { protected: Omega_ik * p_eikonal; double m_smin; public: Event_Generator_Base(): p_eikonal(NULL),m_smin(0.) {} ~Event_Generator_Base() {}; virtual Omega_ik * GetEikonal() const { return p_eikonal;} virtual double Smin() const { return m_smin;} virtual bool IsLastRescatter() const { return false; } virtual double TMax() const { return 0.; } virtual int NLadders() const { return 1; } }; } #endif
cms-externals/sherpa
SHRiMPS/Event_Generation/Event_Generator_Base.H
C++
gpl-3.0
630
/** * JSONDB - JSON Database Manager * * Manage JSON files as databases with JSONDB Query Language (JQL) * * This content is released under the GPL License (GPL-3.0) * * Copyright (c) 2016, Centers Technologies * * @package JSONDB * @author Nana Axel * @copyright Copyright (c) 2016, Centers Technologies * @license http://spdx.org/licenses/GPL-3.0 GPL License * @filesource */ /** * Class Cache * * @package Database * @subpackage Utilities * @category Cache * @author Nana Axel */ var Cache = (function () { function Cache() { } /** * Cache array * @access private * @static {object} */ Cache.cache = {}; /** * Gets cached data * @param {object|string} path The path to the table * @return {object|*} */ Cache.prototype.get = function (path) { if (typeof path === "object") { var results = []; for (var id in path) { results.push(this.get(id)); } return results; } if (!Cache.cache.hasOwnProperty(path)) { var Util = new (require('./Util'))(); Cache.cache[path] = Util.getTableData(path); } return Cache.cache[path]; }; /** * Updates the cached data for a table * @param {string} path The path to the table * @param {object|null} data The data to cache * @return {object} */ Cache.prototype.update = function (path, data) { data = data || null; if (null !== data) { Cache.cache[path] = data; } else { var Util = new (require('./Util'))(); Cache.cache[path] = Util.getTableData(path); } }; /** * Resets the cache * @return Cache */ Cache.prototype.reset = function () { Cache.cache = {}; return this; }; return Cache; })(); // Exports the module module.exports = new Cache();
na2axl/jsondb-js
src/Cache.js
JavaScript
gpl-3.0
1,980
# Cucumber no longer supplies this file. It is here until we figure out if we should get rid of it or keep it # TL;DR: YOU SHOULD DELETE THIS FILE # # This file was generated by Cucumber-Rails and is only here to get you a head start # These step definitions are thin wrappers around the Capybara/Webrat API that lets you # visit pages, interact with widgets and make assertions about page content. # # If you use these step definitions as basis for your features you will quickly end up # with features that are: # # * Hard to maintain # * Verbose to read # # A much better approach is to write your own higher level step definitions, following # the advice in the following blog posts: # # * http://benmabey.com/2008/05/19/imperative-vs-declarative-scenarios-in-user-stories.html # * http://dannorth.net/2011/01/31/whose-domain-is-it-anyway/ # * http://elabs.se/blog/15-you-re-cuking-it-wrong # require 'uri' require 'cgi' require File.expand_path(File.join(File.dirname(__FILE__), "..", "support", "paths")) require File.expand_path(File.join(File.dirname(__FILE__), "..", "support", "selectors")) module WithinHelpers def with_scope(locator) locator ? within(*selector_for(locator)) { yield } : yield end end World(WithinHelpers) # Single-line step scoper When /^(.*) within (.*[^:])$/ do |_step, parent| with_scope(parent) { step _step } end # Multi-line step scoper When /^(.*) within (.*[^:]):$/ do |_step, parent, table_or_string| with_scope(parent) { step "#{_step}:", table_or_string } end Given /^(?:|I )am on (.+)$/ do |page_name| visit path_to(page_name) end When /^(?:|I )go to (.+)$/ do |page_name| visit path_to(page_name) end When /^(?:|I )press "([^"]*)"$/ do |button| click_button(button) end When /^(?:|I )follow "([^"]*)"$/ do |link| click_link(link) end When /^(?:|I )fill in "([^"]*)" with "([^"]*)"$/ do |field, value| fill_in(field, :with => value) end When /^(?:|I )fill in "([^"]*)" for "([^"]*)"$/ do |value, field| fill_in(field, :with => value) end # Use this to fill in an entire form with data from a table. Example: # # When I fill in the following: # | Account Number | 5002 | # | Expiry date | 2009-11-01 | # | Note | Nice guy | # | Wants Email? | | # # TODO: Add support for checkbox, select or option # based on naming conventions. # When /^(?:|I )fill in the following:$/ do |fields| fields.rows_hash.each do |name, value| step %{I fill in "#{name}" with "#{value}"} end end When /^(?:|I )select "([^"]*)" from "([^"]*)"$/ do |value, field| select(value, :from => field) end When /^I select blank from "([^"]*)"/ do |field| select("", :from => field) end When /^(?:|I )check "([^"]*)"$/ do |field| check(field) end When /^(?:|I )uncheck "([^"]*)"$/ do |field| uncheck(field) end When /^(?:|I )choose "([^"]*)"$/ do |field| choose(field) end When /^(?:|I )attach the file "([^"]*)" to "([^"]*)"$/ do |path, field| attach_file(field, File.expand_path(path)) end Then /^(?:|I )should see "([^"]*)"$/ do |text| if page.respond_to? :should page.should have_content(text) else assert page.has_content?(text) end end Then /^(?:|I )should see \/([^\/]*)\/$/ do |regexp| regexp = Regexp.new(regexp) if page.respond_to? :should page.should have_xpath('//*', :text => regexp) else assert page.has_xpath?('//*', :text => regexp) end end Then /^(?:|I )should not see "([^"]*)"$/ do |text| if page.respond_to? :should page.should have_no_content(text) else assert page.has_no_content?(text) end end Then /^(?:|I )should not see \/([^\/]*)\/$/ do |regexp| regexp = Regexp.new(regexp) if page.respond_to? :should page.should have_no_xpath('//*', :text => regexp) else assert page.has_no_xpath?('//*', :text => regexp) end end Then /^the "([^"]*)" field(?: within (.*))? should contain "([^"]*)"$/ do |field, parent, expected_value| with_scope(parent) do field = find_field(field) field_value = (field.tag_name == 'textarea') ? field.text : field.value if expected_value.blank? field_value.should be_blank else field_value.should =~ /#{expected_value}/ end end end Then /^the "([^"]*)" field(?: within (.*))? should not contain "([^"]*)"$/ do |field, parent, value| with_scope(parent) do field = find_field(field) field_value = (field.tag_name == 'textarea') ? field.text : field.value if field_value.respond_to? :should_not field_value.should_not =~ /#{value}/ else assert_no_match(/#{value}/, field_value) end end end Then /^the "([^"]*)" field should have the error "([^"]*)"$/ do |field, error_message| element = find_field(field) classes = element.find(:xpath, '..')[:class].split(' ') form_for_input = element.find(:xpath, 'ancestor::form[1]') using_formtastic = form_for_input[:class].include?('formtastic') error_class = using_formtastic ? 'error' : 'field_with_errors' if classes.respond_to? :should classes.should include(error_class) else assert classes.include?(error_class) end if page.respond_to?(:should) if using_formtastic error_paragraph = element.find(:xpath, '../*[@class="inline-errors"][1]') error_paragraph.should have_content(error_message) else page.should have_content("#{field.titlecase} #{error_message}") end else if using_formtastic error_paragraph = element.find(:xpath, '../*[@class="inline-errors"][1]') assert error_paragraph.has_content?(error_message) else assert page.has_content?("#{field.titlecase} #{error_message}") end end end Then /^the "([^"]*)" field should have no error$/ do |field| element = find_field(field) classes = element.find(:xpath, '..')[:class].split(' ') if classes.respond_to? :should classes.should_not include('field_with_errors') classes.should_not include('error') else assert !classes.include?('field_with_errors') assert !classes.include?('error') end end Then /^the "([^"]*)" checkbox(?: within (.*))? should be checked$/ do |label, parent| with_scope(parent) do field_checked = find_field(label)['checked'] if field_checked.respond_to? :should field_checked.should be_true else assert field_checked end end end Then /^the "([^"]*)" checkbox(?: within (.*))? should not be checked$/ do |label, parent| with_scope(parent) do field_checked = find_field(label)['checked'] if field_checked.respond_to? :should field_checked.should be_false else assert !field_checked end end end Then /^(?:|I )should be on (.+)$/ do |page_name| current_path = URI.parse(current_url).path if current_path.respond_to? :should current_path.should == path_to(page_name) else assert_equal path_to(page_name), current_path end end Then /^(?:|I )should have the following query string:$/ do |expected_pairs| query = URI.parse(current_url).query actual_params = query ? CGI.parse(query) : {} expected_params = {} expected_pairs.rows_hash.each_pair{|k,v| expected_params[k] = v.split(',')} if actual_params.respond_to? :should actual_params.should == expected_params else assert_equal expected_params, actual_params end end Then /^show me the page$/ do save_and_open_page end
IntersectAustralia/anznn
features/step_definitions/web_steps.rb
Ruby
gpl-3.0
7,327
import com.google.common.collect.MapDifference; import com.google.common.collect.Maps; import com.google.common.reflect.TypeToken; import com.google.gson.*; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.xml.DomDriver; import edu.pitt.isg.Converter; import edu.pitt.isg.dc.TestConvertDatsToJava; import edu.pitt.isg.dc.WebApplication; import edu.pitt.isg.dc.entry.Entry; import edu.pitt.isg.dc.entry.EntryService; import edu.pitt.isg.dc.entry.classes.EntryView; import edu.pitt.isg.dc.entry.classes.IsAboutItems; import edu.pitt.isg.dc.entry.classes.PersonOrganization; import edu.pitt.isg.dc.repository.utils.ApiUtil; import edu.pitt.isg.dc.utils.DatasetFactory; import edu.pitt.isg.dc.utils.DatasetFactoryPerfectTest; import edu.pitt.isg.dc.utils.ReflectionFactory; import edu.pitt.isg.dc.validator.*; import edu.pitt.isg.mdc.dats2_2.Dataset; import edu.pitt.isg.mdc.dats2_2.PersonComprisedEntity; import edu.pitt.isg.mdc.dats2_2.Type; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.web.WebAppConfiguration; import java.util.*; import static edu.pitt.isg.dc.validator.ValidatorHelperMethods.validatorErrors; import static org.junit.Assert.*; @RunWith(SpringRunner.class) @WebAppConfiguration @ContextConfiguration(classes = {WebApplication.class}) @TestPropertySource("/application.properties") public class DatasetValidatorTest { public static final java.lang.reflect.Type mapType = new TypeToken<TreeMap<String, Object>>() { }.getType(); private final Converter converter = new Converter(); Gson gson = new GsonBuilder().serializeNulls().enableComplexMapKeySerialization().create(); @Autowired private ApiUtil apiUtil; @Autowired private EntryService repo; private WebFlowReflectionValidator webFlowReflectionValidator = new WebFlowReflectionValidator(); @Test public void testEmptyDataset() { Dataset dataset = new Dataset(); } private Dataset createTestDataset(Long entryId) { Entry entry = apiUtil.getEntryByIdIncludeNonPublic(entryId); EntryView entryView = new EntryView(entry); Dataset dataset = (Dataset) converter.fromJson(entryView.getUnescapedEntryJsonString(), Dataset.class); DatasetFactory datasetFactory = new DatasetFactory(true); dataset = datasetFactory.createDatasetForWebFlow(dataset); // Dataset dataset = (Dataset) ReflectionFactory.create(Dataset.class); //make your dataset here return dataset; } private Dataset createPerfectDataset() { return DatasetFactoryPerfectTest.createDatasetForWebFlow(null); } private List<ValidatorError> test(Dataset dataset) { //don't have to do this yet String breadcrumb = ""; List<ValidatorError> errors = new ArrayList<>(); try { ReflectionValidator reflectionValidator = new ReflectionValidator(); reflectionValidator.validate(Dataset.class, dataset, true, breadcrumb, null, errors); //somehow "expect" error messages.... } catch (Exception e) { e.printStackTrace(); fail(); } return validatorErrors(errors); } @Test public void testPerfectDatasetWithAllPossibleFields() { Dataset dataset = createPerfectDataset(); List<ValidatorError> errors = test(dataset); assertTrue(errors.isEmpty()); } @Test public void testPerfectDatasetForceErrors() { Dataset dataset = createPerfectDataset(); dataset.setTitle(null); ListIterator<? extends Type> iterator = dataset.getTypes().listIterator(); while (iterator.hasNext()) { iterator.next(); iterator.remove(); } dataset.getStoredIn().setName(null); ((PersonOrganization) dataset.getCreators().get(1)).setName(null); dataset.getDistributions().get(0).getAccess().setLandingPage(null); dataset.getDistributions().get(0).getDates().get(0).getType().setValue(null); dataset.getDistributions().get(0).getDates().get(0).getType().setValueIRI(null); dataset.getDistributions().get(0).getConformsTo().get(0).getType().setValue(null); dataset.getDistributions().get(0).getConformsTo().get(0).getType().setValueIRI(null); dataset.getLicenses().get(0).setName(null); ((PersonOrganization) dataset.getCreators().get(0)).getAffiliations().get(0).getLocation().getIdentifier().setIdentifierSource(null); dataset.getPrimaryPublications().get(0).getAcknowledges().get(0).setName(null); DatasetFactory datasetFactory = new DatasetFactory(true); dataset.getPrimaryPublications().get(0).getAcknowledges().get(0).setFunders(datasetFactory.createPersonComprisedEntityList(null)); ((IsAboutItems) dataset.getIsAbout().get(0)).setName(null); dataset.getProducedBy().setName(null); dataset.getProducedBy().getEndDate().setDate(null); List<ValidatorError> errors = test(dataset); if (!errors.isEmpty()) { assertEquals(errors.get(0).getPath(), "(root)->title"); assertEquals(errors.get(0).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD); assertEquals(errors.get(1).getPath(), "(root)->types"); assertEquals(errors.get(1).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD); assertEquals(errors.get(2).getPath(), "(root)->creators->0->affiliations->0->location->identifier->identifierSource"); assertEquals(errors.get(2).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD); assertEquals(errors.get(3).getPath(), "(root)->creators->1->name"); assertEquals(errors.get(3).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD); assertEquals(errors.get(4).getPath(), "(root)->storedIn->name"); assertEquals(errors.get(4).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD); assertEquals(errors.get(5).getPath(), "(root)->distributions->0->access->landingPage"); assertEquals(errors.get(5).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD); assertEquals(errors.get(6).getPath(), "(root)->distributions->0->dates->0->type"); assertEquals(errors.get(6).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD); assertEquals(errors.get(7).getPath(), "(root)->distributions->0->conformsTo->0->type"); assertEquals(errors.get(7).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD); assertEquals(errors.get(8).getPath(), "(root)->primaryPublications->0->acknowledges->0->name"); assertEquals(errors.get(8).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD); assertEquals(errors.get(9).getPath(), "(root)->primaryPublications->0->acknowledges->0->funders"); assertEquals(errors.get(9).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD); assertEquals(errors.get(10).getPath(), "(root)->producedBy->name"); assertEquals(errors.get(10).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD); assertEquals(errors.get(11).getPath(), "(root)->producedBy->endDate->date"); assertEquals(errors.get(11).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD); assertEquals(errors.get(12).getPath(), "(root)->licenses->0->name"); assertEquals(errors.get(12).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD); assertEquals(errors.get(13).getPath(), "(root)->isAbout->0->name"); assertEquals(errors.get(13).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD); } else fail("No error messages produced."); } /* @Test public void testDatasetWithoutTitleOnly() throws Exception { // Dataset dataset = createTestDataset(566L); Dataset dataset = createPerfectDataset(); dataset.setTitle(null); List<ValidatorError> errors = test(dataset); if(!errors.isEmpty()) { assertEquals(errors.get(0).getPath(), "(root)->title"); assertEquals(errors.get(0).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD); } else fail("No error messages produced for missing Title"); } @Test public void testDatasetCreatorOrganizationNameMissing() { Dataset dataset = createPerfectDataset(); ((PersonOrganization) dataset.getCreators().get(1)).setName(null); List<ValidatorError> errors = test(dataset); if(!errors.isEmpty()) { assertEquals(errors.get(0).getPath(), "(root)->creators->name"); assertEquals(errors.get(0).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD); } else fail("No error messages produced for missing Creator Organization name."); } */ @Test public void testDatasetWithoutCreatorsOnly() { Dataset dataset = createPerfectDataset(); ListIterator<? extends PersonComprisedEntity> iterator = dataset.getCreators().listIterator(); while (iterator.hasNext()) { iterator.next(); iterator.remove(); } List<ValidatorError> errors = test(dataset); if (!errors.isEmpty()) { assertEquals(errors.get(0).getPath(), "(root)->creators"); assertEquals(errors.get(0).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD); } else fail("No error messages produced for missing Creators"); } /* @Test public void testDatasetWithoutTyesOnly() { Dataset dataset = createPerfectDataset(); ListIterator<? extends Type> iterator = dataset.getTypes().listIterator(); while (iterator.hasNext()) { Type type = iterator.next(); iterator.remove(); } List<ValidatorError> errors = test(dataset); if(!errors.isEmpty()) { assertEquals(errors.get(0).getPath(), "(root)->types"); assertEquals(errors.get(0).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD); } else fail("No error messages produced for missing Types"); } @Test public void testDatasetWithoutStoredInName() { Dataset dataset = createPerfectDataset(); dataset.getStoredIn().setName(null); List<ValidatorError> errors = test(dataset); if(!errors.isEmpty()) { assertEquals(errors.get(0).getPath(), "(root)->storedIn->name"); assertEquals(errors.get(0).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD); } else fail("No error messages produced for missing StoredIn (Data Repository) name."); } */ @Test public void testDatasetWithoutDistributionAccess() { Dataset dataset = createPerfectDataset(); dataset.getDistributions().get(0).setAccess(null); List<ValidatorError> errors = test(dataset); if (!errors.isEmpty()) { assertEquals(errors.get(0).getPath(), "(root)->distributions->0->access"); assertEquals(errors.get(0).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD); } else fail("No error messages produced for empty Distribution Access."); } /* @Test public void testDatasetWithoutDistributionAccessLandingPage() { Dataset dataset = createPerfectDataset(); dataset.getDistributions().get(0).getAccess().setLandingPage(null); List<ValidatorError> errors = test(dataset); if(!errors.isEmpty()) { assertEquals(errors.get(0).getPath(), "(root)->distributions->access->landingPage"); assertEquals(errors.get(0).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD); } else fail("No error messages produced for empty Distribution Access LandingPage."); } @Test public void testPerfectDatasetExceptLicenseIsMissingName() { Dataset dataset = createPerfectDataset(); dataset.getLicenses().get(0).setName(null); List<ValidatorError> errors = test(dataset); if(!errors.isEmpty()) { assertEquals(errors.get(0).getPath(), "(root)->licenses->name"); assertEquals(errors.get(0).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD); } else fail("No error messages produced for empty License name."); } @Test public void testDatasetWithoutIdentifierSource() { Dataset dataset = createPerfectDataset(); ((PersonOrganization) dataset.getCreators().get(0)).getAffiliations().get(0).getLocation().getIdentifier().setIdentifierSource(null); List<ValidatorError> errors = test(dataset); if(!errors.isEmpty()) { assertEquals(errors.get(0).getPath(), "(root)->creators->affiliations->location->identifier->identifierSource"); assertEquals(errors.get(0).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD); } else fail("No error messages produced for missing IdenfifierSource"); } @Test public void testDatasetWithoutDatesAnnotation() { Dataset dataset = createPerfectDataset(); dataset.getDistributions().get(0).getDates().get(0).getType().setValue(null); dataset.getDistributions().get(0).getDates().get(0).getType().setValueIRI(null); List<ValidatorError> errors = test(dataset); if(!errors.isEmpty()) { assertEquals(errors.get(0).getPath(), "(root)->distributions->dates->type"); assertEquals(errors.get(0).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD); } else fail("No error messages produced for missing Types"); } @Test public void testDatasetWithoutPrimaryPublicationsAcknowledgesName() { Dataset dataset = createPerfectDataset(); dataset.getPrimaryPublications().get(0).getAcknowledges().get(0).setName(null); List<ValidatorError> errors = test(dataset); if(!errors.isEmpty()) { assertEquals(errors.get(0).getPath(), "(root)->primaryPublications->acknowledges->name"); assertEquals(errors.get(0).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD); } else fail("No error messages produced for missing name"); } @Test public void testDatasetWithoutPrimaryPublicationsAcknowledgesFunders() { Dataset dataset = createPerfectDataset(); dataset.getPrimaryPublications().get(0).getAcknowledges().get(0).setFunders(DatasetFactory.createPersonComprisedEntityList(null)); List<ValidatorError> errors = test(dataset); if(!errors.isEmpty()) { assertEquals(errors.get(0).getPath(), "(root)->primaryPublications->acknowledges->funders"); assertEquals(errors.get(0).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD); } else fail("No error messages produced for missing Funders"); } @Test public void testDatasetWithoutIsAboutBiologicalEntityName() { Dataset dataset = createPerfectDataset(); ((IsAboutItems) dataset.getIsAbout().get(0)).setName(null); List<ValidatorError> errors = test(dataset); if(!errors.isEmpty()) { assertEquals(errors.get(0).getPath(), "(root)->isAbout->name"); assertEquals(errors.get(0).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD); } else fail("No error messages produced for missing IsAbout (Biological Entity) name"); } @Test public void testDatasetWithoutStudyName() { Dataset dataset = createPerfectDataset(); dataset.getProducedBy().setName(null); List<ValidatorError> errors = test(dataset); if(!errors.isEmpty()) { assertEquals(errors.get(0).getPath(), "(root)->producedBy->name"); assertEquals(errors.get(0).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD); } else fail("No error messages produced for missing name of Produced By"); } @Test public void testDatasetWithoutDate() { Dataset dataset = createPerfectDataset(); dataset.getProducedBy().getEndDate().setDate(null); List<ValidatorError> errors = test(dataset); if(!errors.isEmpty()) { assertEquals(errors.get(0).getPath(), "(root)->producedBy->endDate->date"); assertEquals(errors.get(0).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD); } else fail("No error messages produced for missing End Date for Produced By"); } @Test public void testDatasetWithoutDistributionConformsToTypes() { Dataset dataset = createPerfectDataset(); dataset.getDistributions().get(0).getConformsTo().get(0).getType().setValue(null); dataset.getDistributions().get(0).getConformsTo().get(0).getType().setValueIRI(null); List<ValidatorError> errors = test(dataset); if(!errors.isEmpty()) { assertEquals(errors.get(0).getPath(), "(root)->distributions->conformsTo->type"); assertEquals(errors.get(0).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD); } else fail("No error messages produced for missing Types"); } */ /* @Test public void testRealDataset() { Dataset dataset = createTestDataset(86L); List<ValidatorError> errors = test(dataset); if(!errors.isEmpty()) { // assertEquals(errors.get(0).getPath(), "(root)->isAbout->name"); // assertEquals(errors.get(0).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD); assertTrue(false); } else assertTrue(true); } */ /* @Test public void testValidationErrorsByDataset() { Set<String> types = new HashSet<>(); types.add(Dataset.class.getTypeName()); List<Entry> entriesList = repo.filterEntryIdsByTypes(types); Map<Dataset, List<ValidatorError>> datasetErrorListMap = new HashMap<Dataset, List<ValidatorError>>(); for (Entry entry : entriesList) { Dataset dataset = createTestDataset(entry.getId().getEntryId()); List<ValidatorError> errors = test(dataset); if(!errors.isEmpty()){ datasetErrorListMap.put(dataset,errors); } } if(datasetErrorListMap.isEmpty()) { assertTrue(true); } else fail("Errors were found!"); } */ @Test public void testValidationErrorCountByBreadcrumbForAllDatasets() { Set<String> types = new HashSet<>(); types.add(Dataset.class.getTypeName()); List<Entry> entriesList = repo.filterEntryIdsByTypesMaxRevisionID(types); Map<String, Integer> errorPathCount = new HashMap<String, Integer>(); for (Entry entry : entriesList) { // System.out.println(entry.getId().getEntryId()); Dataset dataset = createTestDataset(entry.getId().getEntryId()); List<ValidatorError> errors = test(dataset); if (!errors.isEmpty()) { for (ValidatorError error : errors) { if (errorPathCount.containsKey(error.getPath())) { errorPathCount.put(error.getPath(), errorPathCount.get(error.getPath()) + 1); } else errorPathCount.put(error.getPath(), 1); } } } assertEquals(errorPathCount.size(), 0); } @Test public void testGetEntryIdByErrorBreadcrumbForAllDatasets() { Set<String> types = new HashSet<>(); types.add(Dataset.class.getTypeName()); List<Entry> entriesList = repo.filterEntryIdsByTypesMaxRevisionID(types); Map<String, List<Long>> errorPathForEntryIds = new HashMap<String, List<Long>>(); for (Entry entry : entriesList) { Dataset dataset = createTestDataset(entry.getId().getEntryId()); List<ValidatorError> errors = test(dataset); if (!errors.isEmpty()) { for (ValidatorError error : errors) { if (errorPathForEntryIds.containsKey(error.getPath())) { errorPathForEntryIds.get(error.getPath()).add(entry.getId().getEntryId()); } else { ArrayList<Long> longList = new ArrayList<Long>(); longList.add(entry.getId().getEntryId()); errorPathForEntryIds.put(error.getPath(), longList); } } } } assertEquals(errorPathForEntryIds.size(), 0); } private String sortJsonObject(JsonObject jsonObject) { List<String> jsonElements = new ArrayList<>(); Set<Map.Entry<String, JsonElement>> entries = jsonObject.entrySet(); for (Map.Entry<String, JsonElement> entry : entries) jsonElements.add(entry.getKey()); Collections.sort(jsonElements); JsonArray jsonArray = new JsonArray(); for (String elementName : jsonElements) { JsonObject newJsonObject = new JsonObject(); JsonElement jsonElement = jsonObject.get(elementName); if (jsonElement.isJsonObject()) newJsonObject.add(elementName, new JsonPrimitive(sortJsonObject(jsonObject.get(elementName).getAsJsonObject()))); else if (jsonElement.isJsonArray()) { newJsonObject.add(elementName, sortJsonArray(jsonElement)); } else newJsonObject.add(elementName, jsonElement); jsonArray.add(newJsonObject); } return jsonArray.toString(); } private JsonArray sortJsonArray(JsonElement jsonElement) { JsonArray sortedArray = new JsonArray(); JsonArray jsonElementAsArray = jsonElement.getAsJsonArray(); for (JsonElement arrayMember : jsonElementAsArray) if (arrayMember.isJsonObject()) { sortedArray.add(new JsonPrimitive(sortJsonObject(arrayMember.getAsJsonObject()))); } else if (arrayMember.isJsonArray()) { sortedArray.add(sortJsonArray(arrayMember)); } else { sortedArray.add(arrayMember.toString()); } return sortedArray; } /* @Test public void testDatasetCreationComparision() { Long entryId = 566L; Entry entry = apiUtil.getEntryByIdIncludeNonPublic(entryId); EntryView entryView = new EntryView(entry); Dataset dataset = (Dataset) converter.fromJson(entryView.getUnescapedEntryJsonString(), Dataset.class); Dataset datasetJohn = null; Dataset datasetJeff = null; try { datasetJohn = (Dataset) ReflectionFactory.create(Dataset.class, dataset); //Reflection Factory // datasetJohn = (Dataset) ReflectionFactory.create(Dataset.class, createTestDataset(entryId)); //Dataset Factory datasetJeff = createTestDataset(entryId); // datasetJeff = DatasetFactory.createDatasetForWebFlow(null); } catch (Exception e) { e.printStackTrace(); fail(); } assertTrue(datasetComparision(datasetJohn, datasetJeff, entry)); datasetJeff.getDistributions().get(0).getDates().get(4); datasetJohn.getDistributions().get(0).getDates().get(4); XStream xstream = new XStream(new DomDriver()); // does not require XPP3 library String xmlJohn = xstream.toXML(datasetJohn). replaceAll("edu.pitt.isg.dc.utils.ReflectionFactoryElementFactory", "org.springframework.util.AutoPopulatingList\\$ReflectiveElementFactory"). replaceAll("dats2_2", "dats2__2"); String xmlJeff = xstream.toXML(datasetJeff). replaceAll("edu.pitt.isg.dc.utils.AutoPopulatedWrapper.AutoPopulatedDateWrapper", "edu.pitt.isg.mdc.dats2_2.Date"). replaceAll("edu.pitt.isg.dc.utils.AutoPopulatedWrapper.AutoPopulatedOrganizationWrapper", "edu.pitt.isg.mdc.dats2_2.Organization"). replaceAll("edu.pitt.isg.dc.utils.AutoPopulatedWrapper.AutoPopulatedPersonComprisedEntityWrapper", "edu.pitt.isg.mdc.dats2_2.PersonComprisedEntity"). replaceAll("edu.pitt.isg.dc.utils.AutoPopulatedWrapper.AutoPopulatedLicenseWrapper", "edu.pitt.isg.mdc.dats2_2.License"). replaceAll("edu.pitt.isg.dc.utils.AutoPopulatedWrapper.AutoPopulatedAccessWrapper", "edu.pitt.isg.mdc.dats2_2.Access"). replaceAll("edu.pitt.isg.dc.utils.AutoPopulatedWrapper.AutoPopulatedPlaceWrapper", "edu.pitt.isg.mdc.dats2_2.Place"). replaceAll("edu.pitt.isg.dc.utils.AutoPopulatedWrapper.AutoPopulatedTypeWrapper", "edu.pitt.isg.mdc.dats2_2.Type"). replaceAll("edu.pitt.isg.dc.utils.AutoPopulatedWrapper.AutoPopulatedDistributionWrapper", "edu.pitt.isg.mdc.dats2_2.Distribution"). replaceAll("edu.pitt.isg.dc.utils.AutoPopulatedWrapper.AutoPopulatedGrantWrapper", "edu.pitt.isg.mdc.dats2_2.Grant"). replaceAll("edu.pitt.isg.dc.utils.AutoPopulatedWrapper.AutoPopulatedPublicationWrapper", "edu.pitt.isg.mdc.dats2_2.Publication"). replaceAll("edu.pitt.isg.dc.utils.AutoPopulatedWrapper.AutoPopulatedIsAboutWrapper", "edu.pitt.isg.mdc.dats2_2.IsAbout"). replaceAll("edu.pitt.isg.dc.utils.AutoPopulatedWrapper.AutoPopulatedCategoryValuePairWrapper", "edu.pitt.isg.mdc.dats2_2.CategoryValuePair"). replaceAll("edu.pitt.isg.dc.utils.AutoPopulatedWrapper.AutoPopulatedDataStandardWrapper", "edu.pitt.isg.mdc.dats2_2.DataStandard"). replaceAll("dats2_2", "dats2__2"); assertEquals(xmlJeff, xmlJohn); } */ @Test public void testDatasetCreationComparisionForAllDatasets() { Set<String> types = new HashSet<>(); types.add(Dataset.class.getTypeName()); List<Entry> entriesList = repo.filterEntryIdsByTypesMaxRevisionID(types); Map<String, List<Long>> errorPathForEntryIds = new HashMap<String, List<Long>>(); for (Entry entry : entriesList) { EntryView entryView = new EntryView(entry); Dataset dataset = (Dataset) converter.fromJson(entryView.getUnescapedEntryJsonString(), Dataset.class); Dataset datasetJohn = null; Dataset datasetJeff = null; try { //Reflection Factory datasetJohn = (Dataset) ReflectionFactory.create(Dataset.class, dataset); //Dataset Factory datasetJeff = createTestDataset(entryView.getId().getEntryId()); } catch (Exception e) { e.printStackTrace(); fail(); } assertTrue(datasetComparision(datasetJohn, datasetJeff, entry)); // datasetJeff.getDistributions().get(0).getDates().get(4); // datasetJohn.getDistributions().get(0).getDates().get(4); XStream xstream = new XStream(new DomDriver()); // does not require XPP3 library String xmlJohn = xstream.toXML(datasetJohn). replaceAll("edu.pitt.isg.dc.utils.ReflectionFactoryElementFactory", "org.springframework.util.AutoPopulatingList\\$ReflectiveElementFactory"). replaceAll("dats2_2", "dats2__2"); String xmlJeff = xstream.toXML(datasetJeff). replaceAll("edu.pitt.isg.dc.utils.AutoPopulatedWrapper.AutoPopulatedDateWrapper", "edu.pitt.isg.mdc.dats2_2.Date"). replaceAll("edu.pitt.isg.dc.utils.AutoPopulatedWrapper.AutoPopulatedOrganizationWrapper", "edu.pitt.isg.mdc.dats2_2.Organization"). replaceAll("edu.pitt.isg.dc.utils.AutoPopulatedWrapper.AutoPopulatedPersonComprisedEntityWrapper", "edu.pitt.isg.mdc.dats2_2.PersonComprisedEntity"). replaceAll("edu.pitt.isg.dc.utils.AutoPopulatedWrapper.AutoPopulatedLicenseWrapper", "edu.pitt.isg.mdc.dats2_2.License"). replaceAll("edu.pitt.isg.dc.utils.AutoPopulatedWrapper.AutoPopulatedAccessWrapper", "edu.pitt.isg.mdc.dats2_2.Access"). replaceAll("edu.pitt.isg.dc.utils.AutoPopulatedWrapper.AutoPopulatedPlaceWrapper", "edu.pitt.isg.mdc.dats2_2.Place"). replaceAll("edu.pitt.isg.dc.utils.AutoPopulatedWrapper.AutoPopulatedTypeWrapper", "edu.pitt.isg.mdc.dats2_2.Type"). replaceAll("edu.pitt.isg.dc.utils.AutoPopulatedWrapper.AutoPopulatedDistributionWrapper", "edu.pitt.isg.mdc.dats2_2.Distribution"). replaceAll("edu.pitt.isg.dc.utils.AutoPopulatedWrapper.AutoPopulatedGrantWrapper", "edu.pitt.isg.mdc.dats2_2.Grant"). replaceAll("edu.pitt.isg.dc.utils.AutoPopulatedWrapper.AutoPopulatedPublicationWrapper", "edu.pitt.isg.mdc.dats2_2.Publication"). replaceAll("edu.pitt.isg.dc.utils.AutoPopulatedWrapper.AutoPopulatedIsAboutWrapper", "edu.pitt.isg.mdc.dats2_2.IsAbout"). replaceAll("edu.pitt.isg.dc.utils.AutoPopulatedWrapper.AutoPopulatedCategoryValuePairWrapper", "edu.pitt.isg.mdc.dats2_2.CategoryValuePair"). replaceAll("edu.pitt.isg.dc.utils.AutoPopulatedWrapper.AutoPopulatedDataStandardWrapper", "edu.pitt.isg.mdc.dats2_2.DataStandard"). replaceAll("dats2_2", "dats2__2"); assertEquals(xmlJeff, xmlJohn); } } public Boolean datasetComparision(Dataset datasetLeft, Dataset datasetRight, Entry entry) { Class clazz = Dataset.class; //issues with converter.toJsonObject -- with regards to isAbout and PersonComprisedEntity //for example PeronComprisedEntity is only returning identifier and alternateIdentifier; isAbout isn't returning anything JsonObject jsonObjectFromDatabaseLeft = converter.toJsonObject(clazz, datasetLeft); JsonObject jsonObjectFromDatabaseRight = converter.toJsonObject(clazz, datasetRight); Map<String, Object> databaseMapLeft = gson.fromJson(jsonObjectFromDatabaseLeft, mapType); Map<String, Object> databaseMapRight = gson.fromJson(jsonObjectFromDatabaseRight, mapType); MapDifference<String, Object> d = Maps.difference(databaseMapLeft, databaseMapRight); if (datasetLeft.equals(datasetRight) && d.areEqual()) { return true; } else { if (!d.toString().equalsIgnoreCase("equal")) { if (d.entriesOnlyOnLeft().size() > 0) { System.out.print("Entry " + jsonObjectFromDatabaseRight.get("title") + " (" + entry.getId().getEntryId() + "), Left contains"); Iterator<String> it = d.entriesOnlyOnLeft().keySet().iterator(); while (it.hasNext()) { String field = it.next(); System.out.print(" " + field + ","); } System.out.print(" but Right does not.\n"); } if (d.entriesOnlyOnRight().size() > 0) { System.out.print("Entry " + jsonObjectFromDatabaseRight.get("title") + " (" + entry.getId().getEntryId() + "), Right contains"); Iterator<String> it = d.entriesOnlyOnRight().keySet().iterator(); while (it.hasNext()) { String field = it.next(); System.out.print(" " + field + ","); } System.out.print(" but Left does not.\n"); } if (d.entriesDiffering().size() > 0) { Iterator<String> it = d.entriesDiffering().keySet().iterator(); while (it.hasNext()) { String value = it.next(); String left; if (jsonObjectFromDatabaseLeft.get(value).isJsonArray()) { left = sortJsonObject(jsonObjectFromDatabaseLeft.get(value).getAsJsonArray().get(0).getAsJsonObject()); } else { left = sortJsonObject(jsonObjectFromDatabaseLeft.get(value).getAsJsonObject()); } String right; if (jsonObjectFromDatabaseRight.get(value).isJsonArray()) { right = sortJsonObject(jsonObjectFromDatabaseRight.get(value).getAsJsonArray().get(0).getAsJsonObject()); } else { right = sortJsonObject(jsonObjectFromDatabaseRight.get(value).getAsJsonObject()); } if (!left.equals(right)) { int idxOfDifference = TestConvertDatsToJava.indexOfDifference(left, right); try { System.out.println("In " + value + " section from Left: ...\n" + left.substring(0, idxOfDifference) + Converter.ANSI_CYAN + left.substring(idxOfDifference, left.length()) + Converter.ANSI_RESET); System.out.println("In " + value + " section from Right: ...\n" + right.substring(0, idxOfDifference) + Converter.ANSI_CYAN + right.substring(idxOfDifference, right.length()) + Converter.ANSI_RESET); } catch (StringIndexOutOfBoundsException e) { System.out.println("idxOfDifference:" + idxOfDifference); // System.out.println("end:" + end); throw e; } } else { System.out.println(d); } } } } return false; } } /* @Test public void testCleanseSingleDataset(){ Long entryId = 566L; Entry entry = apiUtil.getEntryByIdIncludeNonPublic(entryId); EntryView entryView = new EntryView(entry); //create and clean datasetOriginal -- remove Emtpy Strings Dataset datasetOriginal = (Dataset) converter.fromJson(entryView.getUnescapedEntryJsonString(), Dataset.class); try { datasetOriginal = (Dataset) webFlowReflectionValidator.cleanse(Dataset.class, datasetOriginal); } catch (FatalReflectionValidatorException e) { e.printStackTrace(); } //create and run dataset through Factory Dataset dataset = new Dataset(); try { dataset = (Dataset) ReflectionFactory.create(Dataset.class, datasetOriginal); // dataset = createTestDataset(entry.getId().getEntryId()); } catch (Exception e) { e.printStackTrace(); fail(); } //clean dataset try { dataset = (Dataset) webFlowReflectionValidator.cleanse(Dataset.class, dataset); } catch (FatalReflectionValidatorException e) { e.printStackTrace(); } //compare original (cleaned) with dataset ran through Factory and cleaned assertTrue(datasetComparision(datasetOriginal, dataset, entry)); XStream xstream = new XStream(new DomDriver()); // does not require XPP3 library String xmlCleansed = xstream.toXML(dataset); String xmlOriginal = xstream.toXML(datasetOriginal); assertEquals(xmlOriginal, xmlCleansed); } */ @Test public void testCleanseForAllDatasets() { Set<String> types = new HashSet<>(); types.add(Dataset.class.getTypeName()); List<Entry> entriesList = repo.filterEntryIdsByTypesMaxRevisionID(types); Map<String, List<Long>> errorPathForEntryIds = new HashMap<String, List<Long>>(); for (Entry entry : entriesList) { EntryView entryView = new EntryView(entry); //create and clean datasetOriginal -- remove Emtpy Strings Dataset datasetOriginal = (Dataset) converter.fromJson(entryView.getUnescapedEntryJsonString(), Dataset.class); try { datasetOriginal = (Dataset) webFlowReflectionValidator.cleanse(Dataset.class, datasetOriginal, true, true); } catch (FatalReflectionValidatorException e) { e.printStackTrace(); } //create and run dataset through Factory Dataset dataset = new Dataset(); try { dataset = (Dataset) ReflectionFactory.create(Dataset.class, datasetOriginal); // dataset = createTestDataset(entry.getId().getEntryId()); } catch (Exception e) { e.printStackTrace(); fail(); } //clean dataset try { dataset = (Dataset) webFlowReflectionValidator.cleanse(Dataset.class, dataset, true, true); } catch (FatalReflectionValidatorException e) { e.printStackTrace(); } //compare original (cleaned) with dataset ran through Factory and cleaned assertTrue(datasetComparision(datasetOriginal, dataset, entry)); XStream xstream = new XStream(new DomDriver()); // does not require XPP3 library String xmlCleansed = xstream.toXML(dataset); String xmlOriginal = xstream.toXML(datasetOriginal); assertEquals(xmlOriginal, xmlCleansed); } } }
midas-isg/digital-commons
src/test/java/DatasetValidatorTest.java
Java
gpl-3.0
37,788
from couchpotato.api import addApiView from couchpotato.core.event import addEvent, fireEvent, fireEventAsync from couchpotato.core.helpers.encoding import ss from couchpotato.core.helpers.request import jsonified from couchpotato.core.logger import CPLog from couchpotato.core.plugins.base import Plugin from couchpotato.environment import Env from datetime import datetime from dateutil.parser import parse from git.repository import LocalRepository import json import os import shutil import tarfile import time import traceback import version log = CPLog(__name__) class Updater(Plugin): available_notified = False def __init__(self): if Env.get('desktop'): self.updater = DesktopUpdater() elif os.path.isdir(os.path.join(Env.get('app_dir'), '.git')): self.updater = GitUpdater(self.conf('git_command', default = 'git')) else: self.updater = SourceUpdater() fireEvent('schedule.interval', 'updater.check', self.autoUpdate, hours = 6) addEvent('app.load', self.autoUpdate) addEvent('updater.info', self.info) addApiView('updater.info', self.getInfo, docs = { 'desc': 'Get updater information', 'return': { 'type': 'object', 'example': """{ 'last_check': "last checked for update", 'update_version': "available update version or empty", 'version': current_cp_version }"""} }) addApiView('updater.update', self.doUpdateView) addApiView('updater.check', self.checkView, docs = { 'desc': 'Check for available update', 'return': {'type': 'see updater.info'} }) def autoUpdate(self): if self.check() and self.conf('automatic') and not self.updater.update_failed: if self.updater.doUpdate(): # Notify before restarting try: if self.conf('notification'): info = self.updater.info() version_date = datetime.fromtimestamp(info['update_version']['date']) fireEvent('updater.updated', 'Updated to a new version with hash "%s", this version is from %s' % (info['update_version']['hash'], version_date), data = info) except: log.error('Failed notifying for update: %s', traceback.format_exc()) fireEventAsync('app.restart') return True return False def check(self): if self.isDisabled(): return if self.updater.check(): if not self.available_notified and self.conf('notification') and not self.conf('automatic'): fireEvent('updater.available', message = 'A new update is available', data = self.updater.info()) self.available_notified = True return True return False def info(self): return self.updater.info() def getInfo(self): return jsonified(self.updater.info()) def checkView(self): return jsonified({ 'update_available': self.check(), 'info': self.updater.info() }) def doUpdateView(self): self.check() if not self.updater.update_version: log.error('Trying to update when no update is available.') success = False else: success = self.updater.doUpdate() if success: fireEventAsync('app.restart') # Assume the updater handles things if not success: success = True return jsonified({ 'success': success }) class BaseUpdater(Plugin): repo_user = 'jayme-github' repo_name = 'CouchPotatoServer' branch = version.BRANCH version = None update_failed = False update_version = None last_check = 0 def doUpdate(self): pass def getInfo(self): return jsonified(self.info()) def info(self): return { 'last_check': self.last_check, 'update_version': self.update_version, 'version': self.getVersion(), 'repo_name': '%s/%s' % (self.repo_user, self.repo_name), 'branch': self.branch, } def check(self): pass def deletePyc(self, only_excess = True): for root, dirs, files in os.walk(ss(Env.get('app_dir'))): pyc_files = filter(lambda filename: filename.endswith('.pyc'), files) py_files = set(filter(lambda filename: filename.endswith('.py'), files)) excess_pyc_files = filter(lambda pyc_filename: pyc_filename[:-1] not in py_files, pyc_files) if only_excess else pyc_files for excess_pyc_file in excess_pyc_files: full_path = os.path.join(root, excess_pyc_file) log.debug('Removing old PYC file: %s', full_path) try: os.remove(full_path) except: log.error('Couldn\'t remove %s: %s', (full_path, traceback.format_exc())) for dir_name in dirs: full_path = os.path.join(root, dir_name) if len(os.listdir(full_path)) == 0: try: os.rmdir(full_path) except: log.error('Couldn\'t remove empty directory %s: %s', (full_path, traceback.format_exc())) class GitUpdater(BaseUpdater): def __init__(self, git_command): self.repo = LocalRepository(Env.get('app_dir'), command = git_command) def doUpdate(self): try: log.debug('Stashing local changes') self.repo.saveStash() log.info('Updating to latest version') self.repo.pull() # Delete leftover .pyc files self.deletePyc() return True except: log.error('Failed updating via GIT: %s', traceback.format_exc()) self.update_failed = True return False def getVersion(self): if not self.version: try: output = self.repo.getHead() # Yes, please log.debug('Git version output: %s', output.hash) self.version = { 'hash': output.hash[:8], 'date': output.getDate(), 'type': 'git', } except Exception, e: log.error('Failed using GIT updater, running from source, you need to have GIT installed. %s', e) return 'No GIT' return self.version def check(self): if self.update_version: return True log.info('Checking for new version on github for %s', self.repo_name) if not Env.get('dev'): self.repo.fetch() current_branch = self.repo.getCurrentBranch().name for branch in self.repo.getRemoteByName('origin').getBranches(): if current_branch == branch.name: local = self.repo.getHead() remote = branch.getHead() log.info('Versions, local:%s, remote:%s', (local.hash[:8], remote.hash[:8])) if local.getDate() < remote.getDate(): self.update_version = { 'hash': remote.hash[:8], 'date': remote.getDate(), } return True self.last_check = time.time() return False class SourceUpdater(BaseUpdater): def __init__(self): # Create version file in cache self.version_file = os.path.join(Env.get('cache_dir'), 'version') if not os.path.isfile(self.version_file): self.createFile(self.version_file, json.dumps(self.latestCommit())) def doUpdate(self): try: url = 'https://github.com/%s/%s/tarball/%s' % (self.repo_user, self.repo_name, self.branch) destination = os.path.join(Env.get('cache_dir'), self.update_version.get('hash') + '.tar.gz') extracted_path = os.path.join(Env.get('cache_dir'), 'temp_updater') destination = fireEvent('file.download', url = url, dest = destination, single = True) # Cleanup leftover from last time if os.path.isdir(extracted_path): self.removeDir(extracted_path) self.makeDir(extracted_path) # Extract tar = tarfile.open(destination) tar.extractall(path = extracted_path) tar.close() os.remove(destination) if self.replaceWith(os.path.join(extracted_path, os.listdir(extracted_path)[0])): self.removeDir(extracted_path) # Write update version to file self.createFile(self.version_file, json.dumps(self.update_version)) return True except: log.error('Failed updating: %s', traceback.format_exc()) self.update_failed = True return False def replaceWith(self, path): app_dir = ss(Env.get('app_dir')) # Get list of files we want to overwrite self.deletePyc() existing_files = [] for root, subfiles, filenames in os.walk(app_dir): for filename in filenames: existing_files.append(os.path.join(root, filename)) for root, subfiles, filenames in os.walk(path): for filename in filenames: fromfile = os.path.join(root, filename) tofile = os.path.join(app_dir, fromfile.replace(path + os.path.sep, '')) if not Env.get('dev'): try: if os.path.isfile(tofile): os.remove(tofile) dirname = os.path.dirname(tofile) if not os.path.isdir(dirname): self.makeDir(dirname) shutil.move(fromfile, tofile) try: existing_files.remove(tofile) except ValueError: pass except: log.error('Failed overwriting file "%s": %s', (tofile, traceback.format_exc())) return False if Env.get('app_dir') not in Env.get('data_dir'): for still_exists in existing_files: try: os.remove(still_exists) except: log.error('Failed removing non-used file: %s', traceback.format_exc()) return True def removeDir(self, path): try: if os.path.isdir(path): shutil.rmtree(path) except OSError, inst: os.chmod(inst.filename, 0777) self.removeDir(path) def getVersion(self): if not self.version: try: f = open(self.version_file, 'r') output = json.loads(f.read()) f.close() log.debug('Source version output: %s', output) self.version = output self.version['type'] = 'source' except Exception, e: log.error('Failed using source updater. %s', e) return {} return self.version def check(self): current_version = self.getVersion() try: latest = self.latestCommit() if latest.get('hash') != current_version.get('hash') and latest.get('date') >= current_version.get('date'): self.update_version = latest self.last_check = time.time() except: log.error('Failed updating via source: %s', traceback.format_exc()) return self.update_version is not None def latestCommit(self): try: url = 'https://api.github.com/repos/%s/%s/commits?per_page=1&sha=%s' % (self.repo_user, self.repo_name, self.branch) data = self.getCache('github.commit', url = url) commit = json.loads(data)[0] return { 'hash': commit['sha'], 'date': int(time.mktime(parse(commit['commit']['committer']['date']).timetuple())), } except: log.error('Failed getting latest request from github: %s', traceback.format_exc()) return {} class DesktopUpdater(BaseUpdater): def __init__(self): self.desktop = Env.get('desktop') def doUpdate(self): try: def do_restart(e): if e['status'] == 'done': fireEventAsync('app.restart') elif e['status'] == 'error': log.error('Failed updating desktop: %s', e['exception']) self.update_failed = True self.desktop._esky.auto_update(callback = do_restart) return except: self.update_failed = True return False def info(self): return { 'last_check': self.last_check, 'update_version': self.update_version, 'version': self.getVersion(), 'branch': self.branch, } def check(self): current_version = self.getVersion() try: latest = self.desktop._esky.find_update() if latest and latest != current_version.get('hash'): self.update_version = { 'hash': latest, 'date': None, 'changelog': self.desktop._changelogURL, } self.last_check = time.time() except: log.error('Failed updating desktop: %s', traceback.format_exc()) return self.update_version is not None def getVersion(self): return { 'hash': self.desktop._esky.active_version, 'date': None, 'type': 'desktop', }
jayme-github/CouchPotatoServer
couchpotato/core/_base/updater/main.py
Python
gpl-3.0
14,024
package com.success.txn.jpa.repos; import java.util.Date; import javax.persistence.EntityManager; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Transactional; import com.success.txn.jpa.entities.Student; @Repository @Transactional(isolation = Isolation.REPEATABLE_READ) public class RepetableReadRepo { @Autowired private EntityManager em; private static final Logger logger = LoggerFactory.getLogger(RepetableReadRepo.class); public String insertOne() { Student s = new Student(); String address = "" + new Date(); s.setName(address); s.setAddress(address); em.persist(s); logger.info("new row inserted with address {}", address); Student s1 = em.find(Student.class, 1); logger.info("new name for student 1 {}", address); s1.setName(address); sleep(2000); logger.info("awoke"); return address; } public String getCount() { // when this method and insertOne are executed in parallel in two different txn, this code // executed but data stayed same (even after the insertOne is completed before "after sleep" lines // are execcted) // meaning the data modified by insertOne did not reflect in this method (even after the // insertOne txn is completed before this) CriteriaBuilder qb = em.getCriteriaBuilder(); CriteriaQuery<Long> cq = qb.createQuery(Long.class); cq.select(qb.count(cq.from(Student.class))); logger.info("total rows before sleep {}", em.createQuery(cq).getSingleResult()); sleep(10000); logger.info("total rows after sleep {}", em.createQuery(cq).getSingleResult()); logger.info("name of the student 1 {}", em.find(Student.class, 1).getName()); return "total rows " + em.createQuery(cq).getSingleResult(); } private void sleep(long seconds) { try { Thread.sleep(seconds); } catch (InterruptedException e) { e.printStackTrace(); } } }
btamilselvan/tamils
springtxn/src/main/java/com/success/txn/jpa/repos/RepetableReadRepo.java
Java
gpl-3.0
2,233
/* MapleLib - A general-purpose MapleStory library * Copyright (C) 2009, 2010, 2015 Snow and haha01haha01 * This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.*/ using System.IO; using MapleLib.WzLib.Util; namespace MapleLib.WzLib.WzProperties { /// <summary> /// A property with a string as a value /// </summary> public class WzStringProperty : WzImageProperty { #region Fields internal string name, val; internal WzObject parent; //internal WzImage imgParent; #endregion #region Inherited Members public override void SetValue(object value) { val = (string)value; } public override WzImageProperty DeepClone() { WzStringProperty clone = new WzStringProperty(name, val); return clone; } public override object WzValue { get { return Value; } } /// <summary> /// The parent of the object /// </summary> public override WzObject Parent { get { return parent; } internal set { parent = value; } } /*/// <summary> /// The image that this property is contained in /// </summary> public override WzImage ParentImage { get { return imgParent; } internal set { imgParent = value; } }*/ /// <summary> /// The WzPropertyType of the property /// </summary> public override WzPropertyType PropertyType { get { return WzPropertyType.String; } } /// <summary> /// The name of the property /// </summary> public override string Name { get { return name; } set { name = value; } } public override void WriteValue(MapleLib.WzLib.Util.WzBinaryWriter writer) { writer.Write((byte)8); writer.WriteStringValue(Value, 0, 1); } public override void ExportXml(StreamWriter writer, int level) { writer.WriteLine(XmlUtil.Indentation(level) + XmlUtil.EmptyNamedValuePair("WzString", this.Name, this.Value)); } /// <summary> /// Disposes the object /// </summary> public override void Dispose() { name = null; val = null; } #endregion #region Custom Members /// <summary> /// The value of the property /// </summary> public string Value { get { return val; } set { val = value; } } /// <summary> /// Creates a blank WzStringProperty /// </summary> public WzStringProperty() { } /// <summary> /// Creates a WzStringProperty with the specified name /// </summary> /// <param name="name">The name of the property</param> public WzStringProperty(string name) { this.name = name; } /// <summary> /// Creates a WzStringProperty with the specified name and value /// </summary> /// <param name="name">The name of the property</param> /// <param name="value">The value of the property</param> public WzStringProperty(string name, string value) { this.name = name; this.val = value; } #endregion #region Cast Values public override string GetString() { return val; } public override string ToString() { return val; } #endregion } }
haha01haha01/MapleLib
WzLib/WzProperties/WzStringProperty.cs
C#
gpl-3.0
3,632
/* * Copyright (c) 2011 Nicholas Okunew * All rights reserved. * * This file is part of the com.atomicleopard.webelemental library * * The com.atomicleopard.webelemental library is free software: you * can redistribute it and/or modify it under the terms of the GNU * Lesser General Public License as published by the Free Software Foundation, * either version 3 of the License, or (at your option) any later version. * * The com.atomicleopard.webelemental library is distributed in the hope * that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the com.atomicleopard.webelemental library. If not, see * http://www.gnu.org/licenses/lgpl-3.0.html. */ package com.atomicleopard.webelemental; import static org.hamcrest.Matchers.*; import org.hamcrest.Matcher; import org.hamcrest.Matchers; import com.atomicleopard.webelemental.matchers.HasAttributeMatcher; import com.atomicleopard.webelemental.matchers.HasClassMatcher; import com.atomicleopard.webelemental.matchers.HasIdMatcher; import com.atomicleopard.webelemental.matchers.HasSizeMatcher; import com.atomicleopard.webelemental.matchers.HasTextMatcher; import com.atomicleopard.webelemental.matchers.HasValueMatcher; import com.atomicleopard.webelemental.matchers.IsVisibleMatcher; /** * <p> * {@link ElementMatchers} provides static factory methods for producing * hamcrest {@link Matcher}s for different {@link Element} properties. * </p> * <p> * As an alternative, consider using an {@link ElementMatcher} obtained from * {@link Element#verify()} for a fluent, declarative API. * </p> */ public final class ElementMatchers { ElementMatchers() { } public static Matcher<Element> id(String string) { return id(is(string)); } public static Matcher<Element> id(Matcher<String> matcher) { return new HasIdMatcher(matcher); } public static Matcher<Element> cssClass(String string) { return cssClass(Matchers.is(string)); } public static Matcher<Element> cssClass(Matcher<String> matcher) { return new HasClassMatcher(matcher); } public static Matcher<Element> attr(String attribute, String value) { return attr(attribute, Matchers.is(value)); } public static Matcher<Element> attr(String attribute, Matcher<String> matcher) { return new HasAttributeMatcher(attribute, matcher); } public static Matcher<Element> value(String string) { return value(Matchers.is(string)); } public static Matcher<Element> value(Matcher<String> matcher) { return new HasValueMatcher(matcher); } public static Matcher<Element> size(int size) { return size(is(size)); } public static Matcher<Element> size(Matcher<Integer> matcher) { return new HasSizeMatcher(matcher); } public static Matcher<Element> text(String string) { return text(Matchers.is(string)); } public static Matcher<Element> text(Matcher<String> matcher) { return new HasTextMatcher(matcher); } public static Matcher<Element> visible() { return new IsVisibleMatcher(); } public static Matcher<Element> notVisible() { return not(new IsVisibleMatcher()); } }
atomicleopard/WebElemental
src/main/java/com/atomicleopard/webelemental/ElementMatchers.java
Java
gpl-3.0
3,429
<?php /*************************************************************************** * db.php * ------------------- * begin : Saturday, Feb 13, 2001 * copyright : (C) 2001 The phpBB Group * email : support@phpbb.com * * Id: db.php,v 1.10 2002/03/18 13:35:22 psotfx Exp * * ***************************************************************************/ /*************************************************************************** * This file is part of the phpBB2 port to Nuke 6.0 (c) copyright 2002 * by Tom Nitzschner (tom@toms-home.com) * http://bbtonuke.sourceforge.net (or http://www.toms-home.com) * * As always, make a backup before messing with anything. All code * release by me is considered sample code only. It may be fully * functual, but you use it at your own risk, if you break it, * you get to fix it too. No waranty is given or implied. * * Please post all questions/request about this port on http://bbtonuke.sourceforge.net first, * then on my site. All original header code and copyright messages will be maintained * to give credit where credit is due. If you modify this, the only requirement is * that you also maintain all original copyright messages. All my work is released * under the GNU GENERAL PUBLIC LICENSE. Please see the README for more information. * ***************************************************************************/ /*************************************************************************** * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * ***************************************************************************/ if (stristr($_SERVER['PHP_SELF'], "db.php")) { Header("Location: index.php"); die(); } if (defined('FORUM_ADMIN')) { $the_include = "../../../db"; } elseif (defined('INSIDE_MOD')) { $the_include = "../../db"; } else { $the_include = "db"; } switch($dbtype) { case 'MySQL': include("".$the_include."/mysql.php"); break; case 'mysql4': include("".$the_include."/mysql4.php"); break; case 'sqlite': include("".$the_include."/sqlite.php"); break; case 'postgres': include("".$the_include."/postgres7.php"); break; case 'mssql': include("".$the_include."/mssql.php"); break; case 'oracle': include("".$the_include."/oracle.php"); break; case 'msaccess': include("".$the_include."/msaccess.php"); break; case 'mssql-odbc': include("".$the_include."/mssql-odbc.php"); break; case 'db2': include("".$the_include."/db2.php"); break; } $db = new sql_db($dbhost, $dbuname, $dbpass, $dbname, false); if(!$db->db_connect_id) { //die("<br><br><center><img src=images/logo.gif><br><br><b>There seems to be a problem with the $dbtype server, sorry for the inconvenience.<br><br>We should be back shortly.</center></b>"); die("<br><br><center><img src=images/logo.gif><br><br><b>à¡Ô´¤ÇÒÁ¢Ñ´¢éͧºÒ§»ÃСÒà ¢ÍÍÀÑÂ㹤ÇÒÁäÁèÊдǡ<br><br>¢³Ð¹Õé¡ÓÅѧ´Óà¹Ô¹¡ÒÃá¡éä¢...</center></b>"); } ?>
CATtelecomProjects/BIS
db/db.php
PHP
gpl-3.0
3,290
package edu.casetools.icase.mreasoner.gui.model.io; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class FileReaderModel { FileReader fileReader = null; BufferedReader br = null; public void open(String fileName){ try { fileReader = new FileReader(fileName); br = new BufferedReader(fileReader); } catch (IOException e) { e.printStackTrace(); } } public String read(String fileName) throws IOException{ this.open(fileName); String result= "",sCurrentLine; while ((sCurrentLine = br.readLine()) != null) { result = result + sCurrentLine+"\n"; } this.close(); return result; } public void close(){ try { if (br != null)br.close(); } catch (IOException ex) { ex.printStackTrace(); } } }
ualegre/mreasoner-gui
mreasoner-gui/src/main/java/edu/casetools/icase/mreasoner/gui/model/io/FileReaderModel.java
Java
gpl-3.0
830
package alexiil.mc.mod.load.baked.render; import org.lwjgl.opengl.GL11; import net.minecraft.client.gui.FontRenderer; import alexiil.mc.mod.load.render.MinecraftDisplayerRenderer; import buildcraft.lib.expression.api.IExpressionNode.INodeDouble; import buildcraft.lib.expression.api.IExpressionNode.INodeLong; import buildcraft.lib.expression.node.value.NodeVariableDouble; import buildcraft.lib.expression.node.value.NodeVariableObject; public abstract class BakedTextRender extends BakedRenderPositioned { protected final NodeVariableObject<String> varText; protected final INodeDouble scale; protected final INodeDouble x; protected final INodeDouble y; protected final INodeLong colour; protected final String fontTexture; private String _text; private double _scale; private double _width; private long _colour; private double _x, _y; public BakedTextRender( NodeVariableObject<String> varText, NodeVariableDouble varWidth, NodeVariableDouble varHeight, INodeDouble scale, INodeDouble x, INodeDouble y, INodeLong colour, String fontTexture ) { super(varWidth, varHeight); this.varText = varText; this.scale = scale; this.x = x; this.y = y; this.colour = colour; this.fontTexture = fontTexture; } @Override public void evaluateVariables(MinecraftDisplayerRenderer renderer) { _text = getText(); _scale = scale.evaluate(); FontRenderer font = renderer.fontRenderer(fontTexture); _width = (int) (font.getStringWidth(_text) * _scale); varWidth.value = _width; varHeight.value = font.FONT_HEIGHT * _scale; _x = x.evaluate(); _y = y.evaluate(); _colour = colour.evaluate(); if ((_colour & 0xFF_00_00_00) == 0) { _colour |= 0xFF_00_00_00; } else if ((_colour & 0xFF_00_00_00) == 0x01_00_00_00) { _colour &= 0xFF_FF_FF; } } @Override public void render(MinecraftDisplayerRenderer renderer) { FontRenderer font = renderer.fontRenderer(fontTexture); GL11.glPushMatrix(); GL11.glTranslated(_x, _y, 0); GL11.glScaled(_scale, _scale, _scale); font.drawString(_text, 0, 0, (int) _colour, false); GL11.glPopMatrix(); GL11.glColor4f(1, 1, 1, 1); } public abstract String getText(); @Override public String getLocation() { return fontTexture; } }
AlexIIL/CustomLoadingScreen
src/main/java/alexiil/mc/mod/load/baked/render/BakedTextRender.java
Java
gpl-3.0
2,497
package eu.siacs.conversations.persistance; import android.annotation.TargetApi; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.RectF; import android.media.MediaMetadataRetriever; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.os.ParcelFileDescriptor; import android.provider.MediaStore; import android.provider.OpenableColumns; import android.support.v4.content.FileProvider; import android.system.Os; import android.system.StructStat; import android.util.Base64; import android.util.Base64OutputStream; import android.util.Log; import android.util.LruCache; import android.webkit.MimeTypeMap; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.File; import java.io.FileDescriptor; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.net.URL; import java.security.DigestOutputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.Locale; import eu.siacs.conversations.Config; import eu.siacs.conversations.R; import eu.siacs.conversations.entities.DownloadableFile; import eu.siacs.conversations.entities.Message; import eu.siacs.conversations.services.XmppConnectionService; import eu.siacs.conversations.utils.CryptoHelper; import eu.siacs.conversations.utils.ExifHelper; import eu.siacs.conversations.utils.FileUtils; import eu.siacs.conversations.utils.FileWriterException; import eu.siacs.conversations.utils.MimeUtils; import eu.siacs.conversations.xmpp.pep.Avatar; public class FileBackend { private static final Object THUMBNAIL_LOCK = new Object(); private static final SimpleDateFormat IMAGE_DATE_FORMAT = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US); public static final String FILE_PROVIDER = ".files"; private XmppConnectionService mXmppConnectionService; private static final List<String> BLACKLISTED_PATH_ELEMENTS = Arrays.asList("org.mozilla.firefox"); public FileBackend(XmppConnectionService service) { this.mXmppConnectionService = service; } private void createNoMedia() { final File nomedia = new File(getConversationsDirectory("Files") + ".nomedia"); if (!nomedia.exists()) { try { nomedia.createNewFile(); } catch (Exception e) { Log.d(Config.LOGTAG, "could not create nomedia file"); } } } public void updateMediaScanner(File file) { String path = file.getAbsolutePath(); if (!path.startsWith(getConversationsDirectory("Files"))) { Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); intent.setData(Uri.fromFile(file)); mXmppConnectionService.sendBroadcast(intent); } else { createNoMedia(); } } public boolean deleteFile(Message message) { File file = getFile(message); if (file.delete()) { updateMediaScanner(file); return true; } else { return false; } } public DownloadableFile getFile(Message message) { return getFile(message, true); } public DownloadableFile getFileForPath(String path, String mime) { final DownloadableFile file; if (path.startsWith("/")) { file = new DownloadableFile(path); } else { if (mime != null && mime.startsWith("image/")) { file = new DownloadableFile(getConversationsDirectory("Images") + path); } else if (mime != null && mime.startsWith("video/")) { file = new DownloadableFile(getConversationsDirectory("Videos") + path); } else { file = new DownloadableFile(getConversationsDirectory("Files") + path); } } return file; } public DownloadableFile getFile(Message message, boolean decrypted) { final boolean encrypted = !decrypted && (message.getEncryption() == Message.ENCRYPTION_PGP || message.getEncryption() == Message.ENCRYPTION_DECRYPTED); String path = message.getRelativeFilePath(); if (path == null) { path = message.getUuid(); } final DownloadableFile file = getFileForPath(path, message.getMimeType()); if (encrypted) { return new DownloadableFile(getConversationsDirectory("Files") + file.getName() + ".pgp"); } else { return file; } } public static long getFileSize(Context context, Uri uri) { try { final Cursor cursor = context.getContentResolver().query(uri, null, null, null, null); if (cursor != null && cursor.moveToFirst()) { long size = cursor.getLong(cursor.getColumnIndex(OpenableColumns.SIZE)); cursor.close(); return size; } else { return -1; } } catch (Exception e) { return -1; } } public static boolean allFilesUnderSize(Context context, List<Uri> uris, long max) { if (max <= 0) { Log.d(Config.LOGTAG, "server did not report max file size for http upload"); return true; //exception to be compatible with HTTP Upload < v0.2 } for (Uri uri : uris) { String mime = context.getContentResolver().getType(uri); if (mime != null && mime.startsWith("video/")) { try { Dimensions dimensions = FileBackend.getVideoDimensions(context, uri); if (dimensions.getMin() > 720) { Log.d(Config.LOGTAG, "do not consider video file with min width larger than 720 for size check"); continue; } } catch (NotAVideoFile notAVideoFile) { //ignore and fall through } } if (FileBackend.getFileSize(context, uri) > max) { Log.d(Config.LOGTAG, "not all files are under " + max + " bytes. suggesting falling back to jingle"); return false; } } return true; } public String getConversationsDirectory(final String type) { if (Config.ONLY_INTERNAL_STORAGE) { return mXmppConnectionService.getFilesDir().getAbsolutePath() + "/" + type + "/"; } else { return Environment.getExternalStorageDirectory() + "/Conversations/Media/Conversations " + type + "/"; } } public static String getConversationsLogsDirectory() { return Environment.getExternalStorageDirectory().getAbsolutePath() + "/Conversations/"; } public Bitmap resize(Bitmap originalBitmap, int size) { int w = originalBitmap.getWidth(); int h = originalBitmap.getHeight(); if (Math.max(w, h) > size) { int scalledW; int scalledH; if (w <= h) { scalledW = (int) (w / ((double) h / size)); scalledH = size; } else { scalledW = size; scalledH = (int) (h / ((double) w / size)); } Bitmap result = Bitmap.createScaledBitmap(originalBitmap, scalledW, scalledH, true); if (originalBitmap != null && !originalBitmap.isRecycled()) { originalBitmap.recycle(); } return result; } else { return originalBitmap; } } public static Bitmap rotate(Bitmap bitmap, int degree) { if (degree == 0) { return bitmap; } int w = bitmap.getWidth(); int h = bitmap.getHeight(); Matrix mtx = new Matrix(); mtx.postRotate(degree); Bitmap result = Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, true); if (bitmap != null && !bitmap.isRecycled()) { bitmap.recycle(); } return result; } public boolean useImageAsIs(Uri uri) { String path = getOriginalPath(uri); if (path == null || isPathBlacklisted(path)) { return false; } File file = new File(path); long size = file.length(); if (size == 0 || size >= mXmppConnectionService.getResources().getInteger(R.integer.auto_accept_filesize)) { return false; } BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; try { BitmapFactory.decodeStream(mXmppConnectionService.getContentResolver().openInputStream(uri), null, options); if (options.outMimeType == null || options.outHeight <= 0 || options.outWidth <= 0) { return false; } return (options.outWidth <= Config.IMAGE_SIZE && options.outHeight <= Config.IMAGE_SIZE && options.outMimeType.contains(Config.IMAGE_FORMAT.name().toLowerCase())); } catch (FileNotFoundException e) { return false; } } public static boolean isPathBlacklisted(String path) { for(String element : BLACKLISTED_PATH_ELEMENTS) { if (path.contains(element)) { return true; } } return false; } public String getOriginalPath(Uri uri) { return FileUtils.getPath(mXmppConnectionService, uri); } public void copyFileToPrivateStorage(File file, Uri uri) throws FileCopyException { Log.d(Config.LOGTAG, "copy file (" + uri.toString() + ") to private storage " + file.getAbsolutePath()); file.getParentFile().mkdirs(); OutputStream os = null; InputStream is = null; try { file.createNewFile(); os = new FileOutputStream(file); is = mXmppConnectionService.getContentResolver().openInputStream(uri); byte[] buffer = new byte[1024]; int length; while ((length = is.read(buffer)) > 0) { try { os.write(buffer, 0, length); } catch (IOException e) { throw new FileWriterException(); } } try { os.flush(); } catch (IOException e) { throw new FileWriterException(); } } catch (FileNotFoundException e) { throw new FileCopyException(R.string.error_file_not_found); } catch (FileWriterException e) { throw new FileCopyException(R.string.error_unable_to_create_temporary_file); } catch (IOException e) { e.printStackTrace(); throw new FileCopyException(R.string.error_io_exception); } finally { close(os); close(is); } } public void copyFileToPrivateStorage(Message message, Uri uri, String type) throws FileCopyException { String mime = type != null ? type : MimeUtils.guessMimeTypeFromUri(mXmppConnectionService, uri); Log.d(Config.LOGTAG, "copy " + uri.toString() + " to private storage (mime=" + mime + ")"); String extension = MimeUtils.guessExtensionFromMimeType(mime); if (extension == null) { extension = getExtensionFromUri(uri); } message.setRelativeFilePath(message.getUuid() + "." + extension); copyFileToPrivateStorage(mXmppConnectionService.getFileBackend().getFile(message), uri); } private String getExtensionFromUri(Uri uri) { String[] projection = {MediaStore.MediaColumns.DATA}; String filename = null; Cursor cursor = mXmppConnectionService.getContentResolver().query(uri, projection, null, null, null); if (cursor != null) { try { if (cursor.moveToFirst()) { filename = cursor.getString(0); } } catch (Exception e) { filename = null; } finally { cursor.close(); } } int pos = filename == null ? -1 : filename.lastIndexOf('.'); return pos > 0 ? filename.substring(pos + 1) : null; } private void copyImageToPrivateStorage(File file, Uri image, int sampleSize) throws FileCopyException { file.getParentFile().mkdirs(); InputStream is = null; OutputStream os = null; try { if (!file.exists() && !file.createNewFile()) { throw new FileCopyException(R.string.error_unable_to_create_temporary_file); } is = mXmppConnectionService.getContentResolver().openInputStream(image); if (is == null) { throw new FileCopyException(R.string.error_not_an_image_file); } Bitmap originalBitmap; BitmapFactory.Options options = new BitmapFactory.Options(); int inSampleSize = (int) Math.pow(2, sampleSize); Log.d(Config.LOGTAG, "reading bitmap with sample size " + inSampleSize); options.inSampleSize = inSampleSize; originalBitmap = BitmapFactory.decodeStream(is, null, options); is.close(); if (originalBitmap == null) { throw new FileCopyException(R.string.error_not_an_image_file); } Bitmap scaledBitmap = resize(originalBitmap, Config.IMAGE_SIZE); int rotation = getRotation(image); scaledBitmap = rotate(scaledBitmap, rotation); boolean targetSizeReached = false; int quality = Config.IMAGE_QUALITY; final int imageMaxSize = mXmppConnectionService.getResources().getInteger(R.integer.auto_accept_filesize); while (!targetSizeReached) { os = new FileOutputStream(file); boolean success = scaledBitmap.compress(Config.IMAGE_FORMAT, quality, os); if (!success) { throw new FileCopyException(R.string.error_compressing_image); } os.flush(); targetSizeReached = file.length() <= imageMaxSize || quality <= 50; quality -= 5; } scaledBitmap.recycle(); } catch (FileNotFoundException e) { throw new FileCopyException(R.string.error_file_not_found); } catch (IOException e) { e.printStackTrace(); throw new FileCopyException(R.string.error_io_exception); } catch (SecurityException e) { throw new FileCopyException(R.string.error_security_exception_during_image_copy); } catch (OutOfMemoryError e) { ++sampleSize; if (sampleSize <= 3) { copyImageToPrivateStorage(file, image, sampleSize); } else { throw new FileCopyException(R.string.error_out_of_memory); } } finally { close(os); close(is); } } public void copyImageToPrivateStorage(File file, Uri image) throws FileCopyException { Log.d(Config.LOGTAG, "copy image (" + image.toString() + ") to private storage " + file.getAbsolutePath()); copyImageToPrivateStorage(file, image, 0); } public void copyImageToPrivateStorage(Message message, Uri image) throws FileCopyException { switch (Config.IMAGE_FORMAT) { case JPEG: message.setRelativeFilePath(message.getUuid() + ".jpg"); break; case PNG: message.setRelativeFilePath(message.getUuid() + ".png"); break; case WEBP: message.setRelativeFilePath(message.getUuid() + ".webp"); break; } copyImageToPrivateStorage(getFile(message), image); updateFileParams(message); } private int getRotation(File file) { return getRotation(Uri.parse("file://" + file.getAbsolutePath())); } private int getRotation(Uri image) { InputStream is = null; try { is = mXmppConnectionService.getContentResolver().openInputStream(image); return ExifHelper.getOrientation(is); } catch (FileNotFoundException e) { return 0; } finally { close(is); } } public Bitmap getThumbnail(Message message, int size, boolean cacheOnly) throws FileNotFoundException { final String uuid = message.getUuid(); final LruCache<String, Bitmap> cache = mXmppConnectionService.getBitmapCache(); Bitmap thumbnail = cache.get(uuid); if ((thumbnail == null) && (!cacheOnly)) { synchronized (THUMBNAIL_LOCK) { thumbnail = cache.get(uuid); if (thumbnail != null) { return thumbnail; } DownloadableFile file = getFile(message); final String mime = file.getMimeType(); if (mime.startsWith("video/")) { thumbnail = getVideoPreview(file, size); } else { Bitmap fullsize = getFullsizeImagePreview(file, size); if (fullsize == null) { throw new FileNotFoundException(); } thumbnail = resize(fullsize, size); thumbnail = rotate(thumbnail, getRotation(file)); if (mime.equals("image/gif")) { Bitmap withGifOverlay = thumbnail.copy(Bitmap.Config.ARGB_8888, true); drawOverlay(withGifOverlay, R.drawable.play_gif, 1.0f); thumbnail.recycle(); thumbnail = withGifOverlay; } } this.mXmppConnectionService.getBitmapCache().put(uuid, thumbnail); } } return thumbnail; } private Bitmap getFullsizeImagePreview(File file, int size) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = calcSampleSize(file, size); try { return BitmapFactory.decodeFile(file.getAbsolutePath(), options); } catch (OutOfMemoryError e) { options.inSampleSize *= 2; return BitmapFactory.decodeFile(file.getAbsolutePath(), options); } } private void drawOverlay(Bitmap bitmap, int resource, float factor) { Bitmap overlay = BitmapFactory.decodeResource(mXmppConnectionService.getResources(), resource); Canvas canvas = new Canvas(bitmap); float targetSize = Math.min(canvas.getWidth(), canvas.getHeight()) * factor; Log.d(Config.LOGTAG, "target size overlay: " + targetSize + " overlay bitmap size was " + overlay.getHeight()); float left = (canvas.getWidth() - targetSize) / 2.0f; float top = (canvas.getHeight() - targetSize) / 2.0f; RectF dst = new RectF(left, top, left + targetSize - 1, top + targetSize - 1); canvas.drawBitmap(overlay, null, dst, createAntiAliasingPaint()); } private static Paint createAntiAliasingPaint() { Paint paint = new Paint(); paint.setAntiAlias(true); paint.setFilterBitmap(true); paint.setDither(true); return paint; } private Bitmap getVideoPreview(File file, int size) { MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever(); Bitmap frame; try { metadataRetriever.setDataSource(file.getAbsolutePath()); frame = metadataRetriever.getFrameAtTime(0); metadataRetriever.release(); frame = resize(frame, size); } catch (RuntimeException e) { frame = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888); frame.eraseColor(0xff000000); } drawOverlay(frame, R.drawable.play_video, 0.75f); return frame; } private static String getTakePhotoPath() { return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + "/Camera/"; } public Uri getTakePhotoUri() { File file; if (Config.ONLY_INTERNAL_STORAGE) { file = new File(mXmppConnectionService.getCacheDir().getAbsolutePath(), "Camera/IMG_" + this.IMAGE_DATE_FORMAT.format(new Date()) + ".jpg"); } else { file = new File(getTakePhotoPath() + "IMG_" + this.IMAGE_DATE_FORMAT.format(new Date()) + ".jpg"); } file.getParentFile().mkdirs(); return getUriForFile(mXmppConnectionService, file); } public static Uri getUriForFile(Context context, File file) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N || Config.ONLY_INTERNAL_STORAGE) { try { String packageId = context.getPackageName(); return FileProvider.getUriForFile(context, packageId + FILE_PROVIDER, file); } catch (IllegalArgumentException e) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { throw new SecurityException(e); } else { return Uri.fromFile(file); } } } else { return Uri.fromFile(file); } } public static Uri getIndexableTakePhotoUri(Uri original) { if (Config.ONLY_INTERNAL_STORAGE || "file".equals(original.getScheme())) { return original; } else { List<String> segments = original.getPathSegments(); return Uri.parse("file://" + getTakePhotoPath() + segments.get(segments.size() - 1)); } } public Avatar getPepAvatar(Uri image, int size, Bitmap.CompressFormat format) { Bitmap bm = cropCenterSquare(image, size); if (bm == null) { return null; } if (hasAlpha(bm)) { Log.d(Config.LOGTAG,"alpha in avatar detected; uploading as PNG"); bm.recycle(); bm = cropCenterSquare(image, 96); return getPepAvatar(bm, Bitmap.CompressFormat.PNG, 100); } return getPepAvatar(bm, format, 100); } private static boolean hasAlpha(final Bitmap bitmap) { for(int x = 0; x < bitmap.getWidth(); ++x) { for(int y = 0; y < bitmap.getWidth(); ++y) { if (Color.alpha(bitmap.getPixel(x,y)) < 255) { return true; } } } return false; } private Avatar getPepAvatar(Bitmap bitmap, Bitmap.CompressFormat format, int quality) { try { ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream(); Base64OutputStream mBase64OutputStream = new Base64OutputStream(mByteArrayOutputStream, Base64.DEFAULT); MessageDigest digest = MessageDigest.getInstance("SHA-1"); DigestOutputStream mDigestOutputStream = new DigestOutputStream(mBase64OutputStream, digest); if (!bitmap.compress(format, quality, mDigestOutputStream)) { return null; } mDigestOutputStream.flush(); mDigestOutputStream.close(); long chars = mByteArrayOutputStream.size(); if (format != Bitmap.CompressFormat.PNG && quality >= 50 && chars >= Config.AVATAR_CHAR_LIMIT) { int q = quality - 2; Log.d(Config.LOGTAG, "avatar char length was " + chars + " reducing quality to " + q); return getPepAvatar(bitmap, format, q); } Log.d(Config.LOGTAG, "settled on char length " + chars + " with quality=" + quality); final Avatar avatar = new Avatar(); avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest()); avatar.image = new String(mByteArrayOutputStream.toByteArray()); if (format.equals(Bitmap.CompressFormat.WEBP)) { avatar.type = "image/webp"; } else if (format.equals(Bitmap.CompressFormat.JPEG)) { avatar.type = "image/jpeg"; } else if (format.equals(Bitmap.CompressFormat.PNG)) { avatar.type = "image/png"; } avatar.width = bitmap.getWidth(); avatar.height = bitmap.getHeight(); return avatar; } catch (Exception e) { return null; } } public Avatar getStoredPepAvatar(String hash) { if (hash == null) { return null; } Avatar avatar = new Avatar(); File file = new File(getAvatarPath(hash)); FileInputStream is = null; try { avatar.size = file.length(); BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(file.getAbsolutePath(), options); is = new FileInputStream(file); ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream(); Base64OutputStream mBase64OutputStream = new Base64OutputStream(mByteArrayOutputStream, Base64.DEFAULT); MessageDigest digest = MessageDigest.getInstance("SHA-1"); DigestOutputStream os = new DigestOutputStream(mBase64OutputStream, digest); byte[] buffer = new byte[4096]; int length; while ((length = is.read(buffer)) > 0) { os.write(buffer, 0, length); } os.flush(); os.close(); avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest()); avatar.image = new String(mByteArrayOutputStream.toByteArray()); avatar.height = options.outHeight; avatar.width = options.outWidth; avatar.type = options.outMimeType; return avatar; } catch (IOException e) { return null; } catch (NoSuchAlgorithmException e) { return null; } finally { close(is); } } public boolean isAvatarCached(Avatar avatar) { File file = new File(getAvatarPath(avatar.getFilename())); return file.exists(); } public boolean save(Avatar avatar) { File file; if (isAvatarCached(avatar)) { file = new File(getAvatarPath(avatar.getFilename())); avatar.size = file.length(); } else { String filename = getAvatarPath(avatar.getFilename()); file = new File(filename + ".tmp"); file.getParentFile().mkdirs(); OutputStream os = null; try { file.createNewFile(); os = new FileOutputStream(file); MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.reset(); DigestOutputStream mDigestOutputStream = new DigestOutputStream(os, digest); final byte[] bytes = avatar.getImageAsBytes(); mDigestOutputStream.write(bytes); mDigestOutputStream.flush(); mDigestOutputStream.close(); String sha1sum = CryptoHelper.bytesToHex(digest.digest()); if (sha1sum.equals(avatar.sha1sum)) { file.renameTo(new File(filename)); } else { Log.d(Config.LOGTAG, "sha1sum mismatch for " + avatar.owner); file.delete(); return false; } avatar.size = bytes.length; } catch (IllegalArgumentException | IOException | NoSuchAlgorithmException e) { return false; } finally { close(os); } } return true; } public String getAvatarPath(String avatar) { return mXmppConnectionService.getFilesDir().getAbsolutePath() + "/avatars/" + avatar; } public Uri getAvatarUri(String avatar) { return Uri.parse("file:" + getAvatarPath(avatar)); } public Bitmap cropCenterSquare(Uri image, int size) { if (image == null) { return null; } InputStream is = null; try { BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = calcSampleSize(image, size); is = mXmppConnectionService.getContentResolver().openInputStream(image); if (is == null) { return null; } Bitmap input = BitmapFactory.decodeStream(is, null, options); if (input == null) { return null; } else { input = rotate(input, getRotation(image)); return cropCenterSquare(input, size); } } catch (SecurityException e) { return null; // happens for example on Android 6.0 if contacts permissions get revoked } catch (FileNotFoundException e) { return null; } finally { close(is); } } public Bitmap cropCenter(Uri image, int newHeight, int newWidth) { if (image == null) { return null; } InputStream is = null; try { BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = calcSampleSize(image, Math.max(newHeight, newWidth)); is = mXmppConnectionService.getContentResolver().openInputStream(image); if (is == null) { return null; } Bitmap source = BitmapFactory.decodeStream(is, null, options); if (source == null) { return null; } int sourceWidth = source.getWidth(); int sourceHeight = source.getHeight(); float xScale = (float) newWidth / sourceWidth; float yScale = (float) newHeight / sourceHeight; float scale = Math.max(xScale, yScale); float scaledWidth = scale * sourceWidth; float scaledHeight = scale * sourceHeight; float left = (newWidth - scaledWidth) / 2; float top = (newHeight - scaledHeight) / 2; RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight); Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(dest); canvas.drawBitmap(source, null, targetRect, createAntiAliasingPaint()); if (source.isRecycled()) { source.recycle(); } return dest; } catch (SecurityException e) { return null; //android 6.0 with revoked permissions for example } catch (FileNotFoundException e) { return null; } finally { close(is); } } public Bitmap cropCenterSquare(Bitmap input, int size) { int w = input.getWidth(); int h = input.getHeight(); float scale = Math.max((float) size / h, (float) size / w); float outWidth = scale * w; float outHeight = scale * h; float left = (size - outWidth) / 2; float top = (size - outHeight) / 2; RectF target = new RectF(left, top, left + outWidth, top + outHeight); Bitmap output = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(output); canvas.drawBitmap(input, null, target, createAntiAliasingPaint()); if (!input.isRecycled()) { input.recycle(); } return output; } private int calcSampleSize(Uri image, int size) throws FileNotFoundException, SecurityException { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeStream(mXmppConnectionService.getContentResolver().openInputStream(image), null, options); return calcSampleSize(options, size); } private static int calcSampleSize(File image, int size) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(image.getAbsolutePath(), options); return calcSampleSize(options, size); } public static int calcSampleSize(BitmapFactory.Options options, int size) { int height = options.outHeight; int width = options.outWidth; int inSampleSize = 1; if (height > size || width > size) { int halfHeight = height / 2; int halfWidth = width / 2; while ((halfHeight / inSampleSize) > size && (halfWidth / inSampleSize) > size) { inSampleSize *= 2; } } return inSampleSize; } public void updateFileParams(Message message) { updateFileParams(message, null); } public void updateFileParams(Message message, URL url) { DownloadableFile file = getFile(message); final String mime = file.getMimeType(); boolean image = message.getType() == Message.TYPE_IMAGE || (mime != null && mime.startsWith("image/")); boolean video = mime != null && mime.startsWith("video/"); boolean audio = mime != null && mime.startsWith("audio/"); final StringBuilder body = new StringBuilder(); if (url != null) { body.append(url.toString()); } body.append('|').append(file.getSize()); if (image || video) { try { Dimensions dimensions = image ? getImageDimensions(file) : getVideoDimensions(file); body.append('|').append(dimensions.width).append('|').append(dimensions.height); } catch (NotAVideoFile notAVideoFile) { Log.d(Config.LOGTAG, "file with mime type " + file.getMimeType() + " was not a video file"); //fall threw } } else if (audio) { body.append("|0|0|").append(getMediaRuntime(file)); } message.setBody(body.toString()); } public int getMediaRuntime(Uri uri) { try { MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever(); mediaMetadataRetriever.setDataSource(mXmppConnectionService, uri); return Integer.parseInt(mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)); } catch (RuntimeException e) { return 0; } } private int getMediaRuntime(File file) { try { MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever(); mediaMetadataRetriever.setDataSource(file.toString()); return Integer.parseInt(mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)); } catch (RuntimeException e) { return 0; } } private Dimensions getImageDimensions(File file) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(file.getAbsolutePath(), options); int rotation = getRotation(file); boolean rotated = rotation == 90 || rotation == 270; int imageHeight = rotated ? options.outWidth : options.outHeight; int imageWidth = rotated ? options.outHeight : options.outWidth; return new Dimensions(imageHeight, imageWidth); } private Dimensions getVideoDimensions(File file) throws NotAVideoFile { MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever(); try { metadataRetriever.setDataSource(file.getAbsolutePath()); } catch (RuntimeException e) { throw new NotAVideoFile(e); } return getVideoDimensions(metadataRetriever); } private static Dimensions getVideoDimensions(Context context, Uri uri) throws NotAVideoFile { MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever(); try { mediaMetadataRetriever.setDataSource(context, uri); } catch (RuntimeException e) { throw new NotAVideoFile(e); } return getVideoDimensions(mediaMetadataRetriever); } private static Dimensions getVideoDimensions(MediaMetadataRetriever metadataRetriever) throws NotAVideoFile { String hasVideo = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_HAS_VIDEO); if (hasVideo == null) { throw new NotAVideoFile(); } int rotation = extractRotationFromMediaRetriever(metadataRetriever); boolean rotated = rotation == 90 || rotation == 270; int height; try { String h = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT); height = Integer.parseInt(h); } catch (Exception e) { height = -1; } int width; try { String w = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH); width = Integer.parseInt(w); } catch (Exception e) { width = -1; } metadataRetriever.release(); Log.d(Config.LOGTAG, "extracted video dims " + width + "x" + height); return rotated ? new Dimensions(width, height) : new Dimensions(height, width); } private static int extractRotationFromMediaRetriever(MediaMetadataRetriever metadataRetriever) { int rotation; if (Build.VERSION.SDK_INT >= 17) { String r = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION); try { rotation = Integer.parseInt(r); } catch (Exception e) { rotation = 0; } } else { rotation = 0; } return rotation; } private static class Dimensions { public final int width; public final int height; public Dimensions(int height, int width) { this.width = width; this.height = height; } public int getMin() { return Math.min(width, height); } } private static class NotAVideoFile extends Exception { public NotAVideoFile(Throwable t) { super(t); } public NotAVideoFile() { super(); } } public class FileCopyException extends Exception { private static final long serialVersionUID = -1010013599132881427L; private int resId; public FileCopyException(int resId) { this.resId = resId; } public int getResId() { return resId; } } public Bitmap getAvatar(String avatar, int size) { if (avatar == null) { return null; } Bitmap bm = cropCenter(getAvatarUri(avatar), size, size); if (bm == null) { return null; } return bm; } public boolean isFileAvailable(Message message) { return getFile(message).exists(); } public static void close(Closeable stream) { if (stream != null) { try { stream.close(); } catch (IOException e) { } } } public static void close(Socket socket) { if (socket != null) { try { socket.close(); } catch (IOException e) { } } } public static boolean weOwnFile(Context context, Uri uri) { if (uri == null || !ContentResolver.SCHEME_FILE.equals(uri.getScheme())) { return false; } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { return fileIsInFilesDir(context, uri); } else { return weOwnFileLollipop(uri); } } /** * This is more than hacky but probably way better than doing nothing * Further 'optimizations' might contain to get the parents of CacheDir and NoBackupDir * and check against those as well */ private static boolean fileIsInFilesDir(Context context, Uri uri) { try { final String haystack = context.getFilesDir().getParentFile().getCanonicalPath(); final String needle = new File(uri.getPath()).getCanonicalPath(); return needle.startsWith(haystack); } catch (IOException e) { return false; } } @TargetApi(Build.VERSION_CODES.LOLLIPOP) private static boolean weOwnFileLollipop(Uri uri) { try { File file = new File(uri.getPath()); FileDescriptor fd = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY).getFileDescriptor(); StructStat st = Os.fstat(fd); return st.st_uid == android.os.Process.myUid(); } catch (FileNotFoundException e) { return false; } catch (Exception e) { return true; } } }
andre-hub/Conversations
src/main/java/eu/siacs/conversations/persistance/FileBackend.java
Java
gpl-3.0
34,726
<?php /** * Handler Registry * * @package Quark-Framework * @version $Id: handlerregistry.php 69 2013-01-24 15:14:45Z Jeffrey $ * @author Jeffrey van Harn <Jeffrey at lessthanthree.nl> * @since December 15, 2012 * @copyright Copyright (C) 2012-2013 Jeffrey van Harn. All rights reserved. * @license http://opensource.org/licenses/gpl-3.0.html GNU Public License Version 3 * * Copyright (C) 2012-2013 Jeffrey van Harn * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License (License.txt) for more details. */ // Define Namespace namespace Quark\Extensions; // Prevent individual file access if(!defined('DIR_BASE')) exit; /** * Registry that stores all the available and loaded extensions. * * The value for a Registry entry should be formatted in the following way: * array( * classname => (string) '\Quark\Full\Path\To\ClassName', * types => (array) Array of strings containing the directory extension names that can be loaded by this handler. * ) */ class HandlerRegistry extends \Quark\Util\Registry { /** * All extension handlers available * @var Array */ protected $registry = array( // Driver 'driver' => array( 'path' => 'Quark.Extensions.Handlers.Driver', 'classname' => '\\Quark\\Extensions\\Handlers\\DriverHandler', 'types' => array('driver', 'engine') ) ); /** * All instantiated handler object references. * @var array */ protected $objects = array(); /** * Get a handler for a extension typename * (A type is the extension part like "mysql.driver", then drive is the type, mostly the same as the handler name) * @param string $type Type to check for * @return bool|string[] The handler names. */ public function getByType($type){ $handlers = array(); foreach($this->registry as $name => $handler){ if(in_array($type, $handler['types'])){ $handlers[] = $name; } } // Not found return empty($handlers) ? false : $handlers; } /** * Get the object for a specific handler * @param string $name Handler name to get the object for * @return bool|Handler Boolean on error, object on success */ public function getObject($name){ // Check if the handler is registered if($this->exists($name)){ $handler = $this->registry[$name]; if(!isset($this->objects[$name])){ // Import if needed if(isset($handler['path'])) \Quark\import($handler['path'], true); // Check if the class exists if(class_exists($handler['classname'], false)){ $class = $handler['classname']; $obj = new $class; if($obj instanceof Handler){ $this->objects[$name] = $obj; return $obj; }else throw new \RuntimeException('The given Extension Handler class "'.$class.'" doesn\'t implement the "Handler" interface! Thus I had to exit.'); }else throw new \RuntimeException('The class "'.$handler['classname'].'" for the Extension handler "'.$name.'" did not exist, or could not be loaded!'); }else return $this->objects[$name]; }else return false; } // Override the registry helper functions /** * (Internal) Check if a value is a valid value for storage in the registry. * @param mixed $value Value to check. * @return boolean */ protected function validValue($value){ // Check if the values exist and their types are correct if(!(is_array($value) && (isset($value['classname']) && is_string($value['classname'])) && (isset($value['types']) && is_array($value['types'])))) return false; // Check if the class exists if(!class_exists($value['classname'], false)){ \Quark\Error\Error::raiseWarning('Handler class must already be loaded before registring!'); return false; } // Check if the types aren't already used foreach($types as $type){ $check = $this->getByType($type); if($check == false){ \Quark\Error\Error::raiseWarning('Type "'.$type.'" is already registred for handler "'.$check.'". Please either change or turn off the other handler.'); return false; } } // Everything went well. return true; } }
jvanharn/QuarkFramework
system/framework/extensions/handlerregistry.php
PHP
gpl-3.0
4,477
<?php /* * ******************************************************************** * Customization Services by ModulesGarden.com * Copyright (c) ModulesGarden, INBS Group Brand, All Rights Reserved * (2014-11-12, 10:35:44) * * * CREATED BY MODULESGARDEN -> http://modulesgarden.com * CONTACT -> contact@modulesgarden.com * * * * * This software is furnished under a license and may be used and copied * only in accordance with the terms of such license and with the * inclusion of the above copyright notice. This software or any other * copies thereof may not be provided or otherwise made available to any * other person. No title to and ownership of the software is hereby * transferred. * * * ******************************************************************** */ /** * @author Marcin Kozak <marcin.ko@modulesgarden.com> */ class Modulesgarden_Base_Model_Adminnotification_Item { public $title; public $description; public $url; public function __construct($title, $description, $url = '') { $this->title = $title; $this->description = $description; $this->url = $url; } }
QiuLihua83/Magento_with_some_popular_mods
app/code/community/Modulesgarden/Base/Model/Adminnotification/Item.php
PHP
gpl-3.0
1,257
// port.js class SingleData { constructor (port, order, type, value) { this.port = port this.order = order this.type = type this.value = value } } export let inputVariables = [] export let countVariables = [] // Add a new port export function Add (countInputPort) { countInputPort++ inputVariables[countInputPort] = [] countVariables[countInputPort] = 0 $('div#inputPortList').append( `<div class="list-group-item list-group-item-action" data-toggle="modal" data-target="#addNewModal${countInputPort}" id="inputPort${countInputPort}"> Port ${countInputPort}</div>` ) $(`#inputPort${countInputPort}`).click(function () { portDetail(countInputPort) }) return true } // Show Details of Port export function portDetail (countInputPort) { let container = '' let order = countVariables[countInputPort] // Show exist variables for (let variable of inputVariables[countInputPort]) { container += `<li class="list-group-item list-group-item-action"> <p class="mb-1 float-left text-primary">${variable.order + 1}&nbsp;&nbsp;&nbsp;&nbsp;</p> <p class="mb-1 float-left variable-type"><label class="variable-type" order="${variable.order}"> ${variable.type}</label>&nbsp;&nbsp;&nbsp;&nbsp;</p> <p class="mb-1 float-left"> <input type="text" class="form-control variable-value" order="${variable.order}" value="${variable.value}"> </p> </li>` } // Show variables list $('div#modalArea').html( `<div class="modal fade" id="addNewModal${countInputPort}" tabindex="-1" role="dialog" aria-labelledby="addNewModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="addNewModalLabel">Port ${countInputPort}</h5> <button class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <div class="form-row" id="globalDt"> <select class="form-control col-md-7 mx-sm-3 mb-3" id="dt"> <option value="Numeric">Numeric</option> <option value="Character">Character</option> <option value="Enumeration">Enumeration</option> <option value="Boolean">Boolean</option> <option value="Set">Set</option> <option value="Sequence">Sequence</option> <option value="String">String</option> <option value="Composite">Composite</option> <option value="Product">Product</option> <option value="Map">Map</option> <option value="Union">Union</option> <option value="Class">Class</option> </select> <button class="btn btn-outline-primary col-md-4 mb-3" id="addVariable">Add</button> </div> <!-- list of data types --> <div> <ul class="list-group" id="variables"> ${container} </ul> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-primary" id="savePort">Save changes</button> <button class="btn btn-secondary" data-dismiss="modal">Close</button> </div> </div> </div> </div>` ) // Add a new variables $('button#addVariable').click(function () { let selectedValue = $('select#dt').val() console.log(order) $('ul#variables').append( `<li class="list-group-item list-group-item-action"> <p class="mb-1 float-left text-primary">${order + 1}&nbsp;&nbsp;&nbsp;&nbsp;</p> <p class="mb-1 float-left variable-type"><label class="variable-type" order=${order}> ${selectedValue}</label>&nbsp;&nbsp;&nbsp;&nbsp;</p> <p class="mb-1 float-left"> <input type="text" class="form-control variable-value" order="${order}" placeholder="${selectedValue}"> </p> </li>` ) order++ }) // Save port $('button#savePort').click(function () { let i for (i = 0; i < order; i++) { let type = $(`label.variable-type[order$="${i}"]`).text() let value = $(`input.variable-value[order$="${i}"]`).val() // console.log(type + '\n' + value) inputVariables[countInputPort][i] = new SingleData(countInputPort, i, type, value) console.log(`saved: port: ${countInputPort} order: ${i} type: ${type} value: ${value}`) } countVariables[countInputPort] = i console.log('total: ' + countVariables[countInputPort]) }) } export function Update (id, value) { let editId = 'div#' + id $(editId).text(value) }
cy92830/DataTypeGUI
src/scripts/port1.js
JavaScript
gpl-3.0
4,832
<?PHP require_once("website.php"); $adminModuleUtils->checkAdminModule(MODULE_FORM); $mlText = $languageUtils->getMlText(__FILE__); $warnings = array(); $formSubmitted = LibEnv::getEnvHttpPOST("formSubmitted"); if ($formSubmitted) { $formId = LibEnv::getEnvHttpPOST("formId"); $name = LibEnv::getEnvHttpPOST("name"); $description = LibEnv::getEnvHttpPOST("description"); $name = LibString::cleanString($name); $description = LibString::cleanString($description); // The name is required if (!$name) { array_push($warnings, $mlText[6]); } // Check that the name is not already used if ($form = $formUtils->selectByName($name)) { $wFormId = $form->getId(); if ($wFormId != $formId) { array_push($warnings, $mlText[7]); } } if (count($warnings) == 0) { // Duplicate the form $formUtils->duplicate($formId, $name); $str = LibHtml::urlRedirect("$gFormUrl/admin.php"); printMessage($str); exit; } } else { $formId = LibEnv::getEnvHttpGET("formId"); $name = ''; $description = ''; if ($form = $formUtils->selectById($formId)) { $randomNumber = LibUtils::generateUniqueId(); $name = $form->getName() . FORM_DUPLICATA . '_' . $randomNumber; $description = $form->getDescription(); } } $strWarning = ''; if (count($warnings) > 0) { foreach ($warnings as $warning) { $strWarning .= "<br>$warning"; } } $panelUtils->setHeader($mlText[0], "$gFormUrl/admin.php"); $panelUtils->addLine($panelUtils->addCell($strWarning, "wb")); $help = $popupUtils->getHelpPopup($mlText[3], 300, 300); $panelUtils->setHelp($help); $panelUtils->openForm($PHP_SELF); $panelUtils->addLine($panelUtils->addCell($mlText[4], "nbr"), "<input type='text' name='name' value='$name' size='30' maxlength='50'>"); $panelUtils->addLine(); $panelUtils->addLine($panelUtils->addCell($mlText[5], "nbr"), "<input type='text' name='description' value='$description' size='30' maxlength='255'>"); $panelUtils->addLine(); $panelUtils->addLine('', $panelUtils->getOk()); $panelUtils->addHiddenField('formSubmitted', 1); $panelUtils->addHiddenField('formId', $formId); $panelUtils->closeForm(); $str = $panelUtils->render(); printAdminPage($str); ?>
stephaneeybert/learnintouch
modules/form/duplicate.php
PHP
gpl-3.0
2,253
// DXQuake3 Source // Copyright (c) 2003 Richard Geary (richard.geary@dial.pipex.com) // // // Useful Utilities for DQ // #include "stdafx.h" //'a'-'A' = 97 - 65 = 32 #define DQLowerCase( in ) ( ( (in)>='a' && (in)<='z' ) ? (in)-32 : (in) ) //Copy pSrc to pDest up to null terminating char or MaxLength //Return value is length of copied string, excluding null-terminator int DQstrcpy(char *pDest, const char *pSrc, int MaxLength) { int pos = 0; if( !pDest || !pSrc || MaxLength<0 ) { //Used by c_Exception, so we can't throw a c_Exception type throw 1; } while(*pSrc!='\0' && pos<MaxLength-1) { *pDest = *pSrc; ++pos; ++pSrc; ++pDest; } *pDest = '\0'; return pos; } //Returns length of pSrc excluding null terminting character, up to MaxLength int DQstrlen(const char *pSrc, int MaxLength) { const char *pos = pSrc; int len = 0; while(*pos!='\0' && len<MaxLength) { ++len; ++pos; } return len; } //Compares pStr1 to pStr2 up to Null terminator or Maxlength. Returns 0 if identital, else -1 (c.f. C strcmp) int DQstrcmp(const char *pStr1, const char *pStr2, int MaxLength) { int pos = 1; DebugCriticalAssert( pStr1 && pStr2 ); while(*pStr1==*pStr2) { if(*pStr1=='\0' || pos>=MaxLength) return 0; //strings identical ++pStr1; ++pStr2; ++pos; } if(*pStr1=='\0' || *pStr2=='\0') return 0; //strings different return -1; } //Compares (case insensitive) pStr1 to pStr2 up to Null terminator or Maxlength. Returns 0 if identital, else -1 (c.f. C strcmp) int DQstrcmpi(const char *pStr1, const char *pStr2, int MaxLength) { int pos = 0; DebugCriticalAssert( pStr1 && pStr2 ); char c1, c2; c1 = DQLowerCase( *pStr1 ); c2 = DQLowerCase( *pStr2 ); while(c1==c2) { if(pos>=MaxLength) return -1; if(c1=='\0') return 0; //strings identical ++pStr1; ++pStr2; ++pos; c1 = DQLowerCase( *pStr1 ); c2 = DQLowerCase( *pStr2 ); } //strings different return -1; } //Skips space, tab, new lines, // and /* */ //Returns position (in bytes) relative to pSrc int DQSkipWhitespace(const char *pSrc, int MaxLength) { BOOL bComment = FALSE; //Possible Comment ( // ) int pos=0; DebugCriticalAssert( pSrc ); while(pos<MaxLength && (*pSrc==' ' || *pSrc=='\t' || *pSrc=='/' || *pSrc=='*' || *pSrc==10 || *pSrc==13)) { if(*pSrc=='*') { //if we have /* if(bComment) { //Skip until */ bComment = TRUE; while(bComment) { if(pos>=MaxLength) return MaxLength; if(*pSrc=='*') { if((pos+1<MaxLength) && *(pSrc+1)=='/') { bComment = FALSE; ++pSrc; ++pos; } } ++pSrc; ++pos; } } else break; // we have * on its own, which is not whitespace } if(*pSrc=='/') { if(bComment == TRUE) { //Skip to end of line while(*pSrc!=10 && *pSrc!=0 && pos<MaxLength) { ++pSrc; ++pos; } bComment = FALSE; } else bComment = TRUE; } else { if(bComment == TRUE) { //Previous / was a valid character return pos-1; } } ++pSrc; ++pos; } // if(*pSrc==10 || *pSrc==13 || *pSrc==0 || pos==MaxLength) return MaxLength; //end of the string //else return pos; } //Returns the position of the next space, tab, end of line, comment, or MaxLength int DQSkipWord(const char *pSrc, int MaxLength) { BOOL bComment = FALSE; int pos=0; DebugCriticalAssert( pSrc ); while(pos<MaxLength && *pSrc!=' ' && *pSrc!='\t' && *pSrc!=10 && *pSrc!=13 && *pSrc!=0) { if(*pSrc=='*' && bComment==TRUE) { return pos-1; } if(*pSrc=='/') { if(bComment == TRUE) { // return pos of start of // return pos-1; } else bComment = TRUE; } else { bComment = FALSE; //wasn't a comment line } ++pSrc; ++pos; } return pos; } //Strips an extention off a path void DQStripExtention(char *pPath, int MaxLength) { int pos = 0; while(pos<MaxLength && *pPath!='\0') { ++pos; ++pPath; } //Move back to . while(pos>0 && *pPath!='.') { --pos; --pPath; } //Truncate pPath if(*pPath=='.') *pPath='\0'; return; } //Strips a filename off a path void DQStripFilename(char *pPath, int MaxLength) { BOOL bHasFilename = FALSE; //path has a filename in it int pos = 0; while(pos<MaxLength && *pPath!='\0') { if(*pPath=='.') bHasFilename = TRUE; ++pos; ++pPath; } if(!bHasFilename) { //path has no filename already //Remove any / at the end of pPath --pPath; if(*pPath=='\\' || *pPath=='/') *pPath='\0'; return; } /* Move back to / or \ */ while(pos>0 && *pPath!='/' && *pPath!='\\') { --pos; --pPath; } //Truncate pPath *pPath='\0'; return; } //Returns position of next line (relative to pSrc) int DQNextLine(const char *pSrc, int MaxLength) { int pos=0; DebugCriticalAssert( pSrc ); while(pos<MaxLength && *pSrc!=10 && *pSrc!=13 && *pSrc!=0) { ++pSrc; ++pos; } if(*pSrc==0) return pos; return pos+1; } //Case insensitive Compare pSrc1 to pSrc2 until next whitespace or MaxLength, not including comments (cba) //Return 0 if identical, else -1 int DQWordstrcmpi(const char *pStr1, const char *pStr2, int MaxLength) { DebugCriticalAssert( pStr1 && pStr2 ); int pos = 0; char c1, c2; c1 = DQLowerCase( *pStr1 ); c2 = DQLowerCase( *pStr2 ); while(c1==c2) { if(c1=='\0' || c1==' ' || c1=='\t' || pos>MaxLength) return 0; //strings identical ++pStr1; ++pStr2; ++pos; c1 = DQLowerCase( *pStr1 ); c2 = DQLowerCase( *pStr2 ); } if(c1=='\0' && ( c2==' ' || c2=='\t' || c2==10 || c2==13) ) return 0; if(c2=='\0' && ( c1==' ' || c1=='\t' || c1==10 || c1==13) ) return 0; //strings different return -1; } //Compares (case insensitive) pStrShort to pStrLong up to FIRST Null terminator or Maxlength. //Returns 0 if pStrLong is identical to pStrShort so far, else -1 //eg. pStrShort = "blah", pStrLong = "blahman", return 0 //eg. pStrShort = "blahman", pStrLong = "blah", return -1 int DQPartialstrcmpi(const char *pStrShort, const char *pStrLong, int MaxLength) { int pos = 0; DebugCriticalAssert( pStrShort && pStrLong ); char c1, c2; c1 = DQLowerCase( *pStrShort ); c2 = DQLowerCase( *pStrLong ); while(c1==c2) { if(pos>=MaxLength) return 0; if(c1=='\0') return 0; ++pStrShort; ++pStrLong; ++pos; c1 = DQLowerCase( *pStrShort ); c2 = DQLowerCase( *pStrLong ); } if(*pStrShort=='\0') return 0; //strings different return -1; } //Copies pSrc to pDest until whitespace or MaxLength //Returns length of word, excluding null terminator int DQWordstrcpy(char *pDest, const char *pSrc, int MaxLength) { int pos = 0; DebugCriticalAssert( pSrc && pDest && MaxLength>=0 ); while(*pSrc!='\0' && *pSrc!=' ' && *pSrc!='\t' && *pSrc!=10 && *pSrc!=13 && pos<MaxLength-1) { *pDest = *pSrc; ++pos; ++pSrc; ++pDest; } *pDest = '\0'; return pos; } //Appends pSrcAppend to pDest, up to pSrcAppend[MaxLength] or Null-terminator //Returns length of pSrcAppend int DQstrcat(char *pDest, const char *pSrcAppend, int MaxLength) { int pos = 0, SrcLength = 0; while(*pDest!='\0') { if(pos>=MaxLength) { return MaxLength; } ++pDest; ++pos; } while(*pSrcAppend!='\0') { if(pos>=MaxLength-1) { return MaxLength; } *pDest = *pSrcAppend; ++pDest; ++pSrcAppend; ++pos; ++SrcLength; } *pDest = '\0'; return SrcLength; } void DQStripPath(char *pFullPath, int MaxLength) { int pos = 0; char *pPath = pFullPath; while(pos<MaxLength && *pPath!='\0') { ++pos; ++pPath; } while(pos>0 && *pPath!='/' && *pPath!='\\') { --pPath; --pos; } if(pos==0) return; ++pPath; ++pos; while(pos<MaxLength && *pPath!='\0') { *pFullPath = *pPath; ++pPath; ++pFullPath; ++pos; } *pFullPath='\0'; } //Copy pSrc to pDest until *pSrc==marker or '\0' or MaxLength reached //returns num chars copied +1, or the pos of the null-terminator int DQCopyUntil(char *pDest, const char *pSrc, char marker, int MaxLength) { int pos = 0; while(pos<MaxLength-1 && *pSrc!=marker && *pSrc!='\0') { *pDest=*pSrc; ++pDest; ++pSrc; ++pos; } *pDest = '\0'; if(*pSrc=='\0') return pos; return pos+1; //return the char after marker } //remove "'s void DQStripQuotes(char *pString, int MaxLength) { int i; if(*pString=='"') { for(i=0;i<MaxLength && *(pString+1)!='"';++i,++pString) *pString = *(pString+1); *pString='\0'; } } //Truncate pStr1 when it varies (case insensitive) from pCompareString void DQstrTruncate(char *pStr1, const char *pCompareString, int MaxLength) { int pos = 0; DebugCriticalAssert( pStr1 && pCompareString ); char c1,c2; c1 = DQLowerCase( *pStr1 ); c2 = DQLowerCase( *pCompareString ); while(c1==c2) { if(pos>=MaxLength) return; if(c1=='\0') return; ++pStr1; ++pCompareString; ++pos; c1 = DQLowerCase( *pStr1 ); c2 = DQLowerCase( *pCompareString ); } //Truncate *pStr1 = '\0'; } void DQWCharToChar(WCHAR *pSrc, int SrcLength, char *pDest, int DestLength) { WideCharToMultiByte( CP_ACP, NULL, pSrc, SrcLength, pDest, DestLength, NULL, NULL ); } //same as strcmpi, but insensitive to \ and / int DQFilenamestrcmpi(const char *pStr1, const char *pStr2, int MaxLength) { int pos = 0; DebugCriticalAssert( pStr1 && pStr2 ); char c1, c2; c1 = DQLowerCase( *pStr1 ); c2 = DQLowerCase( *pStr2 ); if(c1=='\\') c1='/'; if(c2=='\\') c2='/'; while(c1==c2) { if(pos>=MaxLength) return -1; if(c1=='\0') return 0; //strings identical ++pStr1; ++pStr2; ++pos; c1 = DQLowerCase( *pStr1 ); c2 = DQLowerCase( *pStr2 ); if(c1=='\\') c1='/'; if(c2=='\\') c2='/'; } //strings different return -1; } void DQStripGfxExtention(char *pSrc, int MaxLength) { int len; if(!pSrc || MaxLength<4) return; len = DQstrlen( pSrc, MAX_QPATH ); if(len>4) { if( (DQstrcmpi(&pSrc[len-4], ".tga", MAX_QPATH)==0) || (DQstrcmpi(&pSrc[len-4], ".jpg", MAX_QPATH)==0) ) { pSrc[len-4] = '\0'; } } }
coltongit/dxquake3
code/utils.cpp
C++
gpl-3.0
10,161
function createDownloadLink(data,filename,componentId){ let a = document.createElement('a'); a.href = 'data:' + data; a.download = filename; a.innerHTML = 'Export'; a.class = 'btn' let container = document.getElementById(componentId); container.appendChild(a); } function closest(array, num) { let i = 0; let minDiff = 1000; let ans; for (i in array) { let m = Math.abs(num - array[i]); if (m < minDiff) { minDiff = m; ans = array[i]; } } return ans; } export {createDownloadLink, closest}
alvcarmona/efficiencycalculatorweb
effcalculator/frontend/assets/js/utils.js
JavaScript
gpl-3.0
678
/* To Do: Fix Reverse Driving Make only one side fire (right) */ /* Copyright (c) 2014, 2015 Qualcomm Technologies Inc All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the limitations in the disclaimer below) provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of Qualcomm Technologies Inc nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.firstinspires.ftc.teamcode; import com.qualcomm.robotcore.eventloop.opmode.*; import com.qualcomm.robotcore.util.ElapsedTime; import com.qualcomm.robotcore.hardware.*; //red turns left //blue turns right /* To Do; Double gears on shooter Rotate Block and Top Part of Beacon Pusher 90 degrees. The servo end position is currently level with the end of the robot instead of sideways */ import java.text.SimpleDateFormat; import java.util.Date; import static android.os.SystemClock.sleep; /** * Registers OpCode and Initializes Variables */ @com.qualcomm.robotcore.eventloop.opmode.Autonomous(name = "Autonomous α", group = "FTC772") public class Autonomous extends LinearOpMode { private ElapsedTime runtime = new ElapsedTime(); private DcMotor frontLeft, frontRight, intake, dispenserLeft, dispenserRight, liftLeft, liftRight, midtake; private Servo dispenser, beaconAngleLeft, beaconAngleRight, forkliftLeft, forkliftRight; private boolean drivingForward = true; //private boolean init = false; //private final double DISPENSER_POWER = 1; private double BEACON_LEFT_IN; private double BEACON_RIGHT_IN; private final int INITIAL_FORWARD = 1000; private final int RAMP_UP = 1000; private final int TURN_ONE = 300; private final int FORWARD_TWO = 500; private final int TURN_TWO = 300; private final int FORWARD_THREE = 300; private final int COLOR_CORRECTION = 50; private final int FORWARD_FOUR = 400; private final int TURN_THREE = 500; private final int FORWARD_FIVE = 500; private final boolean isRed = true; private boolean didColorCorrection = false; private boolean wasChangingAngle = false; private ColorSensor colorSensor; private TouchSensor leftTouchSensor, rightTouchSensor; // @Override // public void init() { // /* // Initialize DcMotors // */ // frontLeft = hardwareMap.dcMotor.get("frontLeft"); // frontRight = hardwareMap.dcMotor.get("frontRight"); // // //intake = hardwareMap.dcMotor.get("intake"); // dispenserLeft = hardwareMap.dcMotor.get("dispenserLeft"); // dispenserRight = hardwareMap.dcMotor.get("dispenserRight"); // // /* // Initialize Servos // */ // dispenserAngle = hardwareMap.servo.get("dispenserAngle"); // beaconAngle = hardwareMap.servo.get("beaconAngle"); // // // /* // Initialize Sensors // */ // colorSensor = hardwareMap.colorSensor.get("colorSensor"); // leftTouchSensor = hardwareMap.touchSensor.get("leftTouchSensor"); // rightTouchSensor = hardwareMap.touchSensor.get("rightTouchSensor"); // // //Display completion message // telemetry.addData("Status", "Initialized"); // } /* * Code to run when the op mode is first enabled goes here * @see com.qualcomm.robotcore.eventloop.opmode.OpMode#start() @Override public void init_loop() { }*/ /* * This method will be called ONCE when start is pressed * @see com.qualcomm.robotcore.eventloop.opmode.OpMode#loop() */ /* public void start() { /* Initialize all motors/servos to position */ //runtime.reset(); //dispenserAngle.setPosition(DEFAULT_ANGLE); // } /* * This method will be called repeatedly in a loop * @see com.qualcomm.robotcore.eventloop.opmode.OpMode#loop() */ @Override public void runOpMode() throws InterruptedException { frontLeft = hardwareMap.dcMotor.get("frontLeft"); frontRight = hardwareMap.dcMotor.get("frontRight"); intake = hardwareMap.dcMotor.get("intake"); midtake = hardwareMap.dcMotor.get("midtake"); dispenserLeft = hardwareMap.dcMotor.get("dispenserLeft"); dispenserRight = hardwareMap.dcMotor.get("dispenserRight"); dispenserLeft.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.FLOAT); dispenserRight.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.FLOAT); liftLeft = hardwareMap.dcMotor.get("liftLeft"); liftRight = hardwareMap.dcMotor.get("liftRight"); liftLeft.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); liftLeft.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER); liftRight.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); liftRight.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER); /* Initialize Servos */ dispenser = hardwareMap.servo.get("dispenser"); beaconAngleLeft = hardwareMap.servo.get("beaconAngleLeft"); beaconAngleRight = hardwareMap.servo.get("beaconAngleRight"); forkliftLeft = hardwareMap.servo.get("forkliftLeft"); forkliftRight = hardwareMap.servo.get("forkliftRight"); /* Initialize Sensors */ //colorSensor = hardwareMap.colorSensor.get("colorSensor"); //leftTouchSensor = hardwareMap.touchSensor.get("leftTouchSensor"); //rightTouchSensor = hardwareMap.touchSensor.get("rightTouchSensor"); //Display completion message telemetry.addData("Status", "Initialized"); /* Steps to Autonomous: Fire starting balls Drive to beacon 1 Press beacon 1 Drive to beacon 2 Press beacon 2 Drive to center and park while knocking ball off */ frontLeft.setPower(1); frontRight.setPower(-1); sleep(INITIAL_FORWARD); frontLeft.setPower(0); frontRight.setPower(0); dispenserLeft.setPower(1); dispenserRight.setPower(1); sleep(RAMP_UP); intake.setPower(1); midtake.setPower(1); dispenser.setPosition(0); sleep(500); dispenser.setPosition(.45); sleep(150); dispenser.setPosition(0); sleep(500); dispenser.setPosition(.45); intake.setPower(0); midtake.setPower(0); dispenserRight.setPower(0); dispenserLeft.setPower(0); if (isRed) { frontLeft.setPower(1); frontRight.setPower(1); sleep(TURN_ONE); frontRight.setPower(-1); } else { frontLeft.setPower(-1); frontRight.setPower(-1); sleep(TURN_ONE); frontLeft.setPower(1); } sleep(FORWARD_TWO); if (!isRed) { frontLeft.setPower(-1); sleep(TURN_TWO); frontLeft.setPower(1); } else { frontRight.setPower(1); sleep(TURN_TWO); frontRight.setPower(-1); } sleep(FORWARD_THREE); frontLeft.setPower(0); frontRight.setPower(0); if (!isRed) { if (colorSensor.red()<colorSensor.blue()) { beaconAngleRight.setPosition(Math.abs(.5-BEACON_RIGHT_IN)); } else { frontLeft.setPower(1); frontRight.setPower(-1); sleep(COLOR_CORRECTION); didColorCorrection = true; frontLeft.setPower(0); frontRight.setPower(0); beaconAngleRight.setPosition(Math.abs(.5-BEACON_RIGHT_IN)); } } else { if (colorSensor.red()>colorSensor.blue()) { beaconAngleLeft.setPosition(Math.abs(.5-BEACON_LEFT_IN)); } else { frontLeft.setPower(1); frontRight.setPower(-1); sleep(COLOR_CORRECTION); didColorCorrection = true; frontLeft.setPower(0); frontRight.setPower(0); beaconAngleLeft.setPosition(Math.abs(.5-BEACON_LEFT_IN)); } } frontLeft.setPower(1); frontRight.setPower(-1); if (didColorCorrection) { sleep(FORWARD_FOUR-COLOR_CORRECTION); } else { sleep(FORWARD_FOUR); } frontLeft.setPower(0); frontRight.setPower(0); if (!isRed) { if (colorSensor.red()<colorSensor.blue()) { beaconAngleRight.setPosition(Math.abs(.5-BEACON_RIGHT_IN)); } else { frontLeft.setPower(1); frontRight.setPower(-1); sleep(COLOR_CORRECTION); frontLeft.setPower(0); frontRight.setPower(0); beaconAngleRight.setPosition(Math.abs(.5-BEACON_RIGHT_IN)); } } else { if (colorSensor.red()>colorSensor.blue()) { beaconAngleLeft.setPosition(Math.abs(.5-BEACON_LEFT_IN)); } else { frontLeft.setPower(1); frontRight.setPower(-1); sleep(COLOR_CORRECTION); frontLeft.setPower(0); frontRight.setPower(0); beaconAngleLeft.setPosition(Math.abs(.5-BEACON_LEFT_IN)); } } frontLeft.setPower(1); frontRight.setPower(1); sleep(TURN_THREE); frontRight.setPower(-1); sleep(FORWARD_FIVE); telemetry.addData("Status", "Run Time: " + runtime.toString()); /* This section is the short version of the autonomous for in case the other part doesn't work. It drives straight forward and knocks the cap ball off in the center. */ sleep(10000); frontLeft.setPower(1); frontRight.setPower(-1); sleep(4000); frontRight.setPower(0); frontLeft.setPower(0); sleep(10000); } }
NeonRD1/FTC772
ftc_app-master/TeamCode/src/main/java/org/firstinspires/ftc/teamcode/Autonomous.java
Java
gpl-3.0
11,732
/*root_check.c */ #include <ctype.h> #include <errno.h> #include <fcntl.h> #include <limits.h> #include <linux/input.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/statfs.h> #include <sys/types.h> #include <time.h> #include <unistd.h> #include <dirent.h> #include "common.h" #include "cutils/properties.h" #include "cutils/android_reboot.h" #include "install.h" #include "minui/minui.h" #include "minzip/DirUtil.h" #include "minzip/SysUtil.h" #include "roots.h" #include "ui.h" #include "screen_ui.h" #include "device.h" #include "minzip/Zip.h" #include "root_check.h" extern "C" { #include "cr32.h" #include "md5.h" } #define FILENAME_MAX 200 unsigned int key=15; bool checkResult = true; static const char *SYSTEM_ROOT = "/system/"; static char* file_to_check[]={ "supersu.apk", "superroot.apk", "superuser.apk", "busybox.apk"}; static char* file_to_pass[]={ "recovery-from-boot.p", "install-recovery.sh", "recovery_rootcheck", "build.prop", "S_ANDRO_SFL.ini", "recovery.sig" }; static const char *IMAGE_LOAD_PATH ="/tmp/rootcheck/"; static const char *TEMP_FILE_IN_RAM="/tmp/system_dencrypt"; static const char *TEMP_IMAGE_IN_RAM="/tmp/image_dencrypt"; static const char *CRC_COUNT_TMP="/tmp/crc_count"; static const char *FILE_COUNT_TMP="/tmp/file_count"; static const char *DYW_DOUB_TMP="/tmp/doub_check"; static const char *FILE_NEW_TMP="/tmp/list_new_file"; struct last_check_file{ int n_newfile; int n_lostfile; int n_modifyfile; int n_rootfile; int file_number_to_check; int expect_file_number; unsigned int file_count_check; unsigned int crc_count_check; }; static struct last_check_file*check_file_result; int root_to_check[MAX_ROOT_TO_CHECK]={0}; extern RecoveryUI* ui; img_name_t img_array[PART_MAX] = { #ifdef MTK_ROOT_PRELOADER_CHECK {"/dev/preloader", "preloader"}, #endif {"/dev/uboot", "uboot"}, {"/dev/bootimg", "bootimg"}, {"/dev/recovery", "recoveryimg"}, {"/dev/logo", "logo"}, }; img_name_t img_array_gpt[PART_MAX] = { #ifdef MTK_ROOT_PRELOADER_CHECK {"/dev/preloader", "preloader"}, #endif {"/dev/block/platform/mtk-msdc.0/by-name/lk", "uboot"}, {"/dev/block/platform/mtk-msdc.0/by-name/boot", "bootimg"}, {"/dev/block/platform/mtk-msdc.0/by-name/recovery", "recoveryimg"}, {"/dev/block/platform/mtk-msdc.0/by-name/logo", "logo"}, }; img_checksum_t computed_checksum[PART_MAX]; img_checksum_t expected_checksum[PART_MAX]; int check_map[MAX_FILES_IN_SYSTEM/INT_BY_BIT+1]; int check_modify[MAX_FILES_IN_SYSTEM/INT_BY_BIT+1]; static bool is_support_gpt_c(void) { int fd = open("/dev/block/platform/mtk-msdc.0/by-name/para", O_RDONLY); if (fd == -1) { return false; } else { close(fd); return true; } } static void set_bit(int x) { check_map[x>>SHIFT]|= 1<<(x&MASK); } static void clear_bit(int x) { check_map[x>>SHIFT]&= ~(1<<(x&MASK)); } static int test_bit(int x) { return check_map[x>>SHIFT]&(1<<(x&MASK)); } static void set_bit_m(int x) { check_modify[x>>SHIFT]|= 1<<(x&MASK); } static void clear_bit_m(int x) { check_modify[x>>SHIFT]&= ~(1<<(x&MASK)); } static int test_bit_m(int x) { return check_modify[x>>SHIFT]&(1<<(x&MASK)); } static int file_crc_check( const char* path, unsigned int* nCS, unsigned char *nMd5) { char buf[4*1024]; FILE *fp = 0; int rRead_count = 0; int i = 0; *nCS = 0; #ifdef MTK_ROOT_ADVANCE_CHECK MD5_CTX md5; MD5Init(&md5); memset(nMd5, 0, MD5_LENGTH); #endif struct stat st; memset(&st,0,sizeof(st)); if ( path == NULL ){ LOGE("file_crc_check-> %s is null", path); return -1; } if(lstat(path,&st)<0) { LOGE("\n %s does not exist,lsta fail", path); return 1; } if(S_ISLNK(st.st_mode)) { printf("%s is a link file,just pass\n", path); return 0; } fp = fopen(path, "r"); if( fp == NULL ) { LOGE("\nfile_crc_check->path:%s ,fp is null", path); LOGE("\nfopen fail reason is %s",strerror(errno)); return -1; } while(!feof(fp)) { memset(buf, 0x0, sizeof(buf)); rRead_count = fread(buf, 1, sizeof(buf), fp); if( rRead_count <=0 ) break; #ifdef MTK_ROOT_NORMAL_CHECK *nCS += crc32(*nCS, buf, rRead_count); #endif #ifdef MTK_ROOT_ADVANCE_CHECK MD5Update(&md5,(unsigned char*)buf, rRead_count); #endif } #ifdef MTK_ROOT_ADVANCE_CHECK MD5Final(&md5, nMd5); #endif fclose(fp); return 0; } static int clear_selinux_file(char* path) { int found=0; int ret=0; FILE *fp_info; FILE *fp_new; char buf[512]; char p_name[256]; unsigned char p_md[MD5_LENGTH*2]; char *p_cmp_name; unsigned int p_size; int p_number; struct stat statbuf; fp_info = fopen(TEMP_FILE_IN_RAM, "r"); if(fp_info) { if(fgets(buf, sizeof(buf), fp_info) != NULL) { while(fgets(buf, sizeof(buf), fp_info)) { if (sscanf(buf, "%d %s %u %s", &p_number,p_name,&p_size,p_md) == 4) { //TODO:path[0] will be '\0' sometimes, and it should be '/' path[0] = '/'; if(strstr(p_name,path)!=NULL) { p_cmp_name=strstr(p_name,path); if(strcmp(p_cmp_name,path)==0) { found=1; clear_bit(p_number); } } } } if(found==0) { LOGE("found a new file,filename is %s",path); check_file_result->n_newfile+=1; if(access(FILE_NEW_TMP,0)==-1) { int fd_new=creat(FILE_NEW_TMP,0755); } fp_new=fopen(FILE_NEW_TMP, "a"); if(fp_new) { fprintf(fp_new,"%s\n",path); } else { LOGE("open %s error,error reason is %s\n",FILE_NEW_TMP,strerror(errno)); return CHECK_ADD_NEW_FILE; } checkResult=false; fclose(fp_info); fclose(fp_new); return CHECK_ADD_NEW_FILE; } } } else { LOGE("open %s error,error reason is %s\n",TEMP_FILE_IN_RAM,strerror(errno)); return CHECK_NO_KEY; } fclose(fp_info); return CHECK_PASS; } static int clear_selinux_dir(char const* path) { int ret=0; FILE *fp_info; FILE *fp_new; char buf[512]; char p_name[256]; unsigned char p_md[MD5_LENGTH*2]; char *p_cmp_name; unsigned int p_size; int p_number; struct stat statbuf; fp_info = fopen(TEMP_FILE_IN_RAM, "r"); if(fp_info) { if(fgets(buf, sizeof(buf), fp_info) != NULL) { while(fgets(buf, sizeof(buf), fp_info)) { if (sscanf(buf, "%d %s %u %s", &p_number,p_name,&p_size,p_md) == 4) { //TODO:path[0] will be '\0' sometimes, and it should be '/' //path[0] = '/'; if(strstr(p_name,path)!=NULL) { p_cmp_name=strstr(p_name,path); LOGE("%s file is selinux protected,just pass\n",p_cmp_name); clear_bit(p_number); } else { //LOGE("not found %s in orignal file,please check!",path); continue; } } } } } else { LOGE("open %s error,error reason is %s\n",TEMP_FILE_IN_RAM,strerror(errno)); return CHECK_NO_KEY; } fclose(fp_info); return CHECK_PASS; } static int check_reall_file(char* path, int nCS, char* nMd5) { int found=0; int ret=0; FILE *fp_info; FILE *fp_new; char buf[512]; char p_name[256]; unsigned char p_md[MD5_LENGTH*2]; char *p_cmp_name; unsigned int p_size; int p_number; struct stat statbuf; fp_info = fopen(TEMP_FILE_IN_RAM, "r"); if(fp_info) { if(fgets(buf, sizeof(buf), fp_info) != NULL) { //while(fgets(buf, sizeof(buf), fp_info)&&!found) while(fgets(buf, sizeof(buf), fp_info)) { memset(p_md, '0', sizeof(p_md)); if (sscanf(buf, "%d %s %u %s", &p_number,p_name,&p_size,p_md) == 4) { //TODO: can not get correct p_name from sscanf(), so use below instead char *p1 = strchr(buf, '\t'); char *p2 = strchr(p1+1, '\t'); if(p1&&p2) memcpy(p_name, p1+1, p2-p1-1); //TODO:path[0] will be '\0' sometimes, and it should be '/' path[0] = '/'; if(strstr(p_name,path)!=NULL) { p_cmp_name=strstr(p_name,path); if(strcmp(p_cmp_name,path)==0) { found=1; int rettmp = 0; clear_bit(p_number); #ifdef MTK_ROOT_NORMAL_CHECK if(p_size==nCS) { //printf("%s crc check pass\n",path); } else { printf("expected crc is %u\n",p_size); printf("computed crc is %u\n",nCS); printf("%s is modifyed\n",path); //fclose(fp_info); rettmp = CHECK_FILE_NOT_MATCH; } #endif #ifdef MTK_ROOT_ADVANCE_CHECK if(p_md[1]=='\0') p_md[1]='0'; hextoi_md5(p_md); if(memcmp(nMd5, p_md, MD5_LENGTH)==0) { //printf("%s md5 check pass\n",path); } else { #if 1 int i; for(i=0;i<16;i++) { printf("%02x",nMd5[i]); } for(i=0;i<16;i++) { printf("%02x", p_md[i]); } #endif LOGE("<<ERROR>>\n"); //check_file_result->n_modifyfile+=1; LOGE("Error:%s has been modified md5",path); ret=stat(path,&statbuf); if(ret != 0) { LOGE("Error:%s is not exist\n",path); } time_t modify=statbuf.st_mtime; ui->Print("on %s\n", ctime(&modify)); //fclose(fp_info); //return CHECK_FILE_NOT_MATCH; rettmp = CHECK_FILE_NOT_MATCH; } #endif if(rettmp){ check_file_result->n_modifyfile+=1; clear_bit_m(p_number); fclose(fp_info); return rettmp; } } } } } if(found==0) { LOGE("found a new file,filename is %s",path); check_file_result->n_newfile+=1; if(access(FILE_NEW_TMP,0)==-1) { int fd_new=creat(FILE_NEW_TMP,0755); } fp_new=fopen(FILE_NEW_TMP, "a"); if(fp_new) { fprintf(fp_new,"%s\n",path); } else { LOGE("open %s error,error reason is %s\n",FILE_NEW_TMP,strerror(errno)); return CHECK_ADD_NEW_FILE; } checkResult=false; fclose(fp_info); fclose(fp_new); return CHECK_ADD_NEW_FILE; } } } else { LOGE("open %s error,error reason is %s\n",TEMP_FILE_IN_RAM,strerror(errno)); return CHECK_NO_KEY; } fclose(fp_info); return CHECK_PASS; } static bool dir_check( char const*dir) { struct dirent *dp; DIR *d_fd; unsigned int nCS = 0; unsigned char nMd5[MD5_LENGTH]; char newdir[FILENAME_MAX]; int find_pass=0; if ((d_fd = opendir(dir)) == NULL) { if(strcmp(dir,"/system/")==0) { LOGE("open system dir fail,please check!\n"); return false; } else { LOGE("%s is selinux protected,this dir just pass!\n",dir); if(clear_selinux_dir(dir) != 0) { LOGE("clear selinux dir fail\n"); } return false; } } while ((dp = readdir(d_fd)) != NULL) { find_pass = 0; if (strcmp(dp->d_name, ".") == 0 || strcmp(dp->d_name, "..") == 0 || strcmp(dp->d_name,"lost+found")==0) continue; if (dp->d_type == DT_DIR){ memset(newdir, 0, FILENAME_MAX); strcpy(newdir, dir); strcat(newdir, dp->d_name); strcat(newdir, "/"); if(dir_check(newdir) == false){ //closedir(d_fd); continue; //return false; } }else{ int idx = 0; int idy = 0; memset(newdir, 0, FILENAME_MAX); strcpy(newdir, dir); strcat(newdir, dp->d_name); for(; idx < sizeof(file_to_check)/sizeof(char*); idx++){ if(strcmp(dp->d_name, file_to_check[idx]) == 0){ root_to_check[idx]=1; ui->Print("Dir_check---found a root File: %s\n",dp->d_name); } } for(; idy < sizeof(file_to_pass)/sizeof(char*); idy++){ if(strcmp(dp->d_name, file_to_pass[idy]) == 0){ printf("Dir_check---found a file to pass: %s\n",dp->d_name); find_pass=1; break; } } if(find_pass==0) { ui->Print("scanning **** %s ****\n",dp->d_name); if(0 == file_crc_check(newdir, &nCS, nMd5)){ if (check_reall_file(newdir, nCS, (char*)nMd5)!=0) { LOGE("Error:%s check fail\n",newdir); checkResult = false; } check_file_result->file_number_to_check++; }else if(1 == file_crc_check(newdir, &nCS, nMd5)) { LOGE("%s could be selinux protected\n",newdir); //closedir(d_fd) if (clear_selinux_file(newdir)!=0) { LOGE("Error:%s is a selinux file,clear bit fail\n",newdir); checkResult = false; } check_file_result->file_number_to_check++; continue; } else { LOGE("check %s error\n",newdir); closedir(d_fd); return false; } } } } closedir(d_fd); return true; } static int load_zip_file() { const char *FILE_COUNT_ZIP="file_count"; const char *CRC_COUNT_ZIP="crc_count"; const char *DOUBLE_DYW_CHECK="doub_check"; const char *ZIP_FILE_ROOT="/system/data/recovery_rootcheck"; //const char *ZIP_FILE_ROOT_TEMP="/system/recovery_rootcheck"; ZipArchive zip; //struct stat statbuf; int ret; int err=1; MemMapping map; if (sysMapFile(ZIP_FILE_ROOT, &map) != 0) { LOGE("failed to map file %s\n", ZIP_FILE_ROOT); return INSTALL_CORRUPT; } //ret=stat(ZIP_FILE_ROOT_TEMP,&statbuf); printf("load zip file from %s\n",ZIP_FILE_ROOT); err = mzOpenZipArchive(map.addr, map.length, &zip); if (err != 0) { LOGE("Can't open %s\n(%s)\n", ZIP_FILE_ROOT, err != -1 ? strerror(err) : "bad"); sysReleaseMap(&map); return CHECK_NO_KEY; } const ZipEntry* file_count = mzFindZipEntry(&zip,FILE_COUNT_ZIP); if (file_count== NULL) { mzCloseZipArchive(&zip); sysReleaseMap(&map); return CHECK_NO_KEY; } unlink(FILE_COUNT_TMP); int fd_file = creat(FILE_COUNT_TMP, 0755); if (fd_file< 0) { mzCloseZipArchive(&zip); LOGE("Can't make %s:%s\n", FILE_COUNT_TMP, strerror(errno)); sysReleaseMap(&map); return CHECK_NO_KEY; } bool ok_file= mzExtractZipEntryToFile(&zip, file_count, fd_file); close(fd_file); if (!ok_file) { LOGE("Can't copy %s\n", FILE_COUNT_ZIP); sysReleaseMap(&map); return CHECK_NO_KEY; } else { printf("%s is ok\n", FILE_COUNT_TMP); } const ZipEntry* crc_count = mzFindZipEntry(&zip,CRC_COUNT_ZIP); if (crc_count== NULL) { mzCloseZipArchive(&zip); sysReleaseMap(&map); return CHECK_NO_KEY; } unlink(CRC_COUNT_TMP); int fd_crc = creat(CRC_COUNT_TMP, 0755); if (fd_crc< 0) { mzCloseZipArchive(&zip); LOGE("Can't make %s\n", CRC_COUNT_TMP); sysReleaseMap(&map); return CHECK_NO_KEY; } bool ok_crc = mzExtractZipEntryToFile(&zip, crc_count, fd_crc); close(fd_crc); if (!ok_crc) { LOGE("Can't copy %s\n", CRC_COUNT_ZIP); sysReleaseMap(&map); return CHECK_NO_KEY; } else { printf("%s is ok\n", CRC_COUNT_TMP); } const ZipEntry* dcheck_crc = mzFindZipEntry(&zip,DOUBLE_DYW_CHECK); if (dcheck_crc== NULL) { mzCloseZipArchive(&zip); sysReleaseMap(&map); return CHECK_NO_KEY; } unlink(DYW_DOUB_TMP); int fd_d = creat(DYW_DOUB_TMP, 0755); if (fd_d< 0) { mzCloseZipArchive(&zip); LOGE("Can't make %s\n", DYW_DOUB_TMP); sysReleaseMap(&map); return CHECK_NO_KEY; } bool ok_d = mzExtractZipEntryToFile(&zip, dcheck_crc, fd_d); close(fd_d); if (!ok_d) { LOGE("Can't copy %s\n", DOUBLE_DYW_CHECK); sysReleaseMap(&map); return CHECK_NO_KEY; } else { printf("%s is ok\n", DYW_DOUB_TMP); } mzCloseZipArchive(&zip); sysReleaseMap(&map); return 0; } static char* decrypt_str(char *source,unsigned int key) { char buf[FILENAME_MAX]={0}; memset(buf, 0, FILENAME_MAX); int i; int j=0; int len=strlen(source); if(len%2 != 0) { printf("Error,sourcr encrypt filename length is odd"); return NULL; } int len2=len/2; for(i=0;i<len2;i++) { char c1=source[j]; char c2=source[j+1]; j=j+2; c1=c1-65; c2=c2-65; char b2=c2*16+c1; char b1=b2^key; buf[i]=b1; } buf[len2]='\0'; memset(source,0,len); strcpy(source,buf); return source; } static int load_image_encrypt_file() { FILE *fp_info; FILE *fp_tmp; char buf[512]; char p_name[512]; char p_img_size[128]; char *p_cmp_name=NULL; char p_crc[256]; char p_md5[256]; int p_number; int p_file_number; fp_info = fopen(CRC_COUNT_TMP, "r"); fp_tmp = fopen(TEMP_IMAGE_IN_RAM,"w+"); if(fp_tmp) { if(fp_info) { while (fgets(buf, sizeof(buf), fp_info)) { memset(p_md5, 0, sizeof(p_md5)); if (sscanf(buf,"%s %s %s %s",p_name,p_img_size,p_crc,p_md5) == 4) { char *p_pname=decrypt_str(p_name,key); char *p_pcrc=decrypt_str(p_crc,key); char *p_pmd5=decrypt_str(p_md5,key); char *p_pimgsize=decrypt_str(p_img_size,key); unsigned long crc; crc = strtoul(p_pcrc, (char **)NULL, 10); unsigned long img_size = strtoul(p_pimgsize, (char **)NULL, 10); //printf("p_pname %s,p_img_size %d,rcrc %u, p_pmd5 %s\n",p_pname,img_size,rcrc, p_pmd5); fprintf(fp_tmp,"%s\t%lu\t%lu\t%s\n",p_pname,img_size, crc, p_pmd5); } } } else { ui->Print("fopen error,error reason is %s\n",strerror(errno)); return -1; } } else { ui->Print("fopen error,error reason is %s\n",strerror(errno)); return CHECK_NO_KEY; } fclose(fp_info); fclose(fp_tmp); return 0; } static int load_system_encrypt_file() { FILE *fp_info; FILE *fp_tmp; char buf[512]; char p_name[512]; char *p_cmp_name=NULL; char p_crc[256]; char p_md5[256]; int p_number; int p_file_number; fp_info = fopen(FILE_COUNT_TMP, "r"); fp_tmp = fopen(TEMP_FILE_IN_RAM,"w+"); if(fp_tmp) { if(fp_info) { if (fgets(buf, sizeof(buf), fp_info) != NULL) { if (sscanf(buf, "%d %s %d", &p_number,p_name,&p_file_number) == 3) { fprintf(fp_tmp,"%d\t%s\t%d\n",p_number,p_name,p_file_number); } while (fgets(buf, sizeof(buf), fp_info)) { memset(p_md5, 0, sizeof(p_md5)); if (sscanf(buf, "%d %s %s %s", &p_number,p_name,p_crc,p_md5) == 4) { char *p_pname=decrypt_str(p_name,key); char *p_pcrc=decrypt_str(p_crc,key); char *p_pmd5=decrypt_str(p_md5,key); unsigned long crc; crc = strtoul(p_pcrc, (char **)NULL, 10); //printf("p_pname:%s, crc32:%s %lu %d %d %d\n", p_pname, p_pcrc, crc, sizeof(long), sizeof(long long), sizeof(unsigned int)); fprintf(fp_tmp,"%d\t%s\t%lu\t%s\n",p_number,p_pname,crc, p_pmd5); } } } } else { ui->Print("fopen error,error reason is %s\n",strerror(errno)); return -1; } } else { ui->Print("fopen error,error reason is %s\n",strerror(errno)); return CHECK_NO_KEY; } fclose(fp_info); fclose(fp_tmp); return 0; } static bool image_crc_check( char const*dir) { struct dirent *dp; DIR *d_fd; unsigned int nCS = 0; unsigned char nMd5[MD5_LENGTH]; if ((d_fd = opendir(dir)) == NULL) { LOGE("dir_check-<<<< %s not dir\n",dir); return false; } while ((dp = readdir(d_fd)) != NULL) { if (strcmp(dp->d_name, ".") == 0 || strcmp(dp->d_name, "..") == 0 || strcmp(dp->d_name,"lost+found")==0) continue; if (dp->d_type == DT_DIR){ char newdir[FILENAME_MAX]={0}; memset(newdir, 0, FILENAME_MAX); strcpy(newdir, dir); strcat(newdir, dp->d_name); strcat(newdir, "/"); if(dir_check(newdir) == false){ closedir(d_fd); return false; } }else{ char newdir[FILENAME_MAX]; int idx = 0; int idy = 0; memset(newdir, 0, FILENAME_MAX); strcpy(newdir, dir); strcat(newdir, dp->d_name); if(0 == file_crc_check(newdir, &nCS, nMd5)){ #ifdef MTK_ROOT_PRELOADER_CHECK if(strstr(newdir,"preloader")!=NULL) { computed_checksum[PRELOADER].crc32=nCS; memcpy(computed_checksum[PRELOADER].md5, nMd5, MD5_LENGTH); } #endif if(strstr(newdir,"bootimg")!=NULL) { computed_checksum[BOOTIMG].crc32=nCS; memcpy(computed_checksum[BOOTIMG].md5, nMd5, MD5_LENGTH); } if(strstr(newdir,"uboot")!=NULL) { computed_checksum[UBOOT].crc32=nCS; memcpy(computed_checksum[UBOOT].md5, nMd5, MD5_LENGTH); } if(strstr(newdir,"recovery")!=NULL) { computed_checksum[RECOVERYIMG].crc32=nCS; memcpy(computed_checksum[RECOVERYIMG].md5, nMd5, MD5_LENGTH); } if(strstr(newdir,"logo")!=NULL) { computed_checksum[LOGO].crc32=nCS; memcpy(computed_checksum[LOGO].md5, nMd5, MD5_LENGTH); } }else{ printf("%s function fail\n",__func__); closedir(d_fd); return false; } } } closedir(d_fd); return true; } static int list_root_file() { int idx=0; for(;idx<MAX_ROOT_TO_CHECK;idx++) { if(root_to_check[idx]==1) { check_file_result->n_rootfile+=1; ui->Print("found a root file,%s\n",file_to_check[idx]); } } return 0; } static int list_lost_file(int number) { FILE *fp_info; char buf[512]; char p_name[256]; char p_md[256]; int found=0; char *p_cmp_name=NULL; unsigned int p_size; int p_number; int idy=0; fp_info = fopen(TEMP_FILE_IN_RAM, "r"); if(fp_info) { if (fgets(buf, sizeof(buf), fp_info) != NULL) { while (fgets(buf, sizeof(buf), fp_info)) { if (sscanf(buf, "%d %s %u %s", &p_number,p_name,&p_size,p_md) == 4) { if(p_number==number) { p_cmp_name=strstr(p_name,"/system"); for(; idy < sizeof(file_to_pass)/sizeof(char*); idy++) { if(strstr(p_cmp_name, file_to_pass[idy]) != NULL) { printf("list lost file---found a file to pass: %s\n",p_cmp_name); //checkResult=true; //break; return 0; } } if(p_cmp_name != NULL) { check_file_result->n_lostfile+=1; ui->Print("Error:%s is lost\n",p_cmp_name); checkResult=false; } else { check_file_result->n_lostfile+=1; ui->Print("Error:%s is lost\n",p_name); checkResult=false; } found=1; break; } } } if(!found) { LOGE("Error:not found a lost file\n"); fclose(fp_info); return -1; } } } else { ui->Print("fopen error,error reason is %s\n",strerror(errno)); return -1; } fclose(fp_info); return 0; } static int image_copy( const char* path,int loop,const char* tem_name) { unsigned int nCS=0; char *temp_file; char buf[1024]; int rRead_count = 0; int idx = 0; int sum=0; if (path == NULL ){ LOGE("image_copy-> %s is null", path); return -1; } if (ensure_path_mounted(IMAGE_LOAD_PATH) != 0) { LOGE("Can't mount %s\n", IMAGE_LOAD_PATH); return -1; } if (mkdir(IMAGE_LOAD_PATH, 0700) != 0) { if (errno != EEXIST) { LOGE("Can't mkdir %s (%s)\n", IMAGE_LOAD_PATH, strerror(errno)); return -1; } } struct stat st; if (stat(IMAGE_LOAD_PATH, &st) != 0) { LOGE("failed to stat %s (%s)\n", IMAGE_LOAD_PATH, strerror(errno)); return -1; } if (!S_ISDIR(st.st_mode)) { LOGE("%s isn't a directory\n", IMAGE_LOAD_PATH); return -1; } if ((st.st_mode & 0777) != 0700) { LOGE("%s has perms %o\n", IMAGE_LOAD_PATH, st.st_mode); return -1; } if (st.st_uid != 0) { LOGE("%s owned by %lu; not root\n", IMAGE_LOAD_PATH, st.st_uid); return -1; } char copy_path[FILENAME_MAX]; memset(copy_path, 0, FILENAME_MAX); strcpy(copy_path, IMAGE_LOAD_PATH); strcat(copy_path, "/temp_"); strcat(copy_path, tem_name); char* buffer = (char*)malloc(1024); if (buffer == NULL) { LOGE("Failed to allocate buffer\n"); return -1; } size_t read; FILE* fin = fopen(path, "rb"); if (fin == NULL) { LOGE("Failed to open %s (%s)\n", path, strerror(errno)); return -1; } FILE* fout = fopen(copy_path, "wb"); if (fout == NULL) { LOGE("Failed to open %s (%s)\n", copy_path, strerror(errno)); return -1; } while ((read = fread(buffer, 1, 1024, fin)) > 0) { sum+=read; if(sum<loop) { if (fwrite(buffer, 1, read, fout) != read) { LOGE("Short write of %s (%s)\n", copy_path, strerror(errno)); return -1; } } else { int read_end=read+loop-sum; if (fwrite(buffer, 1, read_end, fout) != read_end) { LOGE("Short write of %s (%s)\n", copy_path, strerror(errno)); return -1; } break; } } free(buffer); if (fclose(fout) != 0) { LOGE("Failed to close %s (%s)\n", copy_path, strerror(errno)); return -1; } if (fclose(fin) != 0) { LOGE("Failed to close %s (%s)\n", path, strerror(errno)); return -1; } return 0; } static int list_new_file() { FILE *fp_new; struct stat statbuf; char buf[256]; if(access(FILE_NEW_TMP,0)==-1) { printf("%s is not exist\n",FILE_NEW_TMP); return 0; } fp_new= fopen(FILE_NEW_TMP, "r"); if(fp_new) { while (fgets(buf, sizeof(buf), fp_new)) { ui->Print("Error:%s is new ",buf); int ret=stat(buf,&statbuf); /* if(ret != 0) { LOGE("Error:%s is not exist\n",buf); } */ time_t modify=statbuf.st_mtime; ui->Print("it is created on %s\n", ctime(&modify)); } } else { LOGE("open %s error,error reason is %s\n",FILE_NEW_TMP,strerror(errno)); return -1; } fclose(fp_new); return 0; } static bool remove_check_file(const char *file_name) { int ret = 0; ret = unlink(file_name); if (ret == 0) return true; if (ret < 0 && errno == ENOENT) return true; return false; } static bool remove_check_dir(const char *dir_name) { struct dirent *dp; DIR *d_fd; if ((d_fd = opendir(dir_name)) == NULL) { LOGE("dir_check-<<<< %s not dir\n",dir_name); return false; } while ((dp = readdir(d_fd)) != NULL) { if (strcmp(dp->d_name, ".") == 0 || strcmp(dp->d_name, "..") == 0 || strcmp(dp->d_name,"lost+found")==0) continue; if (dp->d_type == DT_DIR){ char newdir[FILENAME_MAX]={0}; memset(newdir, 0, FILENAME_MAX); strcpy(newdir, dir_name); strcat(newdir, dp->d_name); strcat(newdir, "/"); if(remove_check_dir(newdir) == false){ closedir(d_fd); return false; } }else{ char newdir[FILENAME_MAX]; int idx = 0; int idy = 0; memset(newdir, 0, FILENAME_MAX); strcpy(newdir, dir_name); strcat(newdir, dp->d_name); const char* to_remove_file; to_remove_file=newdir; if(!remove_check_file(to_remove_file)) { LOGE("Error:unlink %s fail\n",to_remove_file); } } } return true; } static int get_image_info() { FILE *fp_info; char buf[512]; char p_name[32]; unsigned int p_size; unsigned int p_c; unsigned char p_crc[MD5_LENGTH*2]; memset(expected_checksum, 0, sizeof(expected_checksum)); fp_info = fopen(TEMP_IMAGE_IN_RAM, "r"); if(fp_info) { while (fgets(buf, sizeof(buf), fp_info)) { memset(p_crc, 0, sizeof(p_crc)); //Z_DEBUG("%d %s\n", __LINE__, buf); if (sscanf(buf, "%s %d %u %s", p_name, &p_size, &p_c, p_crc) == 4) { //Z_DEBUG("%d %s\n", __LINE__, p_crc); hextoi_md5(p_crc); #ifdef MTK_ROOT_PRELOADER_CHECK if (!strcmp(p_name, "preloader.bin")) { expected_checksum[PRELOADER].size = p_size; expected_checksum[PRELOADER].crc32 = p_c; memcpy(expected_checksum[PRELOADER].md5, p_crc, MD5_LENGTH); } #endif if (!strcmp(p_name, "lk.bin")) { expected_checksum[UBOOT].size = p_size; expected_checksum[UBOOT].crc32 = p_c; memcpy(expected_checksum[UBOOT].md5, p_crc, MD5_LENGTH); } if (!strcmp(p_name, "boot.img")) { expected_checksum[BOOTIMG].size = p_size; expected_checksum[BOOTIMG].crc32 = p_c; memcpy(expected_checksum[BOOTIMG].md5, p_crc, MD5_LENGTH); } if (!strcmp(p_name, "recovery.img")) { expected_checksum[RECOVERYIMG].size = p_size; expected_checksum[RECOVERYIMG].crc32 = p_c; memcpy(expected_checksum[RECOVERYIMG].md5, p_crc, MD5_LENGTH); } if (!strcmp(p_name, "logo.bin")) { expected_checksum[LOGO].size = p_size; expected_checksum[LOGO].crc32 = p_c; memcpy(expected_checksum[LOGO].md5, p_crc, MD5_LENGTH); } } } } else { printf("%s function fail,open error reason is %s\n",__func__,strerror(errno)); return -1; } fclose(fp_info); return 0; } static int check_file_number_insystem(int file_number) { FILE *fp_info; char buf[512]; char p_name[128]; int p_number; int p_pnumber; fp_info = fopen(TEMP_FILE_IN_RAM, "r"); if(fp_info) { if (fgets(buf, sizeof(buf), fp_info) != NULL) { if (sscanf(buf, "%d %s %d", &p_pnumber,p_name, &p_number)== 3) { printf("p_name:%s,p_number : %d\n",p_name,p_number); if (!strcmp(p_name, "file_number_in_system_dayu")) { check_file_result->expect_file_number=p_number; //printf("func is %s,line is %d,p_number is %d,file_number is %d,n_modfyfile is %d,check_file_result->n_newfile is %d\n",__func__,__LINE__,p_number,file_number,check_file_result->n_modifyfile,check_file_result->n_newfile); #if 0 if((p_number==file_number)&&(check_file_result->n_lostfile==0)&&(check_file_result->n_newfile==0)) { ui->Print("\nSystem Dir File Number Check Pass"); fclose(fp_info); return 0; } else { printf("%s %d p_number:%d file_number:%d check_file_result->n_lostfile:%d check_file_result->n_newfile:%d\n", __func__, __LINE__, p_number, file_number, check_file_result->n_lostfile, check_file_result->n_newfile); ui->Print("\nSystem Dir File Number Check Fail\n"); fclose(fp_info); return CHECK_SYSTEM_FILE_NUM_ERR; } #endif } } } } else { ui->Print("fopen error,error reason is %s\n",strerror(errno)); return 1; } fclose(fp_info); return 0; } static void delete_unneed_file() { if(!remove_check_file(TEMP_FILE_IN_RAM)) { LOGE("unlink temp system crc file error\n"); } if(!remove_check_file(TEMP_IMAGE_IN_RAM)) { LOGE("unlink temp image crc file error\n"); } if(!remove_check_file(FILE_NEW_TMP)) { LOGE("unlink temp new file error\n"); } if(!remove_check_file(FILE_COUNT_TMP)) { LOGE("unlink temp new file error\n"); } if(!remove_check_file(DYW_DOUB_TMP)) { LOGE("unlink temp new file error\n"); } if(!remove_check_dir(IMAGE_LOAD_PATH)) { LOGE("unlink temp image dir error\n"); } } static int list_modify_file(int number) { FILE *fp_info; struct stat statbuf; char buf[512]; char p_name[256]; char p_md[256]; int found=0; char *p_cmp_name=NULL; unsigned int p_size; int p_number; fp_info = fopen(TEMP_FILE_IN_RAM, "r"); if(fp_info) { if (fgets(buf, sizeof(buf), fp_info) != NULL) { while (fgets(buf, sizeof(buf), fp_info)) { if (sscanf(buf,"%d %s %u %s", &p_number,p_name,&p_size,p_md) == 4) { if(p_number==number) { p_cmp_name=strstr(p_name,"/system"); if(p_cmp_name != NULL) { ui->Print("Error:%s has been modified",p_cmp_name); int ret=stat(p_cmp_name,&statbuf); if(ret != 0) { LOGE("Error:%s is not exist\n",p_cmp_name); } time_t modify=statbuf.st_mtime; ui->Print("on %s\n", ctime(&modify)); } else { ui->Print("Error:%s is modifyed\n",p_name); } found=1; break; } } } if(!found) { LOGE("Error:not found a lost file\n"); fclose(fp_info); return -1; } } } else { ui->Print("fopen error,error reason is %s\n",strerror(errno)); return -1; } fclose(fp_info); return 0; } static int encrypt_file_doub_check() { char buf[512]; FILE *fp_info; unsigned int file_count_crc; unsigned int crc_count_crc; unsigned int nCS = 0; unsigned char nMd5[MD5_LENGTH]; fp_info = fopen(DYW_DOUB_TMP, "r"); if(fp_info) { if(fgets(buf, sizeof(buf), fp_info) != NULL) { if (sscanf(buf,"%u %u", &file_count_crc,&crc_count_crc) == 2) { check_file_result->file_count_check=file_count_crc; check_file_result->crc_count_check=crc_count_crc; } else { ui->Print("double check file is error\n"); return CHECK_NO_KEY; } } else { ui->Print("double check file is null\n"); return CHECK_NO_KEY; } } else { LOGE("open %s error,error reason is %s\n",DYW_DOUB_TMP,strerror(errno)); return CHECK_NO_KEY; } if(0 == file_crc_check(FILE_COUNT_TMP, &nCS, nMd5)) { if(nCS!=check_file_result->file_count_check) { ui->Print("file count double check fail\n"); return CHECK_NO_KEY; } } if(0 == file_crc_check(CRC_COUNT_TMP, &nCS, nMd5)) { if(nCS != check_file_result->crc_count_check) { ui->Print("crc count double check fail\n"); return CHECK_NO_KEY; } } return 0; } int root_check(){ ui->SetBackground(RecoveryUI::ERASING); ui->SetProgressType(RecoveryUI::INDETERMINATE); ui->Print("Now check begins, please wait.....\n"); int per,cper; #ifdef MTK_ROOT_NORMAL_CHECK printf("use normal check\n"); #endif #ifdef MTK_ROOT_ADVANCE_CHECK printf("use advance check\n"); #endif check_file_result=(struct last_check_file*)malloc(sizeof(last_check_file)); if(ensure_path_mounted(SYSTEM_ROOT) != 0) { ui->Print("--mount System fail \n"); } memset(check_file_result,0,sizeof(last_check_file)); memset(check_map,0xff,sizeof(check_map)); memset(check_modify,0xff,sizeof(check_modify)); if(load_zip_file()) { ui->Print("load source zip file fail\n"); return CHECK_NO_KEY; } if(load_system_encrypt_file()) { ui->Print("load system encrypt file fail\n"); return CHECK_NO_KEY; } if(load_image_encrypt_file()) { ui->Print("load partition encrypt file fail\n"); return CHECK_NO_KEY; } if(encrypt_file_doub_check()) { ui->Print("encrypt file double check fail\n"); return CHECK_NO_KEY; } if(false == dir_check(SYSTEM_ROOT)) { checkResult = false; } check_file_result->file_number_to_check+=1; ui->Print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"); if (check_file_number_insystem(check_file_result->file_number_to_check)!=0) { checkResult=false; } if(list_new_file()) { LOGE("list new file error\n"); } if(list_root_file()) { LOGE("list root file error\n"); } for(cper=0;cper<check_file_result->file_number_to_check-1;cper++) { if(test_bit(cper)) { //checkResult=false; list_lost_file(cper); } } for(cper=0;cper<check_file_result->file_number_to_check-1;cper++) { if(!test_bit_m(cper)) { checkResult=false; list_modify_file(cper); } } if(check_file_result->n_newfile) { ui->Print("Error:found %d new files\n",check_file_result->n_newfile); } if(check_file_result->n_lostfile) { ui->Print("Error:found %d lost files\n",check_file_result->n_lostfile); } if(check_file_result->n_modifyfile) { ui->Print("Error:found %d modified files\n",check_file_result->n_modifyfile); } if(check_file_result->n_rootfile) { ui->Print("Error:found %d root files\n",check_file_result->n_rootfile); } if(ensure_path_unmounted(SYSTEM_ROOT) != 0) { LOGE("root_check function--unmount System fail \n"); } if(get_image_info()) { checkResult=false; } int i = 0; if(!is_support_gpt_c()) { printf("this is not gpt version"); for(i=0;i<PART_MAX;i++) { if(0 == image_copy(img_array[i].img_devname,expected_checksum[i].size,img_array[i].img_printname)) { printf("copy %s done\n", img_array[i].img_printname); } else { printf("copy %s error\n", img_array[i].img_printname); checkResult = false; } } } else { printf("this is gpt version"); for(i=0;i<PART_MAX;i++) { if(0 == image_copy(img_array_gpt[i].img_devname,expected_checksum[i].size,img_array_gpt[i].img_printname)) { printf("copy %s done\n", img_array_gpt[i].img_printname); } else { printf("copy %s error\n", img_array_gpt[i].img_printname); checkResult = false; } } } if(false == image_crc_check(IMAGE_LOAD_PATH)) { checkResult = false; return CHECK_IMAGE_ERR; } for(i=0;i<PART_MAX;i++) { #ifdef MTK_ROOT_NORMAL_CHECK if((expected_checksum[i].crc32==computed_checksum[i].crc32)&&(computed_checksum[i].crc32 != 0)) { printf("\n%s NORMAL check Pass", img_array[i].img_printname); } else { if(i==1) { checkResult=false; ui->Print("Error:%s NORMAL check Fail\n",img_array[i].img_printname); printf("except check sum is %u,compute checksum is %u\n",expected_checksum[i].crc32,computed_checksum[i].crc32); } } #endif #ifdef MTK_ROOT_ADVANCE_CHECK if(memcmp(expected_checksum[i].md5, computed_checksum[i].md5, MD5_LENGTH)==0) { printf("\n%s ADVANCE check Pass", img_array[i].img_printname); } else { if(i==1) { checkResult=false; ui->Print("Error:%s ADVANCE check Fail\n", img_array[i].img_printname); #if 1 char *nMd5 = (char*)expected_checksum[i].md5; char *p_md = (char*)computed_checksum[i].md5; int i; printf("e:"); for(i=0;i<16;i++) { printf("%02x",nMd5[i]); } printf("\n"); printf("c:"); for(i=0;i<16;i++) { printf("%02x", p_md[i]); } printf("\n"); #endif } } #endif } int m_root_check=0; for(;m_root_check<MAX_ROOT_TO_CHECK;m_root_check++) { root_to_check[m_root_check]=0; } delete_unneed_file(); free(check_file_result); if(checkResult) { return CHECK_PASS; } else { checkResult=true; return CHECK_FAIL; } }
MTK6580/walkie-talkie
ALPS.L1.MP6.V2_HEXING6580_WE_L/alps/bootable/recovery/root_check.cpp
C++
gpl-3.0
49,261
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_View * @subpackage Helper * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: HtmlElement.php 24399 2011-08-26 08:20:07Z padraic $ */ /** * @see Zend_View_Helper_Abstract */ require_once 'Zend/View/Helper/Abstract.php'; /** * @category Zend * @package Zend_View * @subpackage Helper * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ abstract class Zend_View_Helper_HtmlElement extends Zend_View_Helper_Abstract { /** * EOL character */ const EOL = "\n"; /** * The tag closing bracket * * @var string */ protected $_closingBracket = null; /** * Get the tag closing bracket * * @return string */ public function getClosingBracket() { if (!$this->_closingBracket) { if ($this->_isXhtml()) { $this->_closingBracket = ' />'; } else { $this->_closingBracket = '>'; } } return $this->_closingBracket; } /** * Is doctype XHTML? * * @return boolean */ protected function _isXhtml() { $doctype = $this->view->doctype(); return $doctype->isXhtml(); } /** * Is doctype strict? * * @return boolean */ protected function _isStrictDoctype() { $doctype = $this->view->doctype(); return $doctype->isStrict(); } /** * Converts an associative array to a string of tag attributes. * * @access public * * @param array $attribs From this array, each key-value pair is * converted to an attribute name and value. * * @return string The XHTML for the attributes. */ protected function _htmlAttribs($attribs) { $xhtml = ''; foreach ((array)$attribs as $key => $val) { $key = $this->view->escape($key); if (('on' == substr($key, 0, 2)) || ('constraints' == $key)) { // Don't escape event attributes; _do_ substitute double quotes with singles if (!is_scalar($val)) { // non-scalar data should be cast to JSON first require_once 'Zend/Json.php'; $val = Zend_Json::encode($val); } // Escape single quotes inside event attribute values. // This will create html, where the attribute value has // single quotes around it, and escaped single quotes or // non-escaped double quotes inside of it $val = str_replace('\'', '&#39;', $val); } else { if (is_array($val)) { $val = implode(' ', $val); } $val = $this->view->escape($val); } if ('id' == $key) { $val = $this->_normalizeId($val); } if (strpos($val, '"') !== false) { $xhtml .= " $key='$val'"; } else { $xhtml .= " $key=\"$val\""; } } return $xhtml; } /** * Normalize an ID * * @param string $value * @return string */ protected function _normalizeId($value) { if (strstr($value, '[')) { if ('[]' == substr($value, -2)) { $value = substr($value, 0, strlen($value) - 2); } $value = trim($value, ']'); $value = str_replace('][', '-', $value); $value = str_replace('[', '-', $value); } return $value; } }
jvianney/SwiftHR
Zend/View/Helper/HtmlElement.php
PHP
gpl-3.0
4,330
<?php namespace Neos\Neos\TYPO3CR\Transformations; /* * This file is part of the Neos.Neos package. * * (c) Contributors of the Neos Project - www.neos.io * * This package is Open Source Software. For the full copyright and license * information, please view the LICENSE file which was distributed with this * source code. */ use Doctrine\Common\Persistence\ObjectManager; use Neos\Flow\Annotations as Flow; use Neos\Flow\Persistence\PersistenceManagerInterface; use Neos\Flow\ResourceManagement\ResourceManager; use Neos\Media\Domain\Model\ImageInterface; use Neos\Media\Domain\Model\ImageVariant; use Neos\Media\Domain\Repository\AssetRepository; use Neos\Media\TypeConverter\ProcessingInstructionsConverter; use Neos\ContentRepository\Domain\Model\NodeData; use Neos\ContentRepository\Migration\Transformations\AbstractTransformation; /** * Convert serialized (old resource management) ImageVariants to new ImageVariants. */ class ImageVariantTransformation extends AbstractTransformation { /** * @Flow\Inject * @var AssetRepository */ protected $assetRepository; /** * @Flow\Inject * @var ResourceManager */ protected $resourceManager; /** * @Flow\Inject * @var ProcessingInstructionsConverter */ protected $processingInstructionsConverter; /** * @Flow\Inject * @var PersistenceManagerInterface */ protected $persistenceManager; /** * Doctrine's Entity Manager. Note that "ObjectManager" is the name of the related interface. * * @Flow\Inject * @var ObjectManager */ protected $entityManager; /** * @param NodeData $node * @return boolean */ public function isTransformable(NodeData $node) { return true; } /** * Change the property on the given node. * * @param NodeData $node * @return void */ public function execute(NodeData $node) { foreach ($node->getNodeType()->getProperties() as $propertyName => $propertyConfiguration) { if (isset($propertyConfiguration['type']) && ($propertyConfiguration['type'] === ImageInterface::class || preg_match('/array\<.*\>/', $propertyConfiguration['type']))) { if (!isset($nodeProperties)) { $nodeRecordQuery = $this->entityManager->getConnection()->prepare('SELECT properties FROM typo3_typo3cr_domain_model_nodedata WHERE persistence_object_identifier=?'); $nodeRecordQuery->execute([$this->persistenceManager->getIdentifierByObject($node)]); $nodeRecord = $nodeRecordQuery->fetch(\PDO::FETCH_ASSOC); $nodeProperties = unserialize($nodeRecord['properties']); } if (!isset($nodeProperties[$propertyName]) || empty($nodeProperties[$propertyName])) { continue; } if ($propertyConfiguration['type'] === ImageInterface::class) { $adjustments = array(); $oldVariantConfiguration = $nodeProperties[$propertyName]; if (is_array($oldVariantConfiguration)) { foreach ($oldVariantConfiguration as $variantPropertyName => $property) { switch (substr($variantPropertyName, 3)) { case 'originalImage': /** * @var $originalAsset Image */ $originalAsset = $this->assetRepository->findByIdentifier($this->persistenceManager->getIdentifierByObject($property)); break; case 'processingInstructions': $adjustments = $this->processingInstructionsConverter->convertFrom($property, 'array'); break; } } $nodeProperties[$propertyName] = null; if (isset($originalAsset)) { $stream = $originalAsset->getResource()->getStream(); if ($stream === false) { continue; } fclose($stream); $newImageVariant = new ImageVariant($originalAsset); foreach ($adjustments as $adjustment) { $newImageVariant->addAdjustment($adjustment); } $originalAsset->addVariant($newImageVariant); $this->assetRepository->update($originalAsset); $nodeProperties[$propertyName] = $this->persistenceManager->getIdentifierByObject($newImageVariant); } } } elseif (preg_match('/array\<.*\>/', $propertyConfiguration['type'])) { if (is_array($nodeProperties[$propertyName])) { $convertedValue = []; foreach ($nodeProperties[$propertyName] as $entryValue) { if (!is_object($entryValue)) { continue; } $stream = $entryValue->getResource()->getStream(); if ($stream === false) { continue; } fclose($stream); $existingObjectIdentifier = null; try { $existingObjectIdentifier = $this->persistenceManager->getIdentifierByObject($entryValue); if ($existingObjectIdentifier !== null) { $convertedValue[] = $existingObjectIdentifier; } } catch (\Exception $exception) { } } $nodeProperties[$propertyName] = $convertedValue; } } } } if (isset($nodeProperties)) { $nodeUpdateQuery = $this->entityManager->getConnection()->prepare('UPDATE typo3_typo3cr_domain_model_nodedata SET properties=? WHERE persistence_object_identifier=?'); $nodeUpdateQuery->execute([serialize($nodeProperties), $this->persistenceManager->getIdentifierByObject($node)]); } } }
hhoechtl/neos-development-collection
Neos.Neos/Classes/TYPO3CR/Transformations/ImageVariantTransformation.php
PHP
gpl-3.0
6,680
/* * Copyright (C) 2013 The OmniROM Project * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.android.systemui.tuner; import android.content.Context; import android.content.res.TypedArray; import android.preference.Preference; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.TextView; import com.android.systemui.R; public class SeekBarPreference extends Preference implements OnSeekBarChangeListener { public static int maximum = 100; public static int interval = 5; private TextView monitorBox; private SeekBar bar; int currentValue = 100; private OnPreferenceChangeListener changer; public SeekBarPreference(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected View onCreateView(ViewGroup parent) { View layout = View.inflate(getContext(), R.layout.qs_slider_preference, null); monitorBox = (TextView) layout.findViewById(R.id.monitor_box); bar = (SeekBar) layout.findViewById(R.id.seek_bar); bar.setProgress(currentValue); monitorBox.setText(String.valueOf(currentValue) + "%"); bar.setOnSeekBarChangeListener(this); return layout; } public void setInitValue(int progress) { currentValue = progress; } @Override protected Object onGetDefaultValue(TypedArray a, int index) { // TODO Auto-generated method stub return super.onGetDefaultValue(a, index); } @Override public void setOnPreferenceChangeListener( OnPreferenceChangeListener onPreferenceChangeListener) { changer = onPreferenceChangeListener; super.setOnPreferenceChangeListener(onPreferenceChangeListener); } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { progress = Math.round(((float) progress) / interval) * interval; currentValue = progress; monitorBox.setText(String.valueOf(progress) + "%"); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { changer.onPreferenceChange(this, Integer.toString(currentValue)); } }
OmniEvo/android_frameworks_base
packages/SystemUI/src/com/android/systemui/tuner/SeekBarPreference.java
Java
gpl-3.0
3,019
 using System; using System.Web; using System.Web.Routing; using System.Drawing; using System.Drawing.Imaging; using Meridian59.Files.BGF; namespace Meridian59.BgfService { /// <summary> /// /// </summary> public class FileRouteHandler : IRouteHandler { public FileRouteHandler() { } public IHttpHandler GetHttpHandler(RequestContext requestContext) { return new FileHttpHandler(); } } /// <summary> /// Provides contents from BGF file. This includes meta data /// like offsets and hotspots as well as frame images as PNG or BMP. /// </summary> public class FileHttpHandler : IHttpHandler { /// <summary> /// Handles the HTTP request /// </summary> /// <param name="context"></param> public void ProcessRequest(HttpContext context) { HttpResponse response = context.Response; // -------------------------------------------------------------------------------------------- // 1) PARSE URL PARAMETERS // -------------------------------------------------------------------------------------------- // read parameters from url-path (see Global.asax): RouteValueDictionary parms = context.Request.RequestContext.RouteData.Values; string parmFile = parms.ContainsKey("file") ? (string)parms["file"] : null; string parmReq = parms.ContainsKey("req") ? (string)parms["req"] : null; string parm1 = parms.ContainsKey("parm1") ? (string)parms["parm1"] : null; string parm2 = parms.ContainsKey("parm2") ? (string)parms["parm2"] : null; string parm3 = parms.ContainsKey("parm3") ? (string)parms["parm3"] : null; BgfCache.Entry entry; // no filename or request type if (String.IsNullOrEmpty(parmFile) || !BgfCache.GetBGF(parmFile, out entry) || String.IsNullOrEmpty(parmReq)) { context.Response.StatusCode = 404; return; } // set cache behaviour context.Response.Cache.SetCacheability(HttpCacheability.Public); context.Response.Cache.VaryByParams["*"] = false; context.Response.Cache.SetLastModified(entry.LastModified); // -------------------------------------------------------------------------------------------- // FRAME IMAGE // -------------------------------------------------------------------------------------------- if (parmReq == "frame") { ushort index; byte palette = 0; Byte.TryParse(parm3, out palette); // try to parse index and palette and validate range if (!UInt16.TryParse(parm2, out index) || index >= entry.Bgf.Frames.Count) { context.Response.StatusCode = 404; return; } // create BMP (256 col) or PNG (32-bit) or return raw pixels (8bit indices) if (parm1 == "bmp") { response.ContentType = "image/bmp"; response.AddHeader( "Content-Disposition", "inline; filename=" + entry.Bgf.Filename + "-" + index.ToString() + ".bmp"); Bitmap bmp = entry.Bgf.Frames[index].GetBitmap(palette); bmp.Save(context.Response.OutputStream, ImageFormat.Bmp); bmp.Dispose(); } else if (parm1 == "png") { response.ContentType = "image/png"; response.AddHeader( "Content-Disposition", "inline; filename=" + entry.Bgf.Filename + "-" + index.ToString() + ".png"); Bitmap bmp = entry.Bgf.Frames[index].GetBitmapA8R8G8B8(palette); bmp.Save(context.Response.OutputStream, ImageFormat.Png); bmp.Dispose(); } else if (parm1 == "bin") { response.ContentType = "application/octet-stream"; response.AddHeader( "Content-Disposition", "attachment; filename=" + entry.Bgf.Filename + "-" + index.ToString() + ".bin"); byte[] pixels = entry.Bgf.Frames[index].PixelData; context.Response.OutputStream.Write(pixels, 0, pixels.Length); } else context.Response.StatusCode = 404; } // -------------------------------------------------------------------------------------------- // JSON META DATA // -------------------------------------------------------------------------------------------- else if (parmReq == "meta") { // set response type response.ContentType = "application/json"; response.ContentEncoding = new System.Text.UTF8Encoding(false); response.AddHeader("Content-Disposition", "inline; filename=" + entry.Bgf.Filename + ".json"); // unix timestamp long stamp = (entry.LastModified.Ticks - 621355968000000000) / 10000000; ///////////////////////////////////////////////////////////// response.Write("{\"file\":\""); response.Write(entry.Bgf.Filename); response.Write("\",\"size\":"); response.Write(entry.Size.ToString()); response.Write(",\"modified\":"); response.Write(stamp.ToString()); response.Write(",\"shrink\":"); response.Write(entry.Bgf.ShrinkFactor.ToString()); response.Write(",\"frames\":["); for (int i = 0; i < entry.Bgf.Frames.Count; i++) { BgfBitmap frame = entry.Bgf.Frames[i]; if (i > 0) response.Write(','); response.Write("{\"w\":"); response.Write(frame.Width.ToString()); response.Write(",\"h\":"); response.Write(frame.Height.ToString()); response.Write(",\"x\":"); response.Write(frame.XOffset.ToString()); response.Write(",\"y\":"); response.Write(frame.YOffset.ToString()); response.Write(",\"hs\":["); for (int j = 0; j < frame.HotSpots.Count; j++) { BgfBitmapHotspot hs = frame.HotSpots[j]; if (j > 0) response.Write(','); response.Write("{\"i\":"); response.Write(hs.Index.ToString()); response.Write(",\"x\":"); response.Write(hs.X.ToString()); response.Write(",\"y\":"); response.Write(hs.Y.ToString()); response.Write('}'); } response.Write("]}"); } response.Write("],\"groups\":["); for (int i = 0; i < entry.Bgf.FrameSets.Count; i++) { BgfFrameSet group = entry.Bgf.FrameSets[i]; if (i > 0) response.Write(','); response.Write('['); for (int j = 0; j < group.FrameIndices.Count; j++) { if (j > 0) response.Write(','); response.Write(group.FrameIndices[j].ToString()); } response.Write(']'); } response.Write("]}"); } // -------------------------------------------------------------------------------------------- // INVALID // -------------------------------------------------------------------------------------------- else { context.Response.StatusCode = 404; return; } } public bool IsReusable { get { return true; } } } }
MorbusM59/meridian59-dotnet
Meridian59.BgfService/App_Code/FileHttpHandler.cs
C#
gpl-3.0
8,579
<?php require('../core.php'); $act=explode('/',$_REQUEST['action']); $db=$app->conn[0]; $tbl='tbl_grupo'; switch($act[0]){ case 'create': if($app->acl(103)){ $record = json_decode(html_entity_decode(file_get_contents('php://input'),ENT_COMPAT,'utf-8'),true); if($db->AutoExecute($tbl,$record,'INSERT')){ $json['success']=true; }else{ $json['success']=false; $json['msg']=$db->ErrorMsg(); } }else{ $json['success']=false; $json['msg']='Falta de permisos para realizar esta accion'; } break; case 'read': $json=array(); $json['success']=true; $json['data']=array(); $sql="SELECT * FROM {$tbl}"; $rs=$db->Execute($sql); while (!$rs->EOF) { $json['data'][]=$rs->fields; $rs->MoveNext(); } break; case 'update': if($app->acl(103)){ $record = json_decode(html_entity_decode(file_get_contents('php://input'),ENT_COMPAT,'utf-8'),true); if($db->AutoExecute($tbl,$record,'UPDATE',"id={$act[1]}")){ $json['success']=true; }else{ $json['success']=false; $json['msg']=$db->ErrorMsg(); } }else{ $json['success']=false; $json['msg']='Falta de permisos para realizar esta accion'; } break; case 'destroy': if($app->acl(103)){ $rw=$db->GetRow("SELECT * FROM {$tbl} WHERE id={$act[1]}"); $rs=$db->Execute("DELETE FROM {$tbl} WHERE id={$act[1]}"); $json['success']=true; }else{ $json['success']=false; $json['msg']='Falta de permisos para realizar esta accion'; } break; } echo json_encode($json); ?>
openvinci/openvinci
data/group.php
PHP
gpl-3.0
1,942
/* * Copyright (C) 2015 Max Planck Institute for Psycholinguistics * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ function init_cmdi() { $("a.toggle").click(function () { $(this).parent().parent().toggleClass('collapsed'); $(this).parent().parent().toggleClass('expanded'); }); } function expand_highlighted_cmdi() { $(".searchword").parents('.IMDI_group.cmdi').removeClass('collapsed'); $(".searchword").parents('.IMDI_group.cmdi').addClass('expanded'); } $(document).ready(init_cmdi);
TheLanguageArchive/ASV
metadata-browser-hybrid/src/main/java/nl/mpi/metadatabrowser/services/cmdi/impl/res/cmdi2html.js
JavaScript
gpl-3.0
1,134
package com.example.channelmanager; /** * Created by Administrator on 2017/2/7. * 频道列表 */ public class ProjectChannelBean { private String topicid; // 设置该标签是否可编辑,如果出现在我的频道中,且值为1,则可在右上角显示删除按钮 private int editStatus; private String cid; private String tname; private String ename; // 标签类型,显示是我的频道还是更多频道 private int tabType; private String tid; private String column; public ProjectChannelBean(){} public ProjectChannelBean(String tname, String tid){ this.tname = tname; this.tid = tid; } public ProjectChannelBean(String tname, String column, String tid){ this.tname = tname; this.column = column; this.tid = tid; } public String getTname() { return tname; } public void setTname(String tname) { this.tname = tname; } public int getTabType() { return tabType; } public void setTabType(int tabType) { this.tabType = tabType; } public int getEditStatus() { return editStatus; } public void setEditStatus(int editStatus) { this.editStatus = editStatus; } public String getTopicid() { return topicid; } public void setTopicid(String topicid) { this.topicid = topicid; } public String getCid() { return cid; } public void setCid(String cid) { this.cid = cid; } public String getEname() { return ename; } public void setEname(String ename) { this.ename = ename; } public String getTid() { return tid; } public void setTid(String tid) { this.tid = tid; } public String getColumn() { return column; } public void setColumn(String column) { this.column = column; } }
liaozhoubei/NetEasyNews
channelmanager/src/main/java/com/example/channelmanager/ProjectChannelBean.java
Java
gpl-3.0
1,956
/** Template Controllers @module Templates */ /** The execute contract template @class [template] elements_executeContract @constructor */ Template['elements_executeContract'].onCreated(function(){ var template = this; // Set Defaults TemplateVar.set('sending', false); // show execute part if its a custom contract if(CustomContracts.findOne({address: template.data.address})) TemplateVar.set('executionVisible', true); // check address for code web3.eth.getCode(template.data.address, function(e, code) { if(!e && code.length > 2) { TemplateVar.set(template, 'hasCode', true); } }); }); Template['elements_executeContract'].helpers({ /** Reruns when the data context changes @method (reactiveContext) */ 'reactiveContext': function() { var contractInstance = web3.eth.contract(this.jsonInterface).at(this.address); var contractFunctions = []; var contractConstants = []; _.each(this.jsonInterface, function(func, i){ func = _.clone(func); // Walk throught the jsonInterface and extract functions and constants if(func.type == 'function') { func.contractInstance = contractInstance; func.inputs = _.map(func.inputs, Helpers.createTemplateDataFromInput); if(func.constant){ // if it's a constant contractConstants.push(func); } else { //if its a variable contractFunctions.push(func); } } }); TemplateVar.set('contractConstants', contractConstants); TemplateVar.set('contractFunctions', contractFunctions); } }); Template['elements_executeContract'].events({ /** Select a contract function @event 'change .select-contract-function */ 'change .select-contract-function': function(e, template){ TemplateVar.set('executeData', null); // change the inputs and data field TemplateVar.set('selectedFunction', _.find(TemplateVar.get('contractFunctions'), function(contract){ return contract.name === e.currentTarget.value; })); Tracker.afterFlush(function(){ $('.abi-input').trigger('change'); }); }, /** Click the show hide button @event click .toggle-visibility */ 'click .toggle-visibility': function(){ TemplateVar.set('executionVisible', !TemplateVar.get('executionVisible')); } }); /** The contract constants template @class [template] elements_executeContract_constant @constructor */ /** Formats the values for display @method formatOutput */ var formatOutput = function(val) { if(_.isArray(val)) return _.map(val, formatOutput); else { // stringify boolean if(_.isBoolean(val)) val = val ? 'YES' : 'NO'; // convert bignumber objects val = (_.isObject(val) && val.toString) ? val.toString(10) : val; return val; } }; Template['elements_executeContract_constant'].onCreated(function(){ var template = this; // initialize our input data prior to the first call TemplateVar.set('inputs', _.map(template.data.inputs, function(input) { return Helpers.addInputValue([input], input, {})[0]; })); // call the contract functions when data changes and on new blocks this.autorun(function() { // make reactive to the latest block EthBlocks.latest; // get args for the constant function var args = TemplateVar.get('inputs') || []; // add callback args.push(function(e, r) { if(!e) { var outputs = []; // single return value if(template.data.outputs.length === 1) { template.data.outputs[0].value = r; outputs.push(template.data.outputs[0]); // multiple return values } else { outputs = _.map(template.data.outputs, function(output, i) { output.value = r[i]; return output; }); } TemplateVar.set(template, 'outputs', outputs); } }); template.data.contractInstance[template.data.name].apply(null, args); }); }); Template['elements_executeContract_constant'].helpers({ /** Formats the value if its a big number or array @method (value) */ 'value': function() { return _.isArray(this.value) ? formatOutput(this.value) : [formatOutput(this.value)]; }, /** Figures out extra data @method (extra) */ 'extra': function() { var data = formatOutput(this); // 1000000000 if (data > 1400000000 && data < 1800000000 && Math.floor(data/1000) != data/1000) { return '(' + moment(data*1000).fromNow() + ')'; } if (data == 'YES') { return '<span class="icon icon-check"></span>'; } else if (data == 'NO') { return '<span class="icon icon-ban"></span>' } return; } }); Template['elements_executeContract_constant'].events({ /** React on user input on the constant functions @event change .abi-input, input .abi-input */ 'change .abi-input, input .abi-input': function(e, template) { var inputs = Helpers.addInputValue(template.data.inputs, this, e.currentTarget); TemplateVar.set('inputs', inputs); } }); /** The contract function template @class [template] elements_executeContract_function @constructor */ Template['elements_executeContract_function'].onCreated(function(){ var template = this; // change the amount when the currency unit is changed template.autorun(function(c){ var unit = EthTools.getUnit(); if(!c.firstRun) { TemplateVar.set('amount', EthTools.toWei(template.find('input[name="amount"]').value.replace(',','.'), unit)); } }); }); Template['elements_executeContract_function'].onRendered(function(){ // Run all inputs through formatter to catch bools this.$('.abi-input').trigger('change'); }); Template['elements_executeContract_function'].helpers({ 'reactiveDataContext': function(){ if(this.inputs.length === 0) TemplateVar.set('executeData', this.contractInstance[this.name].getData()); } }); Template['elements_executeContract_function'].events({ /** Set the amount while typing @event keyup input[name="amount"], change input[name="amount"], input input[name="amount"] */ 'keyup input[name="amount"], change input[name="amount"], input input[name="amount"]': function(e, template){ var wei = EthTools.toWei(e.currentTarget.value.replace(',','.')); TemplateVar.set('amount', wei || '0'); }, /** React on user input on the execute functions @event change .abi-input, input .abi-input */ 'change .abi-input, input .abi-input': function(e, template) { var inputs = Helpers.addInputValue(template.data.inputs, this, e.currentTarget); TemplateVar.set('executeData', template.data.contractInstance[template.data.name].getData.apply(null, inputs)); }, /** Executes a transaction on contract @event click .execute */ 'click .execute': function(e, template){ var to = template.data.contractInstance.address, gasPrice = 50000000000, estimatedGas = undefined, /* (typeof mist == 'undefined')not working */ amount = TemplateVar.get('amount') || 0, selectedAccount = Helpers.getAccountByAddress(TemplateVar.getFrom('.execute-contract select[name="dapp-select-account"]', 'value')), data = TemplateVar.get('executeData'); var latestTransaction = Transactions.findOne({}, {sort: {timestamp: -1}}); if (latestTransaction && latestTransaction.gasPrice) gasPrice = latestTransaction.gasPrice; if(selectedAccount) { console.log('Providing gas: ', estimatedGas ,' + 100000'); if(selectedAccount.balance === '0') return GlobalNotification.warning({ content: 'i18n:wallet.send.error.emptyWallet', duration: 2 }); // The function to send the transaction var sendTransaction = function(estimatedGas){ TemplateVar.set('sending', true); // CONTRACT TX if(contracts['ct_'+ selectedAccount._id]) { // Load the accounts owned by user and sort by balance var accounts = EthAccounts.find({name: {$exists: true}}, {sort: {name: 1}}).fetch(); accounts.sort(Helpers.sortByBalance); // Looks for them among the wallet account owner var fromAccount = _.find(accounts, function(acc){ return (selectedAccount.owners.indexOf(acc.address)>=0); }) contracts['ct_'+ selectedAccount._id].execute.sendTransaction(to || '', amount || '', data || '', { from: fromAccount.address, gasPrice: gasPrice, gas: estimatedGas }, function(error, txHash){ TemplateVar.set(template, 'sending', false); console.log(error, txHash); if(!error) { console.log('SEND from contract', amount); addTransactionAfterSend(txHash, amount, selectedAccount.address, to, gasPrice, estimatedGas, data); FlowRouter.go('dashboard'); } else { // EthElements.Modal.hide(); GlobalNotification.error({ content: error.message, duration: 8 }); } }); // SIMPLE TX } else { web3.eth.sendTransaction({ from: selectedAccount.address, to: to, data: data, value: amount, gasPrice: gasPrice, gas: estimatedGas }, function(error, txHash){ TemplateVar.set(template, 'sending', false); console.log(error, txHash); if(!error) { console.log('SEND simple'); addTransactionAfterSend(txHash, amount, selectedAccount.address, to, gasPrice, estimatedGas, data); // FlowRouter.go('dashboard'); GlobalNotification.success({ content: 'i18n:wallet.send.transactionSent', duration: 2 }); } else { // EthElements.Modal.hide(); GlobalNotification.error({ content: error.message, duration: 8 }); } }); } }; sendTransaction(estimatedGas); } } });
EarthDollar/ed-meteor-dapp-wallet
app/client/templates/elements/executeContract.js
JavaScript
gpl-3.0
11,818
/* * Copyright (C) 2016 Douglas Wurtele * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.wurtele.ArmyTracker.models.enumerations; /** * * @author Douglas Wurtele */ public enum AbsenceStatusType { SUBMITTED, APPROVED, DISAPPROVED; }
dougwurtele/Army-Tracker
src/main/java/org/wurtele/ArmyTracker/models/enumerations/AbsenceStatusType.java
Java
gpl-3.0
857
package org.zarroboogs.weibo.widget.galleryview; import android.annotation.TargetApi; import android.content.Context; import android.os.Build; import android.util.FloatMath; import android.view.MotionEvent; import android.view.ScaleGestureDetector; import android.view.ScaleGestureDetector.OnScaleGestureListener; import android.view.VelocityTracker; import android.view.ViewConfiguration; public abstract class VersionedGestureDetector { static final String LOG_TAG = "VersionedGestureDetector"; OnGestureListener mListener; public static VersionedGestureDetector newInstance(Context context, OnGestureListener listener) { final int sdkVersion = Build.VERSION.SDK_INT; VersionedGestureDetector detector = null; if (sdkVersion < Build.VERSION_CODES.ECLAIR) { detector = new CupcakeDetector(context); } else if (sdkVersion < Build.VERSION_CODES.FROYO) { detector = new EclairDetector(context); } else { detector = new FroyoDetector(context); } detector.mListener = listener; return detector; } public abstract boolean onTouchEvent(MotionEvent ev); public abstract boolean isScaling(); public static interface OnGestureListener { public void onDrag(float dx, float dy); public void onFling(float startX, float startY, float velocityX, float velocityY); public void onScale(float scaleFactor, float focusX, float focusY); } private static class CupcakeDetector extends VersionedGestureDetector { float mLastTouchX; float mLastTouchY; final float mTouchSlop; final float mMinimumVelocity; public CupcakeDetector(Context context) { final ViewConfiguration configuration = ViewConfiguration.get(context); mMinimumVelocity = configuration.getScaledMinimumFlingVelocity(); mTouchSlop = configuration.getScaledTouchSlop(); } private VelocityTracker mVelocityTracker; private boolean mIsDragging; float getActiveX(MotionEvent ev) { return ev.getX(); } float getActiveY(MotionEvent ev) { return ev.getY(); } public boolean isScaling() { return false; } @Override public boolean onTouchEvent(MotionEvent ev) { switch (ev.getAction()) { case MotionEvent.ACTION_DOWN: { mVelocityTracker = VelocityTracker.obtain(); mVelocityTracker.addMovement(ev); mLastTouchX = getActiveX(ev); mLastTouchY = getActiveY(ev); mIsDragging = false; break; } case MotionEvent.ACTION_MOVE: { final float x = getActiveX(ev); final float y = getActiveY(ev); final float dx = x - mLastTouchX, dy = y - mLastTouchY; if (!mIsDragging) { // Use Pythagoras to see if drag length is larger than // touch slop mIsDragging = FloatMath.sqrt((dx * dx) + (dy * dy)) >= mTouchSlop; } if (mIsDragging) { mListener.onDrag(dx, dy); mLastTouchX = x; mLastTouchY = y; if (null != mVelocityTracker) { mVelocityTracker.addMovement(ev); } } break; } case MotionEvent.ACTION_CANCEL: { // Recycle Velocity Tracker if (null != mVelocityTracker) { mVelocityTracker.recycle(); mVelocityTracker = null; } break; } case MotionEvent.ACTION_UP: { if (mIsDragging) { if (null != mVelocityTracker) { mLastTouchX = getActiveX(ev); mLastTouchY = getActiveY(ev); // Compute velocity within the last 1000ms mVelocityTracker.addMovement(ev); mVelocityTracker.computeCurrentVelocity(1000); final float vX = mVelocityTracker.getXVelocity(), vY = mVelocityTracker.getYVelocity(); // If the velocity is greater than minVelocity, call // listener if (Math.max(Math.abs(vX), Math.abs(vY)) >= mMinimumVelocity) { mListener.onFling(mLastTouchX, mLastTouchY, -vX, -vY); } } } // Recycle Velocity Tracker if (null != mVelocityTracker) { mVelocityTracker.recycle(); mVelocityTracker = null; } break; } } return true; } } @TargetApi(5) private static class EclairDetector extends CupcakeDetector { private static final int INVALID_POINTER_ID = -1; private int mActivePointerId = INVALID_POINTER_ID; private int mActivePointerIndex = 0; public EclairDetector(Context context) { super(context); } @Override float getActiveX(MotionEvent ev) { try { return ev.getX(mActivePointerIndex); } catch (Exception e) { return ev.getX(); } } @Override float getActiveY(MotionEvent ev) { try { return ev.getY(mActivePointerIndex); } catch (Exception e) { return ev.getY(); } } @Override public boolean onTouchEvent(MotionEvent ev) { final int action = ev.getAction(); switch (action & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: mActivePointerId = ev.getPointerId(0); break; case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: mActivePointerId = INVALID_POINTER_ID; break; case MotionEvent.ACTION_POINTER_UP: final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT; final int pointerId = ev.getPointerId(pointerIndex); if (pointerId == mActivePointerId) { // This was our active pointer going up. Choose a new // active pointer and adjust accordingly. final int newPointerIndex = pointerIndex == 0 ? 1 : 0; mActivePointerId = ev.getPointerId(newPointerIndex); mLastTouchX = ev.getX(newPointerIndex); mLastTouchY = ev.getY(newPointerIndex); } break; } mActivePointerIndex = ev.findPointerIndex(mActivePointerId != INVALID_POINTER_ID ? mActivePointerId : 0); return super.onTouchEvent(ev); } } @TargetApi(8) private static class FroyoDetector extends EclairDetector { private final ScaleGestureDetector mDetector; // Needs to be an inner class so that we don't hit // VerifyError's on API 4. private final OnScaleGestureListener mScaleListener = new OnScaleGestureListener() { @Override public boolean onScale(ScaleGestureDetector detector) { mListener.onScale(detector.getScaleFactor(), detector.getFocusX(), detector.getFocusY()); return true; } @Override public boolean onScaleBegin(ScaleGestureDetector detector) { return true; } @Override public void onScaleEnd(ScaleGestureDetector detector) { // NO-OP } }; public FroyoDetector(Context context) { super(context); mDetector = new ScaleGestureDetector(context, mScaleListener); } @Override public boolean isScaling() { return mDetector.isInProgress(); } @Override public boolean onTouchEvent(MotionEvent ev) { mDetector.onTouchEvent(ev); return super.onTouchEvent(ev); } } }
MehmetNuri/Beebo
app/src/main/java/org/zarroboogs/weibo/widget/galleryview/VersionedGestureDetector.java
Java
gpl-3.0
8,826
/*************************************************************************** * Copyright (C) 2011-2017 Alexander V. Popov. * * This file is part of Molecular Dynamics Trajectory * Reader & Analyzer (MDTRA) source code. * * MDTRA source code is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * MDTRA source code is distributed in the hope that it will be * useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ***************************************************************************/ // Purpose: // Implementation of MDTRA_ResultDialog #include "mdtra_main.h" #include "mdtra_mainWindow.h" #include "mdtra_project.h" #include "mdtra_utils.h" #include "mdtra_resultDialog.h" #include "mdtra_resultDataSourceDialog.h" #include "mdtra_multiResultDataSourceDialog.h" #include <QtGui/QMessageBox> #include <QtGui/QPushButton> static const char *szScaleUnitNames[MDTRA_YSU_MAX] = { "Angstroms", "Nanometers", "Degrees", "Radians", "Kcal/A", "Micronewtons", "Square Angstroms", "Square Nanometers", }; static unsigned int uiScaleUnitMap[MDTRA_YSU_MAX] = { (1 << MDTRA_DT_RMSD) | (1 << MDTRA_DT_RMSD_SEL) | (1 << MDTRA_DT_RMSF) | (1 << MDTRA_DT_RMSF_SEL) | (1 << MDTRA_DT_RADIUS_OF_GYRATION) | (1 << MDTRA_DT_DISTANCE), (1 << MDTRA_DT_RMSD) | (1 << MDTRA_DT_RMSD_SEL) | (1 << MDTRA_DT_RMSF) | (1 << MDTRA_DT_RMSF_SEL) | (1 << MDTRA_DT_RADIUS_OF_GYRATION) | (1 << MDTRA_DT_DISTANCE), (1 << MDTRA_DT_ANGLE) | (1 << MDTRA_DT_ANGLE2) | (1 << MDTRA_DT_TORSION) | (1 << MDTRA_DT_TORSION_UNSIGNED) | (1 << MDTRA_DT_DIHEDRAL) | (1 << MDTRA_DT_DIHEDRAL_ABS) | (1 << MDTRA_DT_PLANEANGLE), (1 << MDTRA_DT_ANGLE) | (1 << MDTRA_DT_ANGLE2) | (1 << MDTRA_DT_TORSION) | (1 << MDTRA_DT_TORSION_UNSIGNED) | (1 << MDTRA_DT_DIHEDRAL) | (1 << MDTRA_DT_DIHEDRAL_ABS) | (1 << MDTRA_DT_PLANEANGLE), (1 << MDTRA_DT_FORCE) | (1 << MDTRA_DT_RESULTANT_FORCE), (1 << MDTRA_DT_FORCE) | (1 << MDTRA_DT_RESULTANT_FORCE), (1 << MDTRA_DT_SAS) | (1 << MDTRA_DT_SAS_SEL) | (1 << MDTRA_DT_OCCA) | (1 << MDTRA_DT_OCCA_SEL), (1 << MDTRA_DT_SAS) | (1 << MDTRA_DT_SAS_SEL) | (1 << MDTRA_DT_OCCA) | (1 << MDTRA_DT_OCCA_SEL), }; MDTRA_ResultDialog :: MDTRA_ResultDialog( int index, QWidget *parent ) : QDialog( parent ) { m_pMainWindow = qobject_cast<MDTRA_MainWindow*>(parent); assert(m_pMainWindow != NULL); setupUi( this ); setFixedSize( width(), height() ); setWindowIcon( QIcon(":/png/16x16/result.png") ); if (index < 0) { setWindowTitle( tr("Add Result Collector") ); } else { setWindowTitle( tr("Edit Result Collector") ); } m_iResultIndex = index; MDTRA_DataType currentDT = MDTRA_DT_RMSD; MDTRA_YScaleUnits currentSU = MDTRA_YSU_ANGSTROMS; MDTRA_Layout currentL = UTIL_GetDataSourceDefaultLayout(currentDT); if (index < 0) { QString resultTitle = tr("Result %1").arg(m_pMainWindow->getResultCounter()); lineEdit->setText(resultTitle); } else { MDTRA_Result *pResult = m_pMainWindow->getProject()->fetchResultByIndex( index ); if (pResult) { lineEdit->setText( pResult->name ); currentDT = pResult->type; currentSU = pResult->units; currentL = pResult->layout; dsScaleUnitsCombo->setEnabled( currentDT != MDTRA_DT_USER ); for (int i = 0; i < pResult->sourceList.count(); i++) { m_dsRefList << pResult->sourceList.at(i); MDTRA_DataSource *pDS = m_pMainWindow->getProject()->fetchDataSourceByIndex( pResult->sourceList.at(i).dataSourceIndex ); QListWidgetItem *pItem = new QListWidgetItem( QObject::tr("DATA SOURCE %1: %2\nScale = %3 Bias = %4") .arg(pDS->index) .arg(pDS->name) .arg(pResult->sourceList.at(i).yscale) .arg(pResult->sourceList.at(i).bias), dsList ); pItem->setIcon( QIcon(":/png/16x16/source.png") ); } } } for (int i = 0; i < MDTRA_DT_MAX; i++) { dsTypeCombo->addItem( UTIL_GetDataSourceShortTypeName(i) ); if (UTIL_GetDataSourceTypeId(i) == currentDT) dsTypeCombo->setCurrentIndex(i); } for (int i = 0, j = 0; i < MDTRA_YSU_MAX; i++) { if (uiScaleUnitMap[i] & (1 << (int)currentDT)) { dsScaleUnitsCombo->addItem( szScaleUnitNames[i], i ); if (i == (int)currentSU) dsScaleUnitsCombo->setCurrentIndex(j); j++; } } switch (currentL) { default: case MDTRA_LAYOUT_TIME: rbTime->setChecked( true ); break; case MDTRA_LAYOUT_RESIDUE: rbRes->setChecked( true ); break; } rbLabel->setEnabled( UTIL_IsDataSourceLayoutChangeable(currentDT) ); rbTime->setEnabled( UTIL_IsDataSourceLayoutChangeable(currentDT) ); rbRes->setEnabled( UTIL_IsDataSourceLayoutChangeable(currentDT) ); connect(dsTypeCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(exec_on_update_layout_and_scale_units())); connect(lineEdit, SIGNAL(textChanged(const QString&)), this, SLOT(exec_on_check_resultInput())); connect(buttonBox, SIGNAL(accepted()), this, SLOT(exec_on_accept())); connect(dsAdd, SIGNAL(clicked()), this, SLOT(exec_on_add_result_data_source())); connect(dsAddMulti, SIGNAL(clicked()), this, SLOT(exec_on_add_multiple_result_data_sources())); connect(dsEdit, SIGNAL(clicked()), this, SLOT(exec_on_edit_result_data_source())); connect(dsList, SIGNAL(itemDoubleClicked(QListWidgetItem*)), this, SLOT(exec_on_edit_result_data_source())); connect(dsRemove, SIGNAL(clicked()), this, SLOT(exec_on_remove_result_data_source())); connect(dsUp, SIGNAL(clicked()), this, SLOT(exec_on_up_result_data_source())); connect(dsDown, SIGNAL(clicked()), this, SLOT(exec_on_down_result_data_source())); exec_on_check_resultInput(); } void MDTRA_ResultDialog :: exec_on_update_layout_and_scale_units( void ) { MDTRA_DataType currentDT = UTIL_GetDataSourceTypeId(dsTypeCombo->currentIndex()); int currentDTi = (int)currentDT; int currentSU = dsScaleUnitsCombo->itemData(dsScaleUnitsCombo->currentIndex()).toUInt(); MDTRA_Layout currentL = UTIL_GetDataSourceDefaultLayout(currentDT); rbLabel->setEnabled( UTIL_IsDataSourceLayoutChangeable(currentDT) ); rbTime->setEnabled( UTIL_IsDataSourceLayoutChangeable(currentDT) ); rbRes->setEnabled( UTIL_IsDataSourceLayoutChangeable(currentDT) ); switch (currentL) { default: case MDTRA_LAYOUT_TIME: rbTime->setChecked( true ); break; case MDTRA_LAYOUT_RESIDUE: rbRes->setChecked( true ); break; } dsScaleUnitsCombo->clear(); for (int i = 0, j = 0; i < MDTRA_YSU_MAX; i++) { if (uiScaleUnitMap[i] & (1 << currentDTi)) { dsScaleUnitsCombo->addItem( szScaleUnitNames[i], i ); if (i == currentSU) dsScaleUnitsCombo->setCurrentIndex(j); j++; } } dsScaleUnitsCombo->setEnabled( currentDT != MDTRA_DT_USER ); } void MDTRA_ResultDialog :: exec_on_check_resultInput( void ) { dsTypeCombo->setEnabled( dsList->count() == 0 ); dsUp->setEnabled( dsList->count() > 1 ); dsDown->setEnabled( dsList->count() > 1 ); buttonBox->button( QDialogButtonBox::Ok )->setEnabled( (lineEdit->text().length() > 0) && (dsList->count() > 0)); } void MDTRA_ResultDialog :: exec_on_accept( void ) { if (m_iResultIndex < 0) { if (!m_pMainWindow->getProject()->checkUniqueResultName( lineEdit->text() )) { QMessageBox::warning(this, tr(APPLICATION_TITLE_SMALL), tr("Result \"%1\" already registered.\nPlease enter another result title.").arg(lineEdit->text())); return; } } MDTRA_DataType currentDT = UTIL_GetDataSourceTypeId(dsTypeCombo->currentIndex()); MDTRA_YScaleUnits currentSU = (MDTRA_YScaleUnits)dsScaleUnitsCombo->itemData(dsScaleUnitsCombo->currentIndex()).toUInt(); MDTRA_Layout currentL; if (rbRes->isChecked()) currentL = MDTRA_LAYOUT_RESIDUE; else currentL = MDTRA_LAYOUT_TIME; if (m_iResultIndex < 0) { m_pMainWindow->getProject()->registerResult( lineEdit->text(), currentDT, currentSU, currentL, m_dsRefList, true ); } else { m_pMainWindow->getProject()->modifyResult( m_iResultIndex, lineEdit->text(), currentDT, currentSU, currentL, m_dsRefList ); } accept(); } void MDTRA_ResultDialog :: exec_on_add_result_data_source( void ) { MDTRA_DataType currentDT = UTIL_GetDataSourceTypeId(dsTypeCombo->currentIndex()); MDTRA_ResultDataSourceDialog dialog( currentDT, NULL, m_pMainWindow, this ); if (!dialog.GetAvailableDataSourceCount()) { QMessageBox::warning(this, tr(APPLICATION_TITLE_SMALL), tr("No data sources of type \"%1\" are registered!").arg(UTIL_GetDataSourceShortTypeName(dsTypeCombo->currentIndex()))); return; } QString sCheckUserData(""); bool bCheckUserData = false; if (m_dsRefList.count() > 0) { MDTRA_DataSource *pDS = m_pMainWindow->getProject()->fetchDataSourceByIndex( m_dsRefList.at(0).dataSourceIndex ); sCheckUserData = pDS->userdata; bCheckUserData = true; } if (dialog.exec()) { MDTRA_DSRef newdsref; dialog.GetResultDataSource( &newdsref ); MDTRA_DataSource *pDS = m_pMainWindow->getProject()->fetchDataSourceByIndex( newdsref.dataSourceIndex ); if ( bCheckUserData && (sCheckUserData != pDS->userdata) ) { QMessageBox::warning(this, tr(APPLICATION_TITLE_SMALL), tr("Cannot add user-defined Data Source of type \"%1\"!\nThe Result Collector already has user-defined Data Source of type \"%2\".").arg(pDS->userdata).arg(sCheckUserData)); return; } m_dsRefList << newdsref; QListWidgetItem *pItem = new QListWidgetItem( QObject::tr("DATA SOURCE %1: %2\nScale = %3 Bias = %4") .arg(pDS->index) .arg(pDS->name) .arg(newdsref.yscale) .arg(newdsref.bias), dsList ); pItem->setIcon( QIcon(":/png/16x16/source.png") ); exec_on_check_resultInput(); } } void MDTRA_ResultDialog :: exec_on_edit_result_data_source( void ) { MDTRA_DataType currentDT = UTIL_GetDataSourceTypeId(dsTypeCombo->currentIndex()); QListWidgetItem *pItem = dsList->currentItem(); MDTRA_DSRef *pCurrentRef = const_cast<MDTRA_DSRef*>(&m_dsRefList.at(dsList->currentRow())); MDTRA_ResultDataSourceDialog dialog( currentDT, pCurrentRef, m_pMainWindow, this ); if (dialog.exec()) { dialog.GetResultDataSource( pCurrentRef ); MDTRA_DataSource *pDS = m_pMainWindow->getProject()->fetchDataSourceByIndex( pCurrentRef->dataSourceIndex ); pItem->setText( QObject::tr("DATA SOURCE %1: %2\nScale = %3 Bias = %4") .arg(pDS->index) .arg(pDS->name) .arg(pCurrentRef->yscale) .arg(pCurrentRef->bias)); } } void MDTRA_ResultDialog :: exec_on_remove_result_data_source( void ) { if (dsList->selectedItems().count() <= 0) return; if (QMessageBox::No == QMessageBox::warning( this, tr("Confirm"), tr("Do you want to remove selected result data source from the list?"), QMessageBox::Yes | QMessageBox::Default, QMessageBox::No | QMessageBox::Escape )) { return; } int itemIndex = dsList->currentRow(); m_dsRefList.removeAt( itemIndex ); QListWidgetItem *pItem = dsList->currentItem(); dsList->removeItemWidget( pItem ); delete pItem; exec_on_check_resultInput(); } void MDTRA_ResultDialog :: exec_on_up_result_data_source( void ) { if (dsList->selectedItems().count() <= 0) return; int itemIndex = dsList->currentRow(); if (itemIndex <= 0) return; m_dsRefList.swap( itemIndex, itemIndex-1 ); QListWidgetItem *currentItem = dsList->takeItem( itemIndex ); dsList->insertItem( itemIndex - 1, currentItem ); dsList->setCurrentItem( currentItem ); } void MDTRA_ResultDialog :: exec_on_down_result_data_source( void ) { if (dsList->selectedItems().count() <= 0) return; int itemIndex = dsList->currentRow(); if (itemIndex >= dsList->count()-1) return; m_dsRefList.swap( itemIndex, itemIndex+1 ); QListWidgetItem *currentItem = dsList->takeItem( itemIndex ); dsList->insertItem( itemIndex + 1, currentItem ); dsList->setCurrentItem( currentItem ); } void MDTRA_ResultDialog :: exec_on_add_multiple_result_data_sources( void ) { MDTRA_DataType currentDT = UTIL_GetDataSourceTypeId(dsTypeCombo->currentIndex()); MDTRA_MultiResultDataSourceDialog dialog( currentDT, m_pMainWindow, this ); if (!dialog.GetAvailableDataSourceCount()) { QMessageBox::warning(this, tr(APPLICATION_TITLE_SMALL), tr("No data sources of type \"%1\" are registered!").arg(UTIL_GetDataSourceShortTypeName(dsTypeCombo->currentIndex()))); return; } QString sCheckUserData(""); bool bCheckUserData = false; if (m_dsRefList.count() > 0) { MDTRA_DataSource *pDS = m_pMainWindow->getProject()->fetchDataSourceByIndex( m_dsRefList.at(0).dataSourceIndex ); sCheckUserData = pDS->userdata; bCheckUserData = true; } if (dialog.exec()) { for (int i = 0; i < dialog.GetAvailableDataSourceCount(); i++) { MDTRA_DSRef newdsref; if (!dialog.GetResultDataSource( i, &newdsref )) continue; MDTRA_DataSource *pDS = m_pMainWindow->getProject()->fetchDataSourceByIndex( newdsref.dataSourceIndex ); if ( bCheckUserData && (sCheckUserData != pDS->userdata) ) { QMessageBox::warning(this, tr(APPLICATION_TITLE_SMALL), tr("Cannot add user-defined Data Source of type \"%1\"!\nThe Result Collector already has user-defined Data Source of type \"%2\".").arg(pDS->userdata).arg(sCheckUserData)); continue; } m_dsRefList << newdsref; QListWidgetItem *pItem = new QListWidgetItem( QObject::tr("DATA SOURCE %1: %2\nScale = %3 Bias = %4") .arg(pDS->index) .arg(pDS->name) .arg(newdsref.yscale) .arg(newdsref.bias), dsList ); pItem->setIcon( QIcon(":/png/16x16/source.png") ); if ( !bCheckUserData ) { sCheckUserData = pDS->userdata; bCheckUserData = true; } } exec_on_check_resultInput(); } }
MrXaeroX/MDTRA
src/mdtra_resultDialog.cpp
C++
gpl-3.0
14,044
package com.github.ypid.complexalarm; import java.io.IOException; import java.io.InputStream; import java.util.Scanner; import android.content.Context; import android.content.res.AssetManager; import android.util.Log; import com.evgenii.jsevaluator.JsEvaluator; import com.evgenii.jsevaluator.JsFunctionCallFormatter; import com.evgenii.jsevaluator.interfaces.JsCallback; /* * Simple wrapper for the API documented here: * https://github.com/ypid/opening_hours.js#library-api */ public class OpeningHours { private JsEvaluator mJsEvaluator; final private String nominatiomTestJSONString = "{\"place_id\":\"44651229\",\"licence\":\"Data \u00a9 OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright\",\"osm_type\":\"way\",\"osm_id\":\"36248375\",\"lat\":\"49.5400039\",\"lon\":\"9.7937133\",\"display_name\":\"K 2847, Lauda-K\u00f6nigshofen, Main-Tauber-Kreis, Regierungsbezirk Stuttgart, Baden-W\u00fcrttemberg, Germany, European Union\",\"address\":{\"road\":\"K 2847\",\"city\":\"Lauda-K\u00f6nigshofen\",\"county\":\"Main-Tauber-Kreis\",\"state_district\":\"Regierungsbezirk Stuttgart\",\"state\":\"Baden-W\u00fcrttemberg\",\"country\":\"Germany\",\"country_code\":\"de\",\"continent\":\"European Union\"}}"; private Scanner scanner; private String globalResult; private String getFileContent(String fileName, Context context) throws IOException { final AssetManager am = context.getAssets(); final InputStream inputStream = am.open(fileName); scanner = new Scanner(inputStream, "UTF-8"); return scanner.useDelimiter("\\A").next(); } private String loadJs(String fileName, Context context) { try { return getFileContent(fileName, context); } catch (final IOException e) { e.printStackTrace(); } return null; } protected OpeningHours(Context context) { Log.d("OpeningHours", "Loading up opening_hours.js"); mJsEvaluator = new JsEvaluator(context); String librarySrouce = loadJs("javascript-libs/suncalc/suncalc.min.js", context); mJsEvaluator.evaluate(librarySrouce); librarySrouce = loadJs( "javascript-libs/opening_hours/opening_hours.min.js", context); mJsEvaluator.evaluate(librarySrouce); } protected String evalOpeningHours(String value, String nominatiomJSON, byte oh_mode) { String ohConstructorCall = "new opening_hours('" + value + "', JSON.parse('" + nominatiomJSON + "'), " + oh_mode + ")"; Log.d("OpeningHours constructor", ohConstructorCall); final String code = "var oh, warnings, crashed = true;" + "try {" + " oh = " + ohConstructorCall + ";" + " warnings = oh.getWarnings();" + " crashed = false;" + "} catch(err) {" + " crashed = err;" + "}" + "oh.getNextChange().toString();" + // "crashed.toString();" + ""; mJsEvaluator.evaluate(code, new JsCallback() { @Override public void onResult(final String resultValue) { Log.d("OpeningHours", String.format("Result: %s", resultValue)); } }); return "test"; } protected String getDate() { globalResult = null; mJsEvaluator.evaluate("new Date().toString()", new JsCallback() { @Override public void onResult(final String resultValue) { Log.d("Date", String.format("Result: %s", resultValue)); // Block until event occurs. globalResult = resultValue; Log.d("Date", String.format("globalResult: %s", globalResult)); } }); for (int i = 0; i < 100; i++) { Log.d("Date", String.format("%d, %s", i, globalResult)); try { Log.d("Date", "sleep"); Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block Log.d("Date", "Catch"); e.printStackTrace(); } if (globalResult != null) { break; } } return globalResult; } protected String returnDate() { return globalResult; } protected String evalOpeningHours(String value, String nominatiomJSON) { return evalOpeningHours(value, nominatiomJSON, (byte) 0); } protected String evalOpeningHours(String value) { // evalOpeningHours(value, "{}"); return evalOpeningHours(value, nominatiomTestJSONString); // FIXME // testing // only } }
ypid/ComplexAlarm
src/com/github/ypid/complexalarm/OpeningHours.java
Java
gpl-3.0
4,883
# -*- coding: utf-8 -*- #------------------------------------------------------------------------------ # file: $Id$ # auth: metagriffin <mg.github@uberdev.org> # date: 2012/04/20 # copy: (C) Copyright 2012-EOT metagriffin -- see LICENSE.txt #------------------------------------------------------------------------------ # This software is free software: you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This software is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see http://www.gnu.org/licenses/. #------------------------------------------------------------------------------ from .tracker import * from .merger import * #------------------------------------------------------------------------------ # end of $Id$ #------------------------------------------------------------------------------
metagriffin/pysyncml
pysyncml/change/__init__.py
Python
gpl-3.0
1,255
/** * Copyright (c) 2000-2004 Liferay, LLC. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.dotmarketing.portlets.mailinglists.action; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import com.dotcms.repackage.portlet.javax.portlet.PortletConfig; import com.dotcms.repackage.portlet.javax.portlet.RenderRequest; import com.dotcms.repackage.portlet.javax.portlet.RenderResponse; import com.dotcms.repackage.portlet.javax.portlet.WindowState; import javax.servlet.jsp.PageContext; import com.dotcms.repackage.commons_beanutils.org.apache.commons.beanutils.BeanUtils; import com.dotcms.repackage.struts.org.apache.struts.action.ActionForm; import com.dotcms.repackage.struts.org.apache.struts.action.ActionForward; import com.dotcms.repackage.struts.org.apache.struts.action.ActionMapping; import com.dotmarketing.business.Role; import com.dotmarketing.portlets.mailinglists.factories.MailingListFactory; import com.dotmarketing.portlets.mailinglists.model.MailingList; import com.dotmarketing.portlets.userfilter.factories.UserFilterFactory; import com.dotmarketing.util.Config; import com.dotmarketing.util.Logger; import com.dotmarketing.util.UtilMethods; import com.dotmarketing.util.WebKeys; import com.liferay.portal.model.User; import com.liferay.portal.struts.PortletAction; import com.liferay.portal.util.Constants; /** * <a href="ViewQuestionsAction.java.html"><b><i>View Source</i></b></a> * * @author Brian Wing Shun Chan * @version $Revision: 1.4 $ * */ public class ViewMailingListsAction extends PortletAction { public ActionForward render( ActionMapping mapping, ActionForm form, PortletConfig config, RenderRequest req, RenderResponse res) throws Exception { Logger.debug(this, "Running ViewMailingListsAction"); try { //get the user, order, direction User user = com.liferay.portal.util.PortalUtil.getUser(req); String orderBy = req.getParameter("orderby"); String direction = req.getParameter("direction"); String condition = req.getParameter("query"); //get their lists List list = null; List roles = com.dotmarketing.business.APILocator.getRoleAPI().loadRolesForUser(user.getUserId()); boolean isMarketingAdmin = false; Iterator rolesIt = roles.iterator(); while (rolesIt.hasNext()) { Role role = (Role) rolesIt.next(); if (UtilMethods.isSet(role.getRoleKey()) && role.getRoleKey().equals(Config.getStringProperty("MAILINGLISTS_ADMIN_ROLE"))) { isMarketingAdmin = true; break; } } if (isMarketingAdmin) { if (UtilMethods.isSet(orderBy) && UtilMethods.isSet(direction)) { //list = MailingListFactory.getAllMailingLists(orderBy, direction); list = MailingListFactory.getAllMailingLists(); list.addAll(UserFilterFactory.getAllUserFilter()); if (orderBy.equals("title")) { if (direction.equals(" asc")) Collections.sort(list, new ComparatorTitleAsc()); else Collections.sort(list, new ComparatorTitleDesc()); } } else if(UtilMethods.isSet(condition)) { list = MailingListFactory.getAllMailingListsCondition(condition); list.addAll(UserFilterFactory.getUserFilterByTitle(condition)); Collections.sort(list, new ComparatorTitleAsc()); } else { list = MailingListFactory.getAllMailingLists(); list.addAll(UserFilterFactory.getAllUserFilter()); Collections.sort(list, new ComparatorTitleAsc()); } } else { if (UtilMethods.isSet(orderBy) && UtilMethods.isSet(direction)) { //list = MailingListFactory.getMailingListsByUser(user, orderBy, direction); list = MailingListFactory.getMailingListsByUser(user); list.add(MailingListFactory.getUnsubscribersMailingList()); list.addAll(UserFilterFactory.getAllUserFilterByUser(user)); if (orderBy.equals("title")) { if (direction.equals(" asc")) Collections.sort(list, new ComparatorTitleAsc()); else Collections.sort(list, new ComparatorTitleDesc()); } } else if(UtilMethods.isSet(condition)) { list = MailingListFactory.getMailingListsByUserCondition(user, condition); list.add(MailingListFactory.getUnsubscribersMailingList()); list.addAll(UserFilterFactory.getUserFilterByTitleAndUser(condition, user)); Collections.sort(list, new ComparatorTitleAsc()); } else { list = MailingListFactory.getMailingListsByUser(user); list.add(MailingListFactory.getUnsubscribersMailingList()); list.addAll(UserFilterFactory.getAllUserFilterByUser(user)); Collections.sort(list, new ComparatorTitleAsc()); } } if (req.getWindowState().equals(WindowState.NORMAL)) { // if (list != null) // list = orderMailingListByDescDate(list); req.setAttribute(WebKeys.MAILING_LIST_VIEW_PORTLET, list); return mapping.findForward("portlet.ext.mailinglists.view"); } else { req.setAttribute(WebKeys.MAILING_LIST_VIEW, list); return mapping.findForward("portlet.ext.mailinglists.view_mailinglists"); } } catch (Exception e) { req.setAttribute(PageContext.EXCEPTION, e); return mapping.findForward(Constants.COMMON_ERROR); } } private List<MailingList> orderMailingListByDescDate(List<MailingList> list) { List<MailingList> result = new ArrayList<MailingList>(list.size()); int i; boolean added; MailingList mailingList2; for (MailingList mailingList1: list) { if (result.size() == 0) { result.add(mailingList1); } else { added = false; for (i = 0; i < result.size(); ++i) { mailingList2 = result.get(i); if (mailingList2.getIDate().before(mailingList1.getIDate())) { result.add(i, mailingList1); added = true; break; } } if (!added) result.add(mailingList1); } } return result; } private class ComparatorTitleAsc implements Comparator { public int compare(Object o1, Object o2) { String title1, title2; try { if (o1 instanceof MailingList) title1 = BeanUtils.getProperty(o1, "title"); else title1 = BeanUtils.getProperty(o1, "userFilterTitle"); } catch (Exception e) { title1 = ""; } try { if (o2 instanceof MailingList) title2 = BeanUtils.getProperty(o2, "title"); else title2 = BeanUtils.getProperty(o2, "userFilterTitle"); } catch (Exception e) { title2 = ""; } return title1.compareToIgnoreCase(title2); } } private class ComparatorTitleDesc implements Comparator { public int compare(Object o1, Object o2) { String title1, title2; try { if (o1 instanceof MailingList) title1 = BeanUtils.getProperty(o1, "title"); else title1 = BeanUtils.getProperty(o1, "userFilterTitle"); } catch (Exception e) { title1 = ""; } try { if (o2 instanceof MailingList) title2 = BeanUtils.getProperty(o2, "title"); else title2 = BeanUtils.getProperty(o2, "userFilterTitle"); } catch (Exception e) { title2 = ""; } return title2.compareToIgnoreCase(title1); } } }
austindlawless/dotCMS
src/com/dotmarketing/portlets/mailinglists/action/ViewMailingListsAction.java
Java
gpl-3.0
8,207
/* * Copyright (c) 2017 OBiBa. All rights reserved. * * This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.obiba.mica.core.service; import java.util.Arrays; import java.util.Collection; import java.util.LinkedHashMap; import java.util.Map; import java.util.stream.Collectors; import javax.inject.Inject; import javax.validation.constraints.NotNull; import net.minidev.json.JSONArray; import org.obiba.mica.core.domain.SchemaFormContentAware; import org.obiba.mica.file.FileStoreService; import org.springframework.stereotype.Service; import org.springframework.util.Assert; import com.google.common.collect.Sets; import com.jayway.jsonpath.DocumentContext; import com.jayway.jsonpath.JsonPath; import com.jayway.jsonpath.Option; import com.jayway.jsonpath.PathNotFoundException; import com.jayway.jsonpath.internal.JsonReader; import static com.jayway.jsonpath.Configuration.defaultConfiguration; @Service public class SchemaFormContentFileService { @Inject private FileStoreService fileStoreService; public void save(@NotNull SchemaFormContentAware newEntity, SchemaFormContentAware oldEntity, String entityPath) { Assert.notNull(newEntity, "New content cannot be null"); Object json = defaultConfiguration().jsonProvider().parse(newEntity.getContent()); DocumentContext newContext = JsonPath.using(defaultConfiguration().addOptions(Option.AS_PATH_LIST)).parse(json); Map<String, JSONArray> newPaths = getPathFilesMap(newContext, json); if (newPaths == null) return; // content does not have any file field if (oldEntity != null) { Object oldJson = defaultConfiguration().jsonProvider().parse(oldEntity.getContent()); DocumentContext oldContext = JsonPath.using(defaultConfiguration().addOptions(Option.AS_PATH_LIST)).parse(oldJson); Map<String, JSONArray> oldPaths = getPathFilesMap(oldContext, oldJson); if (oldPaths != null) { saveAndDelete(oldPaths, newPaths, entityPath); } else { // schema and definition now have files newPaths.values().forEach(v -> saveFiles(v, entityPath)); } } else { newPaths.values().forEach(v -> saveFiles(v, entityPath)); } cleanup(newPaths, newContext); newEntity.setContent(newContext.jsonString()); } public void deleteFiles(SchemaFormContentAware entity) { Object json = defaultConfiguration().jsonProvider().parse(entity.getContent()); DocumentContext context = JsonPath.using(defaultConfiguration().addOptions(Option.AS_PATH_LIST)).parse(json); DocumentContext reader = new JsonReader(defaultConfiguration().addOptions(Option.REQUIRE_PROPERTIES)).parse(json); try { ((JSONArray)context.read("$..obibaFiles")).stream() .map(p -> (JSONArray) reader.read(p.toString())) .flatMap(Collection::stream) .forEach(file -> fileStoreService.delete(((LinkedHashMap)file).get("id").toString())); } catch(PathNotFoundException e) { } } /** * Removes the fields with empty obibaFiles from content. * * @param newPaths * @param newContext */ private void cleanup(Map<String, JSONArray> newPaths, DocumentContext newContext) { newPaths.keySet().forEach(p -> { if (newPaths.get(p).isEmpty()) { newContext.delete(p.replace("['obibaFiles']", "")); } }); } private void saveAndDelete(Map<String, JSONArray> oldPaths, Map<String, JSONArray> newPaths, String entityPath) { newPaths.keySet().forEach(p -> { if (oldPaths.containsKey(p)) { saveAndDeleteFiles(oldPaths.get(p), newPaths.get(p), entityPath); } else { saveFiles(newPaths.get(p), entityPath); } }); } private Map<String, JSONArray> getPathFilesMap(DocumentContext context, Object json) { DocumentContext reader = new JsonReader(defaultConfiguration().addOptions(Option.REQUIRE_PROPERTIES)).parse(json); JSONArray paths = null; try { paths = context.read("$..obibaFiles"); } catch(PathNotFoundException e) { return null; } return paths.stream().collect(Collectors.toMap(Object::toString, p -> (JSONArray) reader.read(p.toString()))); } private Iterable<Object> saveAndDeleteFiles(JSONArray oldFiles, JSONArray newFiles, String entityPath) { cleanFileJsonArrays(oldFiles, newFiles); Iterable<Object> toDelete = Sets.difference(Sets.newHashSet(oldFiles), Sets.newHashSet(newFiles)); Iterable<Object> toSave = Sets.difference(Sets.newHashSet(newFiles), Sets.newHashSet(oldFiles)); toDelete.forEach(file -> fileStoreService.delete(((LinkedHashMap)file).get("id").toString())); saveFiles(toSave, entityPath); return toDelete; } private void cleanFileJsonArrays(JSONArray... arrays) { if (arrays != null) { Arrays.stream(arrays).forEach(s -> s.forEach(a -> { if (a instanceof LinkedHashMap) { LinkedHashMap<String, String> jsonMap = (LinkedHashMap<String, String>) a; jsonMap.keySet().stream().filter(k -> k.contains("$")).collect(Collectors.toList()).forEach(jsonMap::remove); } })); } } private void saveFiles(Iterable files, String entityPath) { if(files != null) files.forEach(file -> { LinkedHashMap map = (LinkedHashMap)file; map.put("path", entityPath); fileStoreService.save(map.get("id").toString()); }); } }
Rima-B/mica2
mica-core/src/main/java/org/obiba/mica/core/service/SchemaFormContentFileService.java
Java
gpl-3.0
5,584
Bitrix 17.0.9 Business Demo = e475d0cd490d83505c54e6cec1c3d6ed
gohdan/DFC
known_files/hashes/bitrix/modules/bizproc/install/activities/bitrix/webhookactivity/lang/en/webhookactivity.php
PHP
gpl-3.0
63
<?php /* Smarty version Smarty-3.1.19, created on 2017-09-23 12:35:41 compiled from "/var/www/html/admin240x2hjae/themes/default/template/page_header_toolbar.tpl" */ ?> <?php /*%%SmartyHeaderCode:61757368659c68d5d8d2e84-70988510%%*/if(!defined('SMARTY_DIR')) exit('no direct access allowed'); $_valid = $_smarty_tpl->decodeProperties(array ( 'file_dependency' => array ( 'd65aaeae6f3a1059b7e9527adddd1e40bec16718' => array ( 0 => '/var/www/html/admin240x2hjae/themes/default/template/page_header_toolbar.tpl', 1 => 1506184509, 2 => 'file', ), ), 'nocache_hash' => '61757368659c68d5d8d2e84-70988510', 'function' => array ( ), 'variables' => array ( 'title' => 0, 'page_header_toolbar_title' => 0, 'page_header_toolbar_btn' => 0, 'current_tab_level' => 0, 'breadcrumbs2' => 0, 'toolbar_btn' => 0, 'k' => 0, 'table' => 0, 'btn' => 0, 'help_link' => 0, 'tab_modules_open' => 0, 'tab_modules_list' => 0, 'tabs' => 0, 'level_1' => 0, 'level_2' => 0, 'level_3' => 0, 'level_4' => 0, ), 'has_nocache_code' => false, 'version' => 'Smarty-3.1.19', 'unifunc' => 'content_59c68d5dac6da8_00389838', ),false); /*/%%SmartyHeaderCode%%*/?> <?php if ($_valid && !is_callable('content_59c68d5dac6da8_00389838')) {function content_59c68d5dac6da8_00389838($_smarty_tpl) {?> <?php if (!isset($_smarty_tpl->tpl_vars['title']->value)&&isset($_smarty_tpl->tpl_vars['page_header_toolbar_title']->value)) {?> <?php $_smarty_tpl->tpl_vars['title'] = new Smarty_variable($_smarty_tpl->tpl_vars['page_header_toolbar_title']->value, null, 0);?> <?php }?> <?php if (isset($_smarty_tpl->tpl_vars['page_header_toolbar_btn']->value)) {?> <?php $_smarty_tpl->tpl_vars['toolbar_btn'] = new Smarty_variable($_smarty_tpl->tpl_vars['page_header_toolbar_btn']->value, null, 0);?> <?php }?> <div class="bootstrap"> <div class="page-head <?php if (isset($_smarty_tpl->tpl_vars['current_tab_level']->value)&&$_smarty_tpl->tpl_vars['current_tab_level']->value==3) {?>with-tabs<?php }?>"> <h2 class="page-title"> <?php if (is_array($_smarty_tpl->tpl_vars['title']->value)) {?><?php echo preg_replace('!<[^>]*?>!', ' ', end($_smarty_tpl->tpl_vars['title']->value));?> <?php } else { ?><?php echo preg_replace('!<[^>]*?>!', ' ', $_smarty_tpl->tpl_vars['title']->value);?> <?php }?> </h2> <ul class="breadcrumb page-breadcrumb"> <?php if ($_smarty_tpl->tpl_vars['breadcrumbs2']->value['container']['name']!='') {?> <li class="breadcrumb-container"> <?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['escape'][0][0]->smartyEscape($_smarty_tpl->tpl_vars['breadcrumbs2']->value['container']['name']);?> </li> <?php }?> <?php if ($_smarty_tpl->tpl_vars['breadcrumbs2']->value['tab']['name']!=''&&$_smarty_tpl->tpl_vars['breadcrumbs2']->value['container']['name']!=$_smarty_tpl->tpl_vars['breadcrumbs2']->value['tab']['name']) {?> <li class="breadcrumb-current"> <?php if ($_smarty_tpl->tpl_vars['breadcrumbs2']->value['tab']['href']!='') {?><a href="<?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['escape'][0][0]->smartyEscape($_smarty_tpl->tpl_vars['breadcrumbs2']->value['tab']['href']);?> "><?php }?> <?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['escape'][0][0]->smartyEscape($_smarty_tpl->tpl_vars['breadcrumbs2']->value['tab']['name']);?> <?php if ($_smarty_tpl->tpl_vars['breadcrumbs2']->value['tab']['href']!='') {?></a><?php }?> </li> <?php }?> </ul> <div class="page-bar toolbarBox"> <div class="btn-toolbar"> <a href="#" class="toolbar_btn dropdown-toolbar navbar-toggle" data-toggle="collapse" data-target="#toolbar-nav"><i class="process-icon-dropdown"></i> <div><?php echo smartyTranslate(array('s'=>'Menu'),$_smarty_tpl);?> </div> </a> <ul id="toolbar-nav" class="nav nav-pills pull-right collapse navbar-collapse"> <?php $_smarty_tpl->tpl_vars['btn'] = new Smarty_Variable; $_smarty_tpl->tpl_vars['btn']->_loop = false; $_smarty_tpl->tpl_vars['k'] = new Smarty_Variable; $_from = $_smarty_tpl->tpl_vars['toolbar_btn']->value; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array');} foreach ($_from as $_smarty_tpl->tpl_vars['btn']->key => $_smarty_tpl->tpl_vars['btn']->value) { $_smarty_tpl->tpl_vars['btn']->_loop = true; $_smarty_tpl->tpl_vars['k']->value = $_smarty_tpl->tpl_vars['btn']->key; ?> <?php if ($_smarty_tpl->tpl_vars['k']->value!='back'&&$_smarty_tpl->tpl_vars['k']->value!='modules-list') {?> <li> <a id="page-header-desc-<?php echo $_smarty_tpl->tpl_vars['table']->value;?> -<?php if (isset($_smarty_tpl->tpl_vars['btn']->value['imgclass'])) {?><?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['escape'][0][0]->smartyEscape($_smarty_tpl->tpl_vars['btn']->value['imgclass']);?> <?php } else { ?><?php echo $_smarty_tpl->tpl_vars['k']->value;?> <?php }?>" class="toolbar_btn <?php if (isset($_smarty_tpl->tpl_vars['btn']->value['target'])&&$_smarty_tpl->tpl_vars['btn']->value['target']) {?> _blank<?php }?> pointer"<?php if (isset($_smarty_tpl->tpl_vars['btn']->value['href'])) {?> href="<?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['escape'][0][0]->smartyEscape($_smarty_tpl->tpl_vars['btn']->value['href']);?> "<?php }?> title="<?php if (isset($_smarty_tpl->tpl_vars['btn']->value['help'])) {?><?php echo $_smarty_tpl->tpl_vars['btn']->value['help'];?> <?php } else { ?><?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['escape'][0][0]->smartyEscape($_smarty_tpl->tpl_vars['btn']->value['desc']);?> <?php }?>"<?php if (isset($_smarty_tpl->tpl_vars['btn']->value['js'])&&$_smarty_tpl->tpl_vars['btn']->value['js']) {?> onclick="<?php echo $_smarty_tpl->tpl_vars['btn']->value['js'];?> "<?php }?><?php if (isset($_smarty_tpl->tpl_vars['btn']->value['modal_target'])&&$_smarty_tpl->tpl_vars['btn']->value['modal_target']) {?> data-target="<?php echo $_smarty_tpl->tpl_vars['btn']->value['modal_target'];?> " data-toggle="modal"<?php }?><?php if (isset($_smarty_tpl->tpl_vars['btn']->value['help'])) {?> data-toggle="tooltip" data-placement="bottom"<?php }?>> <i class="<?php if (isset($_smarty_tpl->tpl_vars['btn']->value['icon'])) {?><?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['escape'][0][0]->smartyEscape($_smarty_tpl->tpl_vars['btn']->value['icon']);?> <?php } else { ?>process-icon-<?php if (isset($_smarty_tpl->tpl_vars['btn']->value['imgclass'])) {?><?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['escape'][0][0]->smartyEscape($_smarty_tpl->tpl_vars['btn']->value['imgclass']);?> <?php } else { ?><?php echo $_smarty_tpl->tpl_vars['k']->value;?> <?php }?><?php }?><?php if (isset($_smarty_tpl->tpl_vars['btn']->value['class'])) {?> <?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['escape'][0][0]->smartyEscape($_smarty_tpl->tpl_vars['btn']->value['class']);?> <?php }?>"></i> <div<?php if (isset($_smarty_tpl->tpl_vars['btn']->value['force_desc'])&&$_smarty_tpl->tpl_vars['btn']->value['force_desc']==true) {?> class="locked"<?php }?>><?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['escape'][0][0]->smartyEscape($_smarty_tpl->tpl_vars['btn']->value['desc']);?> </div> </a> </li> <?php }?> <?php } ?> <?php if (isset($_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list'])) {?> <li> <a id="page-header-desc-<?php echo $_smarty_tpl->tpl_vars['table']->value;?> -<?php if (isset($_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['imgclass'])) {?><?php echo $_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['imgclass'];?> <?php } else { ?>modules-list<?php }?>" class="toolbar_btn<?php if (isset($_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['class'])) {?> <?php echo $_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['class'];?> <?php }?><?php if (isset($_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['target'])&&$_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['target']) {?> _blank<?php }?>" <?php if (isset($_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['href'])) {?>href="<?php echo $_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['href'];?> "<?php }?> title="<?php echo $_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['desc'];?> "<?php if (isset($_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['js'])&&$_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['js']) {?> onclick="<?php echo $_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['js'];?> "<?php }?>> <i class="<?php if (isset($_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['icon'])) {?><?php echo $_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['icon'];?> <?php } else { ?>process-icon-<?php if (isset($_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['imgclass'])) {?><?php echo $_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['imgclass'];?> <?php } else { ?>modules-list<?php }?><?php }?>"></i> <div<?php if (isset($_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['force_desc'])&&$_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['force_desc']==true) {?> class="locked"<?php }?>><?php echo $_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['desc'];?> </div> </a> </li> <?php }?> <?php if (isset($_smarty_tpl->tpl_vars['help_link']->value)) {?> <li> <a class="toolbar_btn btn-help" href="<?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['escape'][0][0]->smartyEscape($_smarty_tpl->tpl_vars['help_link']->value);?> " title="<?php echo smartyTranslate(array('s'=>'Help'),$_smarty_tpl);?> "> <i class="process-icon-help"></i> <div><?php echo smartyTranslate(array('s'=>'Help'),$_smarty_tpl);?> </div> </a> </li> <?php }?> </ul> <?php if ((isset($_smarty_tpl->tpl_vars['tab_modules_open']->value)&&$_smarty_tpl->tpl_vars['tab_modules_open']->value)||isset($_smarty_tpl->tpl_vars['tab_modules_list']->value)) {?> <script type="text/javascript"> //<![CDATA[ var modules_list_loaded = false; <?php if (isset($_smarty_tpl->tpl_vars['tab_modules_open']->value)&&$_smarty_tpl->tpl_vars['tab_modules_open']->value) {?> $(function () { $('#modules_list_container').modal('show'); openModulesList(); }); <?php }?> <?php if (isset($_smarty_tpl->tpl_vars['tab_modules_list']->value)) {?> $('.process-icon-modules-list').parent('a').unbind().bind('click', function (event) { event.preventDefault(); $('#modules_list_container').modal('show'); openModulesList(); }); <?php }?> //]]> </script> <?php }?> </div> </div> <?php if (isset($_smarty_tpl->tpl_vars['current_tab_level']->value)&&$_smarty_tpl->tpl_vars['current_tab_level']->value==3) {?> <div class="page-head-tabs"> <?php $_smarty_tpl->tpl_vars['level_1'] = new Smarty_Variable; $_smarty_tpl->tpl_vars['level_1']->_loop = false; $_from = $_smarty_tpl->tpl_vars['tabs']->value; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array');} foreach ($_from as $_smarty_tpl->tpl_vars['level_1']->key => $_smarty_tpl->tpl_vars['level_1']->value) { $_smarty_tpl->tpl_vars['level_1']->_loop = true; ?> <?php $_smarty_tpl->tpl_vars['level_2'] = new Smarty_Variable; $_smarty_tpl->tpl_vars['level_2']->_loop = false; $_from = $_smarty_tpl->tpl_vars['level_1']->value['sub_tabs']; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array');} foreach ($_from as $_smarty_tpl->tpl_vars['level_2']->key => $_smarty_tpl->tpl_vars['level_2']->value) { $_smarty_tpl->tpl_vars['level_2']->_loop = true; ?> <?php $_smarty_tpl->tpl_vars['level_3'] = new Smarty_Variable; $_smarty_tpl->tpl_vars['level_3']->_loop = false; $_from = $_smarty_tpl->tpl_vars['level_2']->value['sub_tabs']; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array');} foreach ($_from as $_smarty_tpl->tpl_vars['level_3']->key => $_smarty_tpl->tpl_vars['level_3']->value) { $_smarty_tpl->tpl_vars['level_3']->_loop = true; ?> <?php if ($_smarty_tpl->tpl_vars['level_3']->value['current']) {?> <?php $_smarty_tpl->tpl_vars['level_4'] = new Smarty_Variable; $_smarty_tpl->tpl_vars['level_4']->_loop = false; $_from = $_smarty_tpl->tpl_vars['level_3']->value['sub_tabs']; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array');} foreach ($_from as $_smarty_tpl->tpl_vars['level_4']->key => $_smarty_tpl->tpl_vars['level_4']->value) { $_smarty_tpl->tpl_vars['level_4']->_loop = true; ?> <a href="<?php echo $_smarty_tpl->tpl_vars['level_4']->value['href'];?> " <?php if ($_smarty_tpl->tpl_vars['level_4']->value['current']) {?>class="current"<?php }?>><?php echo $_smarty_tpl->tpl_vars['level_4']->value['name'];?> </a> <?php } ?> <?php }?> <?php } ?> <?php } ?> <?php } ?> </div> <?php }?> </div> <?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['hook'][0][0]->smartyHook(array('h'=>'displayDashboardTop'),$_smarty_tpl);?> </div> <?php }} ?>
rjpalermo1/paymentsandbox_ps
src/app/cache/dev/smarty/compile/d6/5a/ae/d65aaeae6f3a1059b7e9527adddd1e40bec16718.file.page_header_toolbar.tpl.php
PHP
gpl-3.0
14,335
/** * * This file is part of Tulip (www.tulip-software.org) * * Authors: David Auber and the Tulip development Team * from LaBRI, University of Bordeaux * * Tulip is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation, either version 3 * of the License, or (at your option) any later version. * * Tulip is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * */ #include <stdio.h> #include <string> #include <iostream> #include <cppunit/TestCase.h> #include <tulip/TulipPluginHeaders.h> using namespace std; class Test2 : public tlp::BooleanAlgorithm { public: PLUGININFORMATION("Test2","Jezequel","03/11/2004","0","1.0", "") Test2(tlp::PluginContext* context) : tlp::BooleanAlgorithm(context) {} ~Test2() {} bool run() { return true; } }; PLUGIN(Test2)
jukkes/TulipProject
unit_test/library/tulip/testPlugin2.cpp
C++
gpl-3.0
1,069
"""Test class for Custom Sync UI :Requirement: Sync :CaseAutomation: Automated :CaseLevel: Acceptance :CaseComponent: Repositories :TestType: Functional :CaseImportance: High :Upstream: No """ from fauxfactory import gen_string from nailgun import entities from robottelo import manifests from robottelo.api.utils import enable_rhrepo_and_fetchid from robottelo.constants import ( DISTRO_RHEL6, DISTRO_RHEL7, DOCKER_REGISTRY_HUB, DOCKER_UPSTREAM_NAME, FAKE_1_YUM_REPO, FEDORA27_OSTREE_REPO, REPOS, REPOSET, REPO_TYPE, PRDS, ) from robottelo.decorators import ( fixture, run_in_one_thread, skip_if_not_set, tier2, upgrade, skip_if_bug_open, ) from robottelo.decorators.host import skip_if_os from robottelo.products import ( RepositoryCollection, RHELCloudFormsTools, SatelliteCapsuleRepository, ) @fixture(scope='module') def module_org(): return entities.Organization().create() @fixture(scope='module') def module_custom_product(module_org): return entities.Product(organization=module_org).create() @fixture(scope='module') def module_org_with_manifest(): org = entities.Organization().create() manifests.upload_manifest_locked(org.id) return org @tier2 def test_positive_sync_custom_repo(session, module_custom_product): """Create Content Custom Sync with minimal input parameters :id: 00fb0b04-0293-42c2-92fa-930c75acee89 :expectedresults: Sync procedure is successful :CaseImportance: Critical """ repo = entities.Repository( url=FAKE_1_YUM_REPO, product=module_custom_product).create() with session: results = session.sync_status.synchronize([ (module_custom_product.name, repo.name)]) assert len(results) == 1 assert results[0] == 'Syncing Complete.' @run_in_one_thread @skip_if_not_set('fake_manifest') @tier2 @upgrade def test_positive_sync_rh_repos(session, module_org_with_manifest): """Create Content RedHat Sync with two repos. :id: e30f6509-0b65-4bcc-a522-b4f3089d3911 :expectedresults: Sync procedure for RedHat Repos is successful :CaseLevel: Integration """ repos = ( SatelliteCapsuleRepository(cdn=True), RHELCloudFormsTools(cdn=True) ) distros = [DISTRO_RHEL7, DISTRO_RHEL6] repo_collections = [ RepositoryCollection(distro=distro, repositories=[repo]) for distro, repo in zip(distros, repos) ] for repo_collection in repo_collections: repo_collection.setup(module_org_with_manifest.id, synchronize=False) repo_paths = [ ( repo.repo_data['product'], repo.repo_data.get('releasever'), repo.repo_data.get('arch'), repo.repo_data['name'], ) for repo in repos ] with session: session.organization.select(org_name=module_org_with_manifest.name) results = session.sync_status.synchronize(repo_paths) assert len(results) == len(repo_paths) assert all([result == 'Syncing Complete.' for result in results]) @skip_if_bug_open('bugzilla', 1625783) @skip_if_os('RHEL6') @tier2 @upgrade def test_positive_sync_custom_ostree_repo(session, module_custom_product): """Create custom ostree repository and sync it. :id: e4119b9b-0356-4661-a3ec-e5807224f7d2 :expectedresults: ostree repo should be synced successfully :CaseLevel: Integration """ repo = entities.Repository( content_type='ostree', url=FEDORA27_OSTREE_REPO, product=module_custom_product, unprotected=False, ).create() with session: results = session.sync_status.synchronize([ (module_custom_product.name, repo.name)]) assert len(results) == 1 assert results[0] == 'Syncing Complete.' @run_in_one_thread @skip_if_bug_open('bugzilla', 1625783) @skip_if_os('RHEL6') @skip_if_not_set('fake_manifest') @tier2 @upgrade def test_positive_sync_rh_ostree_repo(session, module_org_with_manifest): """Sync CDN based ostree repository. :id: 4d28fff0-5fda-4eee-aa0c-c5af02c31de5 :Steps: 1. Import a valid manifest 2. Enable the OStree repo and sync it :expectedresults: ostree repo should be synced successfully from CDN :CaseLevel: Integration """ enable_rhrepo_and_fetchid( basearch=None, org_id=module_org_with_manifest.id, product=PRDS['rhah'], repo=REPOS['rhaht']['name'], reposet=REPOSET['rhaht'], releasever=None, ) with session: session.organization.select(org_name=module_org_with_manifest.name) results = session.sync_status.synchronize([ (PRDS['rhah'], REPOS['rhaht']['name'])]) assert len(results) == 1 assert results[0] == 'Syncing Complete.' @tier2 @upgrade def test_positive_sync_docker_via_sync_status(session, module_org): """Create custom docker repo and sync it via the sync status page. :id: 00b700f4-7e52-48ed-98b2-e49b3be102f2 :expectedresults: Sync procedure for specific docker repository is successful :CaseLevel: Integration """ product = entities.Product(organization=module_org).create() repo_name = gen_string('alphanumeric') with session: session.repository.create( product.name, {'name': repo_name, 'repo_type': REPO_TYPE['docker'], 'repo_content.upstream_url': DOCKER_REGISTRY_HUB, 'repo_content.upstream_repo_name': DOCKER_UPSTREAM_NAME} ) assert session.repository.search(product.name, repo_name)[0]['Name'] == repo_name result = session.sync_status.synchronize([(product.name, repo_name)]) assert result[0] == 'Syncing Complete.'
omaciel/robottelo
tests/foreman/ui/test_sync.py
Python
gpl-3.0
5,811
<?php $L['Alerts_Title'] = 'Allarmi personalizzati'; $L['Alerts_Description'] = 'Allarmi personalizzati da ${0}'; $L['Alerts_header'] = 'Allarmi personalizzati da ${0}'; $L['Alerts_Configure_header'] = 'Configura download automatico'; $L['Update_Alerts_label'] = 'Scarica allarmi personalizzati'; $L['Refresh_label'] = 'Download configurazioni allarmi'; $L['last_update_label'] = 'Ultimo aggiornamento'; $L['Type_label'] = 'Allarme'; $L['Instance_label'] = 'Parametro'; $L['Threshold_label'] = 'Soglia'; $L['AlertsAutoUpdates_enabled_label'] = 'Abilita download automatico degli allarmi personalizzati (raccomandato)'; $L['AlertsAutoUpdates_disabled_label'] = 'Disabilita download automatico degli allarmi personalizzati'; $L['df_label'] = 'Spazio disco libero'; $L['load_label'] = 'Carico CPU'; $L['ping_droprate_label'] = 'Tasso di pacchetti persi'; $L['ping_label'] = 'Latenza ping'; $L['swap_label'] = 'Swap libero'; $L['Partition_label'] = 'Partizione'; $L['Host_label'] = 'Host'; $L['Intro_label'] = 'Ogni server ha una lista predefinita di allarmi di default. Solo alcuni possono essere personalizzati. <br/> Questa pagina mostra solo gli allarmi personalizzati su <a href="${0}">${0}</a>.'; $L['Download_label'] = 'Di default, le modifiche agli allarmi fatte su <a href="${0}">${0}</a> sono applicate ogni notte. <br/> Il tasto "Scarica allarmi personalizzati" scarica la configurazione subito.'; $L['max_fail_label'] = 'Critica sopra'; $L['min_fail_label'] = 'Critica sotto'; $L['max_warn_label'] = 'Media sopra'; $L['min_warn_label'] = 'Media sotto';
NethServer/nethserver-lang
locale/it/server-manager/NethServer_Module_Alerts.php
PHP
gpl-3.0
1,563
// dependencies define(['mvc/ui/ui-tabs', 'mvc/ui/ui-misc', 'mvc/ui/ui-portlet', 'utils/utils', 'plugin/models/chart', 'plugin/models/group', 'plugin/views/group', 'plugin/views/settings', 'plugin/views/types'], function(Tabs, Ui, Portlet, Utils, Chart, Group, GroupView, SettingsView, TypesView) { /** * The charts editor holds the tabs for selecting chart types, chart configuration * and data group selections. */ return Backbone.View.extend({ // initialize initialize: function(app, options){ // link this var self = this; // link application this.app = app; // get current chart object this.chart = this.app.chart; // message element this.message = new Ui.Message(); // create portlet this.portlet = new Portlet.View({ icon : 'fa-bar-chart-o', title: 'Editor', operations : { 'save' : new Ui.ButtonIcon({ icon : 'fa-save', tooltip : 'Draw Chart', title : 'Draw', onclick : function() { self._saveChart(); } }), 'back' : new Ui.ButtonIcon({ icon : 'fa-caret-left', tooltip : 'Return to Viewer', title : 'Cancel', onclick : function() { // show viewer/viewport self.app.go('viewer'); // reset chart self.app.storage.load(); } }) } }); // // grid with chart types // this.types = new TypesView(app, { onchange : function(chart_type) { // get chart definition var chart_definition = self.app.types.get(chart_type); if (!chart_definition) { console.debug('FAILED - Editor::onchange() - Chart type not supported.'); } // parse chart definition self.chart.definition = chart_definition; // reset type relevant chart content self.chart.settings.clear(); // update chart type self.chart.set({type: chart_type}); // set modified flag self.chart.set('modified', true); // log console.debug('Editor::onchange() - Switched chart type.'); }, ondblclick : function(chart_id) { self._saveChart(); } }); // // tabs // this.tabs = new Tabs.View({ title_new : 'Add Data', onnew : function() { var group = self._addGroupModel(); self.tabs.show(group.id); } }); // // main/default tab // // construct elements this.title = new Ui.Input({ placeholder: 'Chart title', onchange: function() { self.chart.set('title', self.title.value()); } }); // append element var $main = $('<div/>'); $main.append(Utils.wrap((new Ui.Label({ title : 'Provide a chart title:'})).$el)); $main.append(Utils.wrap(this.title.$el)); $main.append(Utils.wrap(this.types.$el)); // add tab this.tabs.add({ id : 'main', title : 'Start', $el : $main }); // // main settings tab // // create settings view this.settings = new SettingsView(this.app); // add tab this.tabs.add({ id : 'settings', title : 'Configuration', $el : this.settings.$el }); // append tabs this.portlet.append(this.message.$el); this.portlet.append(this.tabs.$el); // elements this.setElement(this.portlet.$el); // hide back button on startup this.tabs.hideOperation('back'); // chart events var self = this; this.chart.on('change:title', function(chart) { self._refreshTitle(); }); this.chart.on('change:type', function(chart) { self.types.value(chart.get('type')); }); this.chart.on('reset', function(chart) { self._resetChart(); }); this.app.chart.on('redraw', function(chart) { self.portlet.showOperation('back'); }); // groups events this.app.chart.groups.on('add', function(group) { self._addGroup(group); }); this.app.chart.groups.on('remove', function(group) { self._removeGroup(group); }); this.app.chart.groups.on('reset', function(group) { self._removeAllGroups(); }); this.app.chart.groups.on('change:key', function(group) { self._refreshGroupKey(); }); // reset this._resetChart(); }, // hide show: function() { this.$el.show(); }, // hide hide: function() { this.$el.hide(); }, // refresh title _refreshTitle: function() { var title = this.chart.get('title'); this.portlet.title(title); this.title.value(title); }, // refresh group _refreshGroupKey: function() { var self = this; var counter = 0; this.chart.groups.each(function(group) { var title = group.get('key', ''); if (title == '') { title = 'Data label'; } self.tabs.title(group.id, ++counter + ': ' + title); }); }, // add group model _addGroupModel: function() { var group = new Group({ id : Utils.uuid() }); this.chart.groups.add(group); return group; }, // add group tab _addGroup: function(group) { // link this var self = this; // create view var group_view = new GroupView(this.app, {group: group}); // add new tab this.tabs.add({ id : group.id, $el : group_view.$el, ondel : function() { self.chart.groups.remove(group.id); } }); // update titles this._refreshGroupKey(); // reset this.chart.set('modified', true); }, // remove group _removeGroup: function(group) { this.tabs.del(group.id); // update titles this._refreshGroupKey(); // reset this.chart.set('modified', true); }, // remove group _removeAllGroups: function(group) { this.tabs.delRemovable(); }, // reset _resetChart: function() { // reset chart details this.chart.set('id', Utils.uuid()); this.chart.set('type', 'nvd3_bar'); this.chart.set('dataset_id', this.app.options.config.dataset_id); this.chart.set('title', 'New Chart'); // reset back button this.portlet.hideOperation('back'); }, // create chart _saveChart: function() { // update chart data this.chart.set({ type : this.types.value(), title : this.title.value(), date : Utils.time() }); // make sure that at least one data group is available if (this.chart.groups.length == 0) { this.message.update({message: 'Please select data columns before drawing the chart.'}); var group = this._addGroupModel(); this.tabs.show(group.id); return; } // make sure that all necessary columns are assigned var self = this; var valid = true; var chart_def = this.chart.definition; this.chart.groups.each(function(group) { if (!valid) { return; } for (var key in chart_def.columns) { if (group.attributes[key] == 'null') { self.message.update({status: 'danger', message: 'This chart type requires column types not found in your tabular file.'}); self.tabs.show(group.id); valid = false; return; } } }); // validate if columns have been selected if (!valid) { return; } // show viewport this.app.go('viewer'); // wait until chart is ready var self = this; this.app.deferred.execute(function() { // save self.app.storage.save(); // trigger redraw self.chart.trigger('redraw'); }); } }); });
mikel-egana-aranguren/SADI-Galaxy-Docker
galaxy-dist/config/plugins/visualizations/charts/static/views/editor.js
JavaScript
gpl-3.0
9,412
/** * This file is part of RT2D, a 2D OpenGL framework. * * - Copyright 2017 Rik Teerling <rik@onandoffables.com> * - Initial commit */ #include "canvas.h" Canvas::Canvas() : Entity() { this->init(16); } Canvas::Canvas(int pixelsize) : Entity() { this->init(pixelsize); } Canvas::~Canvas() { } void Canvas::update(float deltaTime) { } void Canvas::init(int pixelsize) { this->position = Point2(SWIDTH/2, SHEIGHT/2); this->scale = Point2(pixelsize, pixelsize); // width, height, bitdepth, filter, wrap PixelBuffer tmp = PixelBuffer(SWIDTH/pixelsize, SHEIGHT/pixelsize, 4, 0, 0); this->addDynamicSprite(&tmp); // get the pixels from the texture and make the framebuffer point to it this->_framebuffer = this->sprite()->texture()->pixels(); this->_width = SWIDTH / pixelsize; this->_height = SHEIGHT / pixelsize; backgroundcolor = RGBAColor(0, 0, 0, 0); this->fill(backgroundcolor); } void Canvas::setPixel(int x, int y, RGBAColor color) { this->_framebuffer->setPixel(x, y, color); } RGBAColor Canvas::getPixel(int x, int y) { return this->_framebuffer->getPixel(x, y); } void Canvas::clearPixel(int x, int y) { this->_framebuffer->setPixel(x, y, backgroundcolor); } void Canvas::fill(RGBAColor color) { // fill framebuffer with color for (long y=0; y<_framebuffer->height; y++) { for (long x=0; x<_framebuffer->width; x++) { this->setPixel(x, y, color); } } } void Canvas::drawSprite(const PixelSprite& spr) { size_t s = spr.pixels.size(); for (size_t i = 0; i < s; i++) { this->setPixel(spr.pixels[i].position.x + spr.position.x, spr.pixels[i].position.y + spr.position.y, spr.pixels[i].color); } } void Canvas::clearSprite(const PixelSprite& spr) { size_t s = spr.pixels.size(); for (size_t i = 0; i < s; i++) { this->clearPixel(spr.pixels[i].position.x + spr.position.x, spr.pixels[i].position.y + spr.position.y); } } void Canvas::drawLine(Vector2f from, Vector2f to, RGBAColor color) { float x0 = from.x; float y0 = from.y; float x1 = to.x; float y1 = to.y; bool steep = false; if (std::abs(x0-x1) < std::abs(y0-y1)) { std::swap(x0, y0); std::swap(x1, y1); steep = true; } if (x0 > x1) { std::swap(x0, x1); std::swap(y0, y1); } int dx = x1-x0; int dy = y1-y0; int derror2 = std::abs(dy)*2; int error2 = 0; int y = y0; for (int x = x0; x <= x1; x++) { if (steep) { this->setPixel(y, x, color); } else { this->setPixel(x, y, color); } error2 += derror2; if (error2 > dx) { y += (y1 > y0 ? 1 : -1); error2 -= dx*2; } } }
rktrlng/rt2d
rt2d/canvas.cpp
C++
gpl-3.0
2,543
<?php namespace App\Services\Geografico\ObterOsc; use App\Services\BaseService; use App\Dao\Geografico\GeolocalizacaoDao; class Service extends BaseService{ public function executar(){ $conteudoRequisicao = $this->requisicao->getConteudo(); $modelo = new Model($conteudoRequisicao); if($modelo->obterCodigoResposta() === 200){ $requisicao = $modelo->obterRequisicao(); $geolocalizacaoOsc = (new GeolocalizacaoDao())->obterGeolocalizacaoOsc($requisicao->id_osc); if($geolocalizacaoOsc){ $this->resposta->prepararResposta($geolocalizacaoOsc, 200); }else{ $this->resposta->prepararResposta(null, 204); } }else{ $this->resposta->prepararResposta($modelo->obterMensagemResposta(), $modelo->obterCodigoResposta()); } } }
Plataformas-Cidadania/portalosc
app/Services/Geografico/ObterOsc/Service.php
PHP
gpl-3.0
795
package com.dank.festivalapp.lib; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; public class DataBaseHelper extends SQLiteOpenHelper{ //The Android's default system path of your application database. private static final String DATABASE_NAME = "FestivalApp.db"; private static final int DATABASE_VERSION = 1; private static DataBaseHelper mInstance = null; private DataBaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } public static DataBaseHelper getInstance(Context ctx) { /** * use the application context as suggested by CommonsWare. * this will ensure that you dont accidentally leak an Activitys * context (see this article for more information: * http://developer.android.com/resources/articles/avoiding-memory-leaks.html) */ if (mInstance == null) { mInstance = new DataBaseHelper(ctx); } return mInstance; } public boolean isTableExists(SQLiteDatabase db, String tableName) { Cursor cursor = db.rawQuery("select DISTINCT tbl_name from sqlite_master where tbl_name = '"+ tableName +"'", null); if(cursor != null) { if(cursor.getCount() > 0) { cursor.close(); return true; } cursor.close(); } return false; } @Override public void onCreate(SQLiteDatabase db) { } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(DataBaseHelper.class.getName(), "TODO "); } }
dankl/festivalapp-lib
src/com/dank/festivalapp/lib/DataBaseHelper.java
Java
gpl-3.0
1,650
// -*- Mode: Go; indent-tabs-mode: t -*- /* * Copyright (C) 2019-2020 Canonical Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package install import ( "bytes" "fmt" "os/exec" "strconv" "strings" "time" "github.com/snapcore/snapd/gadget" "github.com/snapcore/snapd/gadget/quantity" "github.com/snapcore/snapd/logger" "github.com/snapcore/snapd/osutil" "github.com/snapcore/snapd/strutil" ) var ( ensureNodesExist = ensureNodesExistImpl ) var createdPartitionGUID = []string{ "0FC63DAF-8483-4772-8E79-3D69D8477DE4", // Linux filesystem data "0657FD6D-A4AB-43C4-84E5-0933C84B4F4F", // Linux swap partition } // creationSupported returns whether we support and expect to create partitions // of the given type, it also means we are ready to remove them for re-installation // or retried installation if they are appropriately marked with createdPartitionAttr. func creationSupported(ptype string) bool { return strutil.ListContains(createdPartitionGUID, strings.ToUpper(ptype)) } // createMissingPartitions creates the partitions listed in the laid out volume // pv that are missing from the existing device layout, returning a list of // structures that have been created. func createMissingPartitions(dl *gadget.OnDiskVolume, pv *gadget.LaidOutVolume) ([]gadget.OnDiskStructure, error) { buf, created := buildPartitionList(dl, pv) if len(created) == 0 { return created, nil } logger.Debugf("create partitions on %s: %s", dl.Device, buf.String()) // Write the partition table. By default sfdisk will try to re-read the // partition table with the BLKRRPART ioctl but will fail because the // kernel side rescan removes and adds partitions and we have partitions // mounted (so it fails on removal). Use --no-reread to skip this attempt. cmd := exec.Command("sfdisk", "--append", "--no-reread", dl.Device) cmd.Stdin = buf if output, err := cmd.CombinedOutput(); err != nil { return created, osutil.OutputErr(output, err) } // Re-read the partition table if err := reloadPartitionTable(dl.Device); err != nil { return nil, err } // Make sure the devices for the partitions we created are available if err := ensureNodesExist(created, 5*time.Second); err != nil { return nil, fmt.Errorf("partition not available: %v", err) } return created, nil } // buildPartitionList builds a list of partitions based on the current // device contents and gadget structure list, in sfdisk dump format, and // returns a partitioning description suitable for sfdisk input and a // list of the partitions to be created. func buildPartitionList(dl *gadget.OnDiskVolume, pv *gadget.LaidOutVolume) (sfdiskInput *bytes.Buffer, toBeCreated []gadget.OnDiskStructure) { sectorSize := dl.SectorSize // Keep track what partitions we already have on disk seen := map[quantity.Offset]bool{} for _, s := range dl.Structure { start := s.StartOffset / quantity.Offset(sectorSize) seen[start] = true } // Check if the last partition has a system-data role canExpandData := false if n := len(pv.LaidOutStructure); n > 0 { last := pv.LaidOutStructure[n-1] if last.VolumeStructure.Role == gadget.SystemData { canExpandData = true } } // The partition index pIndex := 0 // Write new partition data in named-fields format buf := &bytes.Buffer{} for _, p := range pv.LaidOutStructure { if !p.IsPartition() { continue } pIndex++ s := p.VolumeStructure // Skip partitions that are already in the volume start := p.StartOffset / quantity.Offset(sectorSize) if seen[start] { continue } // Only allow the creation of partitions with known GUIDs // TODO:UC20: also provide a mechanism for MBR (RPi) ptype := partitionType(dl.Schema, p.Type) if dl.Schema == "gpt" && !creationSupported(ptype) { logger.Noticef("cannot create partition with unsupported type %s", ptype) continue } // Check if the data partition should be expanded size := s.Size if s.Role == gadget.SystemData && canExpandData && quantity.Size(p.StartOffset)+s.Size < dl.Size { size = dl.Size - quantity.Size(p.StartOffset) } // Can we use the index here? Get the largest existing partition number and // build from there could be safer if the disk partitions are not consecutive // (can this actually happen in our images?) node := deviceName(dl.Device, pIndex) fmt.Fprintf(buf, "%s : start=%12d, size=%12d, type=%s, name=%q\n", node, p.StartOffset/quantity.Offset(sectorSize), size/sectorSize, ptype, s.Name) toBeCreated = append(toBeCreated, gadget.OnDiskStructure{ LaidOutStructure: p, Node: node, Size: size, }) } return buf, toBeCreated } func partitionType(label, ptype string) string { t := strings.Split(ptype, ",") if len(t) < 1 { return "" } if len(t) == 1 { return t[0] } if label == "gpt" { return t[1] } return t[0] } func deviceName(name string, index int) string { if len(name) > 0 { last := name[len(name)-1] if last >= '0' && last <= '9' { return fmt.Sprintf("%sp%d", name, index) } } return fmt.Sprintf("%s%d", name, index) } // removeCreatedPartitions removes partitions added during a previous install. func removeCreatedPartitions(lv *gadget.LaidOutVolume, dl *gadget.OnDiskVolume) error { indexes := make([]string, 0, len(dl.Structure)) for i, s := range dl.Structure { if wasCreatedDuringInstall(lv, s) { logger.Noticef("partition %s was created during previous install", s.Node) indexes = append(indexes, strconv.Itoa(i+1)) } } if len(indexes) == 0 { return nil } // Delete disk partitions logger.Debugf("delete disk partitions %v", indexes) cmd := exec.Command("sfdisk", append([]string{"--no-reread", "--delete", dl.Device}, indexes...)...) if output, err := cmd.CombinedOutput(); err != nil { return osutil.OutputErr(output, err) } // Reload the partition table if err := reloadPartitionTable(dl.Device); err != nil { return err } // Re-read the partition table from the device to update our partition list if err := gadget.UpdatePartitionList(dl); err != nil { return err } // Ensure all created partitions were removed if remaining := createdDuringInstall(lv, dl); len(remaining) > 0 { return fmt.Errorf("cannot remove partitions: %s", strings.Join(remaining, ", ")) } return nil } // ensureNodeExists makes sure the device nodes for all device structures are // available and notified to udev, within a specified amount of time. func ensureNodesExistImpl(dss []gadget.OnDiskStructure, timeout time.Duration) error { t0 := time.Now() for _, ds := range dss { found := false for time.Since(t0) < timeout { if osutil.FileExists(ds.Node) { found = true break } time.Sleep(100 * time.Millisecond) } if found { if err := udevTrigger(ds.Node); err != nil { return err } } else { return fmt.Errorf("device %s not available", ds.Node) } } return nil } // reloadPartitionTable instructs the kernel to re-read the partition // table of a given block device. func reloadPartitionTable(device string) error { // Re-read the partition table using the BLKPG ioctl, which doesn't // remove existing partitions, only appends new partitions with the right // size and offset. As long as we provide consistent partitioning from // userspace we're safe. output, err := exec.Command("partx", "-u", device).CombinedOutput() if err != nil { return osutil.OutputErr(output, err) } return nil } // udevTrigger triggers udev for the specified device and waits until // all events in the udev queue are handled. func udevTrigger(device string) error { if output, err := exec.Command("udevadm", "trigger", "--settle", device).CombinedOutput(); err != nil { return osutil.OutputErr(output, err) } return nil } // wasCreatedDuringInstall returns if the OnDiskStructure was created during // install by referencing the gadget volume. A structure is only considered to // be created during install if it is a role that is created during install and // the start offsets match. We specifically don't look at anything on the // structure such as filesystem information since this may be incomplete due to // a failed installation, or due to the partial layout that is created by some // ARM tools (i.e. ptool and fastboot) when flashing images to internal MMC. func wasCreatedDuringInstall(lv *gadget.LaidOutVolume, s gadget.OnDiskStructure) bool { // for a structure to have been created during install, it must be one of // the system-boot, system-data, or system-save roles from the gadget, and // as such the on disk structure must exist in the exact same location as // the role from the gadget, so only return true if the provided structure // has the exact same StartOffset as one of those roles for _, gs := range lv.LaidOutStructure { // TODO: how to handle ubuntu-save here? maybe a higher level function // should decide whether to delete it or not? switch gs.Role { case gadget.SystemSave, gadget.SystemData, gadget.SystemBoot: // then it was created during install or is to be created during // install, see if the offset matches the provided on disk structure // has if s.StartOffset == gs.StartOffset { return true } } } return false } // createdDuringInstall returns a list of partitions created during the // install process. func createdDuringInstall(lv *gadget.LaidOutVolume, layout *gadget.OnDiskVolume) (created []string) { created = make([]string, 0, len(layout.Structure)) for _, s := range layout.Structure { if wasCreatedDuringInstall(lv, s) { created = append(created, s.Node) } } return created }
chipaca/snappy
gadget/install/partition.go
GO
gpl-3.0
10,175
// ---------------------------------------------------------------------- // File: VersionedHashRevisionTracker.cc // Author: Georgios Bitzes - CERN // ---------------------------------------------------------------------- /************************************************************************ * quarkdb - a redis-like highly available key-value store * * Copyright (C) 2019 CERN/Switzerland * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>.* ************************************************************************/ #include "VersionedHashRevisionTracker.hh" #include "utils/Macros.hh" #include "Formatter.hh" namespace quarkdb { //------------------------------------------------------------------------------ // Indicate which revision we're referring to. When called multiple times // for the same object, the given value MUST be the same. //------------------------------------------------------------------------------ void VersionedHashRevision::setRevisionNumber(uint64_t rev) { if(currentRevision != 0) { qdb_assert(currentRevision == rev); } else { currentRevision = rev; } } //------------------------------------------------------------------------------ // Add to update batch - empty value indicates deletion //------------------------------------------------------------------------------ void VersionedHashRevision::addUpdate(std::string_view field, std::string_view value) { updateBatch.emplace_back(field, value); } //------------------------------------------------------------------------------ // Serialize contents //------------------------------------------------------------------------------ std::string VersionedHashRevision::serialize() const { return Formatter::vhashRevision(currentRevision, updateBatch).val; } //------------------------------------------------------------------------------ // Get revision for a specific key //------------------------------------------------------------------------------ VersionedHashRevision& VersionedHashRevisionTracker::forKey(std::string_view key) { return contents[std::string(key)]; } //------------------------------------------------------------------------------ // Iterate through contents //------------------------------------------------------------------------------ std::map<std::string, VersionedHashRevision>::iterator VersionedHashRevisionTracker::begin() { return contents.begin(); } std::map<std::string, VersionedHashRevision>::iterator VersionedHashRevisionTracker::end() { return contents.end(); } }
gbitzes/quarkdb
src/storage/VersionedHashRevisionTracker.cc
C++
gpl-3.0
3,494
package ems.server.protocol; import ems.server.domain.Device; import ems.server.domain.EventSeverity; import ems.server.domain.EventType; import ems.server.utils.EventHelper; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; /** * EventAwareResponseHandler * Created by thebaz on 9/15/14. */ public class EventAwareResponseHandler implements ResponseHandler { private final DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'"); private final Device device; public EventAwareResponseHandler(Device device) { this.device = device; format.setTimeZone(TimeZone.getTimeZone("UTC")); } @Override public void onTimeout(String variable) { EventHelper.getInstance().addEvent(device, EventType.EVENT_NETWORK, EventSeverity.EVENT_WARN); } @Override public void onSuccess(String variable) { //do nothing } @Override public void onError(String variable, int errorCode, String errorDescription) { EventSeverity eventSeverity = EventSeverity.EVENT_ERROR; EventType eventType = EventType.EVENT_PROTOCOL; String description = "Event of type: \'" + eventType + "\' at: " + format.format(new Date(System.currentTimeMillis())) + " with severity: \'" + eventSeverity + "\' for device: " + device.getName() + ". Error code:" + errorCode + ", Error description: " + errorDescription; EventHelper.getInstance().addEvent(device, eventType, eventSeverity, description); } }
thebaz73/ems-server
src/main/java/ems/server/protocol/EventAwareResponseHandler.java
Java
gpl-3.0
1,600
<?php /* COPYRIGHT 2008 - see www.milliondollarscript.com for a list of authors This file is part of the Million Dollar Script. Million Dollar Script is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Million Dollar Script is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with the Million Dollar Script. If not, see <http://www.gnu.org/licenses/>. */ require_once ('category.inc.php'); require_once ('lists.inc.php'); require_once ('dynamic_forms.php'); global $ad_tag_to_field_id; global $ad_tag_to_search; global $CACHE_ENABLED; if ($CACHE_ENABLED=='YES') { $dir = dirname(__FILE__); $dir = preg_split ('%[/\\\]%', $dir); $blank = array_pop($dir); $dir = implode('/', $dir); include ("$dir/cache/form1_cache.inc.php"); $ad_tag_to_search = $tag_to_search; $ad_tag_to_field_id = $tag_to_field_id; } else { $ad_tag_to_search = tag_to_search_init(1); $ad_tag_to_field_id = ad_tag_to_field_id_init(); } ##################################### function ad_tag_to_field_id_init () { global $CACHE_ENABLED; if ($CACHE_ENABLED=='YES') { global $ad_tag_to_field_id; return $ad_tag_to_field_id; } global $label; $sql = "SELECT *, t2.field_label AS NAME FROM `form_fields` as t1, form_field_translations as t2 where t1.field_id = t2.field_id AND t2.lang='".$_SESSION['MDS_LANG']."' AND form_id=1 ORDER BY list_sort_order "; $result = mysql_query($sql) or die (mysql_error()); # do a query for each field while ($fields = mysql_fetch_array($result, MYSQL_ASSOC)) { //$form_data = $row[] $tag_to_field_id[$fields['template_tag']]['field_id'] = $fields['field_id']; $tag_to_field_id[$fields['template_tag']]['field_type'] = $fields['field_type']; $tag_to_field_id[$fields['template_tag']]['field_label'] = $fields['NAME']; } $tag_to_field_id["ORDER_ID"]['field_id'] = 'order_id'; $tag_to_field_id["ORDER_ID"]['field_label'] = 'Order ID'; //$tag_to_field_id["ORDER_ID"]['field_label'] = $label["employer_resume_list_date"]; $tag_to_field_id["BID"]['field_id'] = 'banner_id'; $tag_to_field_id["BID"]['field_label'] = 'Grid ID'; $tag_to_field_id["USER_ID"]['field_id'] = 'user_id'; $tag_to_field_id["USER_ID"]['field_label'] = 'User ID'; $tag_to_field_id["AD_ID"]['field_id'] = 'ad_id'; $tag_to_field_id["AD_ID"]['field_label'] = 'Ad ID'; $tag_to_field_id["DATE"]['field_id'] = 'ad_date'; $tag_to_field_id["DATE"]['field_label'] = 'Date'; return $tag_to_field_id; } ###################################################################### function load_ad_values ($ad_id) { $prams = array(); $sql = "SELECT * FROM `ads` WHERE ad_id='$ad_id' "; $result = mysql_query($sql) or die ($sql. mysql_error()); if ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { $prams['ad_id'] = $ad_id; $prams['user_id'] = $row['user_id']; $prams['order_id'] = $row['order_id']; $prams['banner_id'] = $row['banner_id']; $sql = "SELECT * FROM form_fields WHERE form_id=1 AND field_type != 'SEPERATOR' AND field_type != 'BLANK' AND field_type != 'NOTE' "; $result = mysql_query($sql) or die(mysql_error()); while ($fields = mysql_fetch_array($result, MYSQL_ASSOC)) { $prams[$fields['field_id']] = $row[$fields['field_id']]; if ($fields['field_type']=='DATE') { $day = $_REQUEST[$row['field_id']."d"]; $month = $_REQUEST[$row['field_id']."m"]; $year = $_REQUEST[$row['field_id']."y"]; $prams[$fields['field_id']] = "$year-$month-$day"; } elseif (($fields['field_type']=='MSELECT') || ($row['field_type']=='CHECK')) { if (is_array($_REQUEST[$row['field_id']])) { $prams[$fields['field_id']] = implode (",", $_REQUEST[$fields['field_id']]); } else { $prams[$fields['field_id']] = $_REQUEST[$fields['field_id']]; } } } return $prams; } else { return false; } } ######################################################### function assign_ad_template($prams) { global $label; $str = $label['mouseover_ad_template']; $sql = "SELECT * FROM form_fields WHERE form_id='1' AND field_type != 'SEPERATOR' AND field_type != 'BLANK' AND field_type != 'NOTE' "; //echo $sql; $result = mysql_query($sql) or die(mysql_error()); while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { if ($row['field_type']=='IMAGE') { if ((file_exists(UPLOAD_PATH.'images/'.$prams[$row['field_id']]))&&($prams[$row['field_id']])) { $str = str_replace('%'.$row['template_tag'].'%', '<img alt="" src="'. UPLOAD_HTTP_PATH."images/".$prams[$row['field_id']].'" >', $str); } else { //$str = str_replace('%'.$row['template_tag'].'%', '<IMG SRC="'.UPLOAD_HTTP_PATH.'images/no-image.gif" WIDTH="150" HEIGHT="150" BORDER="0" ALT="">', $str); $str = str_replace('%'.$row['template_tag'].'%', '', $str); } } else { $str = str_replace('%'.$row['template_tag'].'%', get_template_value($row['template_tag'],1), $str); } $str = str_replace('$'.$row['template_tag'].'$', get_template_field_label($row['template_tag'],1), $str); } return $str; } ######################################################### function display_ad_form ($form_id, $mode, $prams) { global $label; global $error; global $BID; if ($prams == '' ) { $prams['mode'] = $_REQUEST['mode']; $prams['ad_id']= $_REQUEST['ad_id']; $prams['banner_id'] = $BID; $prams['user_id'] = $_REQUEST['user_id']; $sql = "SELECT * FROM form_fields WHERE form_id='$form_id' AND field_type != 'SEPERATOR' AND field_type != 'BLANK' AND field_type != 'NOTE' "; //echo $sql; $result = mysql_query($sql) or die(mysql_error()); while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { //$prams[$row[field_id]] = $_REQUEST[$row[field_id]]; if ($row['field_type']=='DATE') { $day = $_REQUEST[$row['field_id']."d"]; $month = $_REQUEST[$row['field_id']."m"]; $year = $_REQUEST[$row['field_id']."y"]; $prams[$row['field_id']] = "$year-$month-$day"; } elseif (($row['field_type']=='MSELECT') || ($row['field_type']=='CHECK')) { if (is_array($_REQUEST[$row['field_id']])) { $prams[$row['field_id']] = implode (",", $_REQUEST[$row['field_id']]); } else { $prams[$row['field_id']] = $_REQUEST[$row['field_id']]; } } else { $prams[$row['field_id']] = stripslashes ($_REQUEST[$row['field_id']]); } } } if (!defined('SCW_INCLUDE')) { ?> <script type='text/JavaScript' src='<?php echo BASE_HTTP_PATH."scw/scw_js.php?lang=".$_SESSION['MDS_LANG']; ?>'></script> <?php define ('SCW_INCLUDE', 'Y'); } ?> <form method="POST" action="<?php htmlentities($_SERVER['PHP_SELF']); ?>" name="form1" onsubmit=" form1.savebutton.disabled=true;" enctype="multipart/form-data"> <input type="hidden" name="mode" size="" value="<?php echo $mode; ?>"> <input type="hidden" name="ad_id" size="" value="<?php echo $prams['ad_id']; ?>"> <input type="hidden" name="user_id" size="" value="<?php echo $prams['user_id']; ?>"> <input type="hidden" name="order_id" size="" value="<?php echo $prams['order_id']; ?>"> <input type="hidden" name="banner_id" size="" value="<?php echo $prams['banner_id']; ?>"> <table cellSpacing="1" cellPadding="5" class="ad_data" id="ad" > <?php if (($error != '' ) && ($mode!='EDIT')) { ?> <tr> <td bgcolor="#F2F2F2" colspan="2"><?php echo "<span class='error_msg_label'>".$label['ad_save_error']."</span><br> <b>".$error."</b>"; ?></td> </tr> <?php } ?> <tr bgColor="#ffffff"> <td bgColor="#eaeaea"> <?php if ($mode == "EDIT") { echo "[Ad Form]"; } // section 1 display_form ($form_id, $mode, $prams, 1); ?> </tr> <tr><td colspan="2" bgcolor="#ffffff"> <input type="hidden" name="save" id="save101" value=""> <?php if ($mode=='edit') { ?> <input class="form_submit_button" TYPE="SUBMIT" class='big_button' name="savebutton" value="<?php echo $label['ad_save_button'];?>" onClick="save101.value='1';"> <?php } ?> </td></tr> </table> </form> <?php } ########################################################################### function list_ads ($admin=false, $order, $offset, $list_mode='ALL', $user_id='') { ## Globals global $label; global $tag_to_field_id; $tag_to_field_id = ad_tag_to_field_id_init(); ########################################### # Load in the form data, including column names # (dont forget LANGUAGE TOO) global $ad_tag_to_field_id; $records_per_page = 40; global $label; // languages array $order_str = $order; if ($order == '') { $order = " `order_id` "; } else { $order = " `$order` "; } global $action; // process search result if ($_REQUEST['action'] == 'search') { $q_string = generate_q_string(1); $where_sql = generate_search_sql(1); } // DATE_FORMAT(`adate`, '%d-%b-%Y') AS formatted_date $order = $_REQUEST['order_by']; if ($_REQUEST['ord']=='asc') { $ord = 'ASC'; } elseif ($_REQUEST['ord']=='desc') { $ord = 'DESC'; } else { $ord = 'DESC'; // sort descending by default } if ($order == '') { $order = " `ad_date` "; } else { $order = " `$order` "; } global $BID; if ($list_mode == 'USER' ) { if (!is_numeric($user_id)) { $user_id = $_SESSION['MDS_ID']; } $sql = "Select * FROM `ads` as t1, `orders` as t2 WHERE t1.ad_id=t2.ad_id AND t1.order_id > 0 AND t1.banner_id='".$BID."' AND t1.user_id='".$user_id."' AND (t2.status = 'completed' OR t2.status = 'expired') $where_sql ORDER BY $order $ord "; } elseif ($list_mode =='TOPLIST') { // $sql = "SELECT *, DATE_FORMAT(MAX(order_date), '%Y-%c-%d') as max_date, sum(quantity) AS pixels FROM orders, ads where ads.order_id=orders.order_id AND status='completed' and orders.banner_id='$BID' GROUP BY orders.user_id, orders.banner_id order by pixels desc "; } else { $sql = "Select * FROM `ads` as t1, `orders` AS t2 WHERE t1.ad_id=t2.ad_id AND t1.banner_id='$BID' and t1.order_id > 0 $where_sql ORDER BY $order $ord "; } //echo "[".$sql."]"; $result = mysql_query($sql) or die (mysql_error()); ############ # get the count $count = mysql_num_rows($result); if ($count > $records_per_page) { mysql_data_seek($result, $offset); } if ($count > 0 ) { if ($pages == 1) { } elseif ($list_mode!='USER') { $pages = ceil($count / $records_per_page); $cur_page = $_REQUEST['offset'] / $records_per_page; $cur_page++; echo "<center>"; //echo "Page $cur_page of $pages - "; $label["navigation_page"] = str_replace ("%CUR_PAGE%", $cur_page, $label["navigation_page"]); $label["navigation_page"] = str_replace ("%PAGES%", $pages, $label["navigation_page"]); echo "<span > ".$label["navigation_page"]."</span> "; $nav = nav_pages_struct($result, $q_string, $count, $records_per_page); $LINKS = 10; render_nav_pages($nav, $LINKS, $q_string, $show_emp, $cat); echo "</center>"; } $dir = dirname(__FILE__); $dir = preg_split ('%[/\\\]%', $dir); $blank = array_pop($dir); $dir = implode('/', $dir); include ($dir.'/mouseover_box.htm'); // edit this file to change the style of the mouseover box! echo '<script language="JAVASCRIPT">'; include ('mouseover_js.inc.php'); echo '</script>'; ?> <table border='0' bgcolor='#d9d9d9' cellspacing="1" cellpadding="5" id="adslist" > <tr bgcolor="#EAEAEA"> <?php if ($admin == true ) { echo '<td class="list_header_cell">&nbsp;</td>'; } if ($list_mode == 'USER' ) { echo '<td class="list_header_cell">&nbsp;</td>'; } echo_list_head_data(1, $admin); if (($list_mode == 'USER' ) || ($admin)) { echo '<td class="list_header_cell">'.$label['ads_inc_pixels_col'].'</td>'; echo '<td class="list_header_cell">'.$label['ads_inc_expires_col'].'</td>'; echo '<td class="list_header_cell" >'.$label['ad_list_status'].'</td>'; } ?> </tr> <?php $i=0; global $prams; while (($prams = mysql_fetch_array($result, MYSQL_ASSOC)) && ($i < $records_per_page)) { $i++; ?> <tr bgcolor="ffffff" onmouseover="old_bg=this.getAttribute('bgcolor');this.setAttribute('bgcolor', '#FBFDDB', 0);" onmouseout="this.setAttribute('bgcolor', old_bg, 0);"> <?php if ($admin == true ) { echo '<td class="list_data_cell" >'; ?> <!--<input style="font-size: 8pt" type="button" value="Delete" onClick="if (!confirmLink(this, 'Delete, are you sure?')) {return false;} window.location='<?php echo htmlentities($_SERVER['PHP_SELF']);?>?action=delete&ad_id=<?php echo $prams['ad_id']; ?>'"><br>!--> <input type="button" style="font-size: 8pt" value="Edit" onClick="window.location='<?php echo htmlentities($_SERVER['PHP_SELF']);?>?action=edit&ad_id=<?php echo $prams['ad_id']; ?>'"> <?php echo '</td>'; } if ($list_mode == 'USER' ) { echo '<td class="list_data_cell">'; ?> <!--<input style="font-size: 8pt" type="button" value="Delete" onClick="if (!confirmLink(this, 'Delete, are you sure?')) {return false;} window.location='<?php echo htmlentities($_SERVER['PHP_SELF']);?>?action=delete&ad_id=<?php echo $prams['ad_id']; ?>'"><br>--> <input type="button" style="font-size: 8pt" value="Edit" onClick="window.location='<?php echo htmlentities($_SERVER['PHP_SELF']);?>?ad_id=<?php echo $prams['ad_id']; ?>'"> <?php echo '</td>'; } echo_ad_list_data($admin); if (($list_mode == 'USER' ) || ($admin)) { ///////////////// echo '<td class="list_data_cell"><img src="get_order_image.php?BID='.$BID.'&aid='.$prams['ad_id'].'"></td>'; ////////////////// echo '<td>'; if ($prams['days_expire'] > 0) { if ($prams['published']!='Y') { $time_start = strtotime(gmdate('r')); } else { $time_start = strtotime($prams['date_published']." GMT"); } $elapsed_time = strtotime(gmdate('r')) - $time_start; $elapsed_days = floor ($elapsed_time / 60 / 60 / 24); $exp_time = ($prams['days_expire'] * 24 * 60 * 60); $exp_time_to_go = $exp_time - $elapsed_time; $exp_days_to_go = floor ($exp_time_to_go / 60 / 60 / 24); $to_go = elapsedtime($exp_time_to_go); $elapsed = elapsedtime($elapsed_time); if ($prams['status']=='expired') { $days = "<a href='orders.php'>".$label['ads_inc_expied_stat']."</a>"; } elseif ($prams['date_published']=='') { $days = $label['ads_inc_nyp_stat']; } else { $days = str_replace ('%ELAPSED%', $elapsed, $label['ads_inc_elapsed_stat']); $days = str_replace ('%TO_GO%', $to_go, $days); //$days = "$elapsed elapsed<br> $to_go to go "; } //$days = $elapsed_time; //print_r($prams); } else { $days = $label['ads_inc_nev_stat']; } echo $days; echo '</td>'; ///////////////// if ($prams['published']=='Y') { $pub =$label['ads_inc_pub_stat']; } else { $pub = $label['ads_inc_npub_stat']; } if ($prams['approved']=='Y') { $app = $label['ads_inc_app_stat'].', '; } else { $app = $label['ads_inc_napp_stat'].', '; } //$label['ad_list_st_'.$prams['status']]." echo '<td class="list_data_cell">'.$app.$pub."</td>"; } ?> </tr> <?php //$prams[file_photo] = ''; // $new_name=''; } echo "</table>"; } else { echo "<center><font size='2' face='Arial'><b>".$label["ads_not_found"].".</b></font></center>"; } return $count; } ######################################################## function delete_ads_files ($ad_id) { $sql = "select * from form_fields where form_id=1 "; $result = mysql_query ($sql) or die (mysql_error()); while ($row=mysql_fetch_array($result, MYSQL_ASSOC)) { $field_id = $row['field_id']; $field_type = $row['field_type']; if (($field_type == "FILE")) { deleteFile("ads", "ad_id", $ad_id, $field_id); } if (($field_type == "IMAGE")){ deleteImage("ads", "ad_id", $ad_id, $field_id); } } } #################### function delete_ad ($ad_id) { delete_ads_files ($ad_id); $sql = "delete FROM `ads` WHERE `ad_id`='".$ad_id."' "; $result = mysql_query($sql) or die (mysql_error().$sql); } ################################ function search_category_tree_for_ads() { if (func_num_args() > 0 ) { $cat_id = func_get_arg(0); } else { $cat_id = $_REQUEST[cat]; } $sql = "select search_set from categories where category_id='$cat_id' "; $result2 = mysql_query ($sql) or die (mysql_error()); $row = mysql_fetch_array($result2); $search_set = $row[search_set]; $sql = "select * from form_fields where field_type='CATEGORY' AND form_id='1'"; $result = mysql_query ($sql) or die (mysql_error()); $i=0; if (mysql_num_rows($result) >0) { while ($row=mysql_fetch_array($result, MYSQL_ASSOC)) { if ($i>0) { $where_cat .= " OR "; } $where_cat .= " `$row[field_id]` IN ($search_set) "; $i++; } } if ($where_cat=='') { return " AND 1=2 "; } if ($search_set=='') { return ""; } return " AND ($where_cat) "; } #################### function search_category_for_ads() { if (func_num_args() > 0 ) { $cat_id = func_get_arg(0); } else { $cat_id = $_REQUEST[cat]; } $sql = "select * from form_fields where field_type='CATEGORY' AND form_id='1'"; $result = mysql_query ($sql) or die (mysql_error()); $i=0; if (mysql_num_rows($result) >0) { while ($row=mysql_fetch_array($result, MYSQL_ASSOC)) { if ($i>0) { $where_cat .= " OR "; } $where_cat .= " `$row[field_id]`='$cat_id' "; $i++; } } if ($where_cat=='') { return " AND 1=2 "; } return " AND ($where_cat) "; //$sql ="Select * from posts_table where $where_cat "; //echo $sql."<br/>"; //$result2 = mysql_query ($sql) or die (mysql_error()); } ################## function generate_ad_id () { $query ="SELECT max(`ad_id`) FROM `ads`"; $result = mysql_query($query) or die(mysql_error()); $row = mysql_fetch_row($result); $row[0]++; return $row[0]; } ################# function temp_ad_exists($sid) { $query ="SELECT ad_id FROM `ads` where user_id='$sid' "; $result = mysql_query($query) or die(mysql_error()); // $row = mysql_fetch_row($result); return mysql_num_rows($result); } ################################################################ function insert_ad_data() { if (func_num_args() > 0) { $admin = func_get_arg(0); // admin mode. } $user_id = $_SESSION['MDS_ID']; if ($user_id=='') { $user_id = addslashes(session_id()); } $order_id = $_REQUEST['order_id']; $ad_date = (gmdate("Y-m-d H:i:s")); $banner_id = $_REQUEST['banner_id']; if ($_REQUEST['ad_id'] == '') { $ad_id = generate_ad_id (); $now = (gmdate("Y-m-d H:i:s")); $sql = "REPLACE INTO `ads` (`ad_id`, `order_id`, `user_id`, `ad_date`, `banner_id` ".get_sql_insert_fields(1).") VALUES ('$ad_id', '$order_id', '$user_id', '$ad_date', '$banner_id' ".get_sql_insert_values(1, "ads", "ad_id", $_REQUEST['ad_id'], $user_id).") "; } else { $ad_id = $_REQUEST['ad_id']; if (!$admin) { // make sure that the logged in user is the owner of this ad. if (!is_numeric($_REQUEST['user_id'])) { // temp order (user_id = session_id()) if ($_REQUEST['user_id']!=session_id()) return false; } else { // user is logged in $sql = "select user_id from `ads` WHERE ad_id='".$_REQUEST['ad_id']."'"; $result = mysql_query ($sql) or die(mysql_error()); $row = @mysql_fetch_array($result); if ($_SESSION['MDS_ID']!==$row['user_id']) { return false; // not the owner, hacking attempt! } } } $now = (gmdate("Y-m-d H:i:s")); $sql = "UPDATE `ads` SET `ad_date`='$now' ".get_sql_update_values (1, "ads", "ad_id", $_REQUEST['ad_id'], $user_id)." WHERE ad_id='".$ad_id."'"; } //echo "<hr><b>Insert:</b> $sql<hr>"; //print_r ($_FILES); mysql_query ($sql) or die("[$sql]".mysql_error()); //build_ad_count(0); return $ad_id; } ############################################################### function validate_ad_data($form_id) { return validate_form_data(1); return $error; } ################################################################ function update_blocks_with_ad($ad_id, $user_id) { global $prams; $prams = load_ad_values($ad_id); if ($prams['order_id']>0) { $sql = "UPDATE blocks SET alt_text='".addslashes(get_template_value('ALT_TEXT', 1))."', url='".addslashes(get_template_value('URL', 1))."' WHERE order_id='".$prams['order_id']."' AND user_id='".$user_id."' "; mysql_query($sql) or die(mysql_error()); mds_log("Updated blocks with ad URL, ALT_TEXT", $sql); } } ?>
LauraHilliger/hufemap
include/ads.inc.php
PHP
gpl-3.0
21,673
// binary_frame.go /* Binary Frame Tool. Version: 0.1.1. Date of Creation: 2018-01-28. Author: McArcher. This is a simple Tool which draws a binary Frame around the Content. A Frame consists of logical Ones (1) and has a Spacer of Zeroes (0). So, --- XXX XXX --- Becomes something with a binary Frame with a Spacer: ------- 1111111 1000001 10XXX01 10XXX01 1000001 1111111 ------- This Technique is a great Thing to enclose Dimensions of the "X" into the File. It may be useful for Transmission of Signals in Space or other Places with a great Chances for Signal Corruption. Even when damaged, a Frame or Remains of a Frame may help a lot in the Process of Data Recovery. This Frame may be used as a Transport Package when there is no Package of the Transmission Protocol, and may be used in a universal Range. To comply with this-day Computers, the Algorithm makes Sizes compatible with 8-Bit Bytes, but it is also able to use any Size you want. */ //============================================================================== package main import ( "flag" "fmt" "io/ioutil" "log" "math" "os" "strconv" ) //============================================================================== type bit bool type row_of_bits []bit type field_of_bits []row_of_bits //============================================================================== const bits_in_byte = 8 const FILLED = true const EMPTY = false const ACTION_NONE = 0 const ACTION_ENCODE_F1 = 1 const ACTION_ENCODE_F2 = 2 const ACTION_DECODE_F1 = 3 const ACTION_DECODE_F2 = 4 const ERROR_1 = 1 //============================================================================== var cla_file_in *string var cla_file_out *string var cla_action_type *string var cla_x *string var cla_y *string var action_type uint8 var file_input_path string var file_output_path string var file_input_content []byte var file_output_content []byte var file_input_x uint64 var file_input_y uint64 var file_input_size uint64 // Number of Bytes. var input_field_size uint64 // Number of Bits. var output_field_size uint64 // Number of Bits. var file_input_cols uint64 var file_input_rows uint64 var file_output_cols uint64 var file_output_rows uint64 var field field_of_bits var field_framed field_of_bits //============================================================================== func main() { var err error var err_code uint8 var ok bool // Command Line Arguments. read_cla() // Read Input File. file_input_content, err = ioutil.ReadFile(file_input_path) check_error(err) file_input_size = uint64(len(file_input_content)) input_field_size = file_input_size * bits_in_byte // Check X & Y. if file_input_x <= 0 { fmt.Println("Bad X Size.") os.Exit(ERROR_1) } file_input_cols = file_input_x if (input_field_size % file_input_x) != 0 { fmt.Println("Bad X Size.") os.Exit(ERROR_1) } file_input_rows = input_field_size / file_input_x // Do Action. if action_type == ACTION_ENCODE_F1 { fmt.Println("Encoding (F1) \"" + file_input_path + "\"...") // // Output Size. file_output_cols = file_input_cols + 4 file_output_rows = file_input_rows + 4 output_field_size = file_output_cols * file_output_rows // Report. fmt.Println("Input Data (WxH):", file_input_cols, "x", file_input_rows, ".") /// fmt.Println("Output Data (WxH):", file_output_cols, "x", file_output_rows, ".") /// // Bytes -> Field. field, ok = bytes_to_field(input_field_size, file_input_cols, file_input_rows, file_input_content) check_ok(ok) // Field -> Frame. field_framed, err_code = pack_data_f1(input_field_size, file_input_cols, file_input_rows, field) check_err_code(err_code) // Frame -> Bytes. file_output_content, ok = field_to_bytes(output_field_size, file_output_cols, file_output_rows, field_framed) check_ok(ok) // Bytes -> File. fmt.Println("Writing \"" + file_output_path + "\"...") // err = ioutil.WriteFile(file_output_path, file_output_content, 0644) check_error(err) } if action_type == ACTION_ENCODE_F2 { fmt.Println("Encoding (F2) \"" + file_input_path + "\"...") // // Output Size. file_output_cols = file_input_cols + 8 file_output_rows = file_input_rows + 8 output_field_size = file_output_cols * file_output_rows // Report. fmt.Println("Input Data (WxH):", file_input_cols, "x", file_input_rows, ".") /// fmt.Println("Output Data (WxH):", file_output_cols, "x", file_output_rows, ".") /// // Bytes -> Field. field, ok = bytes_to_field(input_field_size, file_input_cols, file_input_rows, file_input_content) check_ok(ok) // Field -> Frame. field_framed, err_code = pack_data_f2(input_field_size, file_input_cols, file_input_rows, field) check_err_code(err_code) // Frame -> Bytes. file_output_content, ok = field_to_bytes(output_field_size, file_output_cols, file_output_rows, field_framed) check_ok(ok) // Bytes -> File. fmt.Println("Writing \"" + file_output_path + "\"...") // err = ioutil.WriteFile(file_output_path, file_output_content, 0644) check_error(err) } if action_type == ACTION_DECODE_F1 { fmt.Println("Decoding (F1) \"" + file_input_path + "\"...") // // Output Size. file_output_cols = file_input_cols - 4 file_output_rows = file_input_rows - 4 output_field_size = file_output_cols * file_output_rows // Report. fmt.Println("Input Data (WxH):", file_input_cols, "x", file_input_rows, ".") /// fmt.Println("Output Data (WxH):", file_output_cols, "x", file_output_rows, ".") /// // Bytes -> Frame. field_framed, ok = bytes_to_field(input_field_size, file_input_cols, file_input_rows, file_input_content) check_ok(ok) // Frame -> Field. field, ok = get_data_f1(input_field_size, file_input_cols, file_input_rows, field_framed) check_ok(ok) // Field -> Bytes. file_output_content, ok = field_to_bytes(output_field_size, file_output_cols, file_output_rows, field) check_ok(ok) // Bytes -> File. fmt.Println("Writing \"" + file_output_path + "\"...") // err = ioutil.WriteFile(file_output_path, file_output_content, 0644) check_error(err) } if action_type == ACTION_DECODE_F2 { fmt.Println("Decoding (F2) \"" + file_input_path + "\"...") // // Output Size. file_output_cols = file_input_cols - 8 file_output_rows = file_input_rows - 8 output_field_size = file_output_cols * file_output_rows // Report. fmt.Println("Input Data (WxH):", file_input_cols, "x", file_input_rows, ".") /// fmt.Println("Output Data (WxH):", file_output_cols, "x", file_output_rows, ".") /// // Bytes -> Frame. field_framed, ok = bytes_to_field(input_field_size, file_input_cols, file_input_rows, file_input_content) check_ok(ok) // Frame -> Field. field, ok = get_data_f2(input_field_size, file_input_cols, file_input_rows, field_framed) check_ok(ok) // Field -> Bytes. file_output_content, ok = field_to_bytes(output_field_size, file_output_cols, file_output_rows, field) check_ok(ok) // Bytes -> File. fmt.Println("Writing \"" + file_output_path + "\"...") // err = ioutil.WriteFile(file_output_path, file_output_content, 0644) check_error(err) } if action_type == ACTION_NONE { fmt.Println("Idle...") // } } //============================================================================== // Packs useful Data into Message and surrounds it with a Frame I. func pack_data_f1( data_bits_count uint64, data_columns_count uint64, data_rows_count uint64, data field_of_bits) (field_of_bits, uint8) { const DS = 4 const DO = DS / 2 const data_columns_count_limit = math.MaxUint64 - DS const data_rows_count_limit = math.MaxUint64 - DS const ERROR_ALL_CLEAR = 0 // No Error. const ERROR_BAD_SIZE = 1 // (Colums * Rows) ≠ (Bit Count). const ERROR_COLUMNS_ERROR = 2 // Too many Columns in Data. const ERROR_ROWS_ERROR = 3 // Too many Rows in Data. var data_bits_count_required uint64 var result field_of_bits // Cursors in Result. var i uint64 // Current Row #. var i_max uint64 // var i_min uint64 // var j uint64 // Current Column #. var j_max uint64 // var j_min uint64 // // Cursors in Data. var y uint64 // Current Row #. var x uint64 // Current Column #. var result_columns_count uint64 var result_rows_count uint64 var data_first_column_index uint64 var data_first_row_index uint64 //var data_last_column_index uint64 //var data_last_row_index uint64 var result_first_column_index uint64 var result_first_row_index uint64 var result_last_column_index uint64 var result_last_row_index uint64 // Check Input Data. data_bits_count_required = data_columns_count * data_rows_count if data_bits_count != data_bits_count_required { return nil, ERROR_BAD_SIZE } if data_columns_count > data_columns_count_limit { return nil, ERROR_COLUMNS_ERROR } if data_rows_count > data_rows_count_limit { return nil, ERROR_ROWS_ERROR } // Indices & Sizes. result_columns_count = data_columns_count + DS result_rows_count = data_rows_count + DS data_first_column_index = 0 data_first_row_index = 0 //data_last_column_index = data_columns_count - 1 //data_last_row_index = data_rows_count - 1 result_first_column_index = 0 result_first_row_index = 0 result_last_column_index = result_columns_count - 1 result_last_row_index = result_rows_count - 1 // Create an empty Field. result = make(field_of_bits, result_rows_count) for i = result_first_row_index; i <= result_last_row_index; i++ { result[i] = make(row_of_bits, result_columns_count) for j = result_first_column_index; j <= result_last_column_index; j++ { result[i][j] = EMPTY } } // Draw the Frame I. for j = result_first_column_index; j <= result_last_column_index; j++ { result[result_first_row_index][j] = FILLED result[result_last_row_index][j] = FILLED } for i = result_first_row_index; i <= result_last_row_index; i++ { result[i][result_first_column_index] = FILLED result[i][result_last_column_index] = FILLED } // Draw Frame's Spacer. i_min = result_first_row_index + 1 i_max = result_last_row_index - 1 j_min = result_first_column_index + 1 j_max = result_last_column_index - 1 for j = j_min; j <= j_max; j++ { result[i_min][j] = EMPTY result[i_max][j] = EMPTY } for i = i_min; i <= i_max; i++ { result[i][j_min] = EMPTY result[i][j_max] = EMPTY } // Draw Data. i_min = result_first_row_index + DO i_max = result_last_row_index - DO j_min = result_first_column_index + DO j_max = result_last_column_index - DO y = data_first_row_index for i = i_min; i <= i_max; i++ { x = data_first_column_index for j = j_min; j <= j_max; j++ { result[i][j] = data[y][x] x++ } y++ } return result, ERROR_ALL_CLEAR } //============================================================================== // Packs useful Data into Message and surrounds it with a Frame II. func pack_data_f2( data_bits_count uint64, data_columns_count uint64, data_rows_count uint64, data field_of_bits) (field_of_bits, uint8) { const DS = 8 const DO = DS / 2 const data_columns_count_limit = math.MaxUint64 - DS const data_rows_count_limit = math.MaxUint64 - DS const ERROR_ALL_CLEAR = 0 // No Error. const ERROR_BAD_SIZE = 1 // (Colums * Rows) ≠ (Bit Count). const ERROR_COLUMNS_ERROR = 2 // Too many Columns in Data. const ERROR_ROWS_ERROR = 3 // Too many Rows in Data. var data_bits_count_required uint64 var result field_of_bits // Cursors in Result. var i uint64 // Current Row #. var i_max uint64 // var i_min uint64 // var j uint64 // Current Column #. var j_max uint64 // var j_min uint64 // // Cursors in Data. var y uint64 // Current Row #. var x uint64 // Current Column #. var result_columns_count uint64 var result_rows_count uint64 var data_first_column_index uint64 var data_first_row_index uint64 //var data_last_column_index uint64 //var data_last_row_index uint64 var result_first_column_index uint64 var result_first_row_index uint64 var result_last_column_index uint64 var result_last_row_index uint64 // Check Input Data. data_bits_count_required = data_columns_count * data_rows_count if data_bits_count != data_bits_count_required { return nil, ERROR_BAD_SIZE } if data_columns_count > data_columns_count_limit { return nil, ERROR_COLUMNS_ERROR } if data_rows_count > data_rows_count_limit { return nil, ERROR_ROWS_ERROR } // Indices & Sizes. result_columns_count = data_columns_count + DS result_rows_count = data_rows_count + DS data_first_column_index = 0 data_first_row_index = 0 //data_last_column_index = data_columns_count - 1 //data_last_row_index = data_rows_count - 1 result_first_column_index = 0 result_first_row_index = 0 result_last_column_index = result_columns_count - 1 result_last_row_index = result_rows_count - 1 // Create an empty Field. result = make(field_of_bits, result_rows_count) for i = result_first_row_index; i <= result_last_row_index; i++ { result[i] = make(row_of_bits, result_columns_count) for j = result_first_column_index; j <= result_last_column_index; j++ { result[i][j] = EMPTY } } // Draw the Frame I. for j = result_first_column_index; j <= result_last_column_index; j++ { result[result_first_row_index][j] = FILLED result[result_last_row_index][j] = FILLED } for i = result_first_row_index; i <= result_last_row_index; i++ { result[i][result_first_column_index] = FILLED result[i][result_last_column_index] = FILLED } // Draw Frame's Spacer. i_min = result_first_row_index + 1 i_max = result_last_row_index - 1 j_min = result_first_column_index + 1 j_max = result_last_column_index - 1 for j = j_min; j <= j_max; j++ { result[i_min][j] = EMPTY result[i_max][j] = EMPTY } for i = i_min; i <= i_max; i++ { result[i][j_min] = EMPTY result[i][j_max] = EMPTY } // Draw the Frame II. i_min = result_first_row_index + 2 i_max = result_last_row_index - 2 j_min = result_first_column_index + 2 j_max = result_last_column_index - 2 for j = j_min; j <= j_max; j++ { result[i_min][j] = FILLED result[i_max][j] = FILLED } for i = i_min; i <= i_max; i++ { result[i][j_min] = FILLED result[i][j_max] = FILLED } // Draw Frame's Spacer. i_min = result_first_row_index + 3 i_max = result_last_row_index - 3 j_min = result_first_column_index + 3 j_max = result_last_column_index - 3 for j = j_min; j <= j_max; j++ { result[i_min][j] = EMPTY result[i_max][j] = EMPTY } for i = i_min; i <= i_max; i++ { result[i][j_min] = EMPTY result[i][j_max] = EMPTY } // Draw Data. i_min = result_first_row_index + DO i_max = result_last_row_index - DO j_min = result_first_column_index + DO j_max = result_last_column_index - DO y = data_first_row_index for i = i_min; i <= i_max; i++ { x = data_first_column_index for j = j_min; j <= j_max; j++ { result[i][j] = data[y][x] x++ } y++ } return result, ERROR_ALL_CLEAR } //============================================================================== // Checks Integrity of a Frame I of the Message. func check_frame_f1( message_bits_count uint64, message_columns_count uint64, message_rows_count uint64, message field_of_bits) bool { const message_columns_count_limit = math.MaxUint64 const message_rows_count_limit = math.MaxUint64 const message_rows_count_min = 4 + 1 // Rows in empty Message. const message_columns_count_min = 4 + 1 // Columns in empty Message. const ERROR_ALL_CLEAR = true // No Error. const ERROR = false var data_bits_count_required uint64 // Cursors in Message. var i uint64 // Current Row #. var i_max uint64 // var i_min uint64 // var j uint64 // Current Column #. var j_max uint64 // var j_min uint64 // // Check Input Data. data_bits_count_required = message_columns_count * message_rows_count if message_bits_count != data_bits_count_required { return ERROR } if message_columns_count > message_columns_count_limit { return ERROR } if message_rows_count > message_rows_count_limit { return ERROR } // Check Minimum Sizes. if message_rows_count < message_rows_count_min { return ERROR } if message_columns_count < message_columns_count_min { return ERROR } // Check Dimensions of Array. if uint64(len(message)) != message_rows_count { return ERROR } i_min = 0 i_max = message_rows_count - 1 for i = i_min; i <= i_max; i++ { if uint64(len(message[i])) != message_columns_count { return ERROR } } // Check Frame I. j_min = 0 j_max = message_columns_count - 1 for j = j_min; j <= j_max; j++ { if message[i_min][j] != FILLED { return ERROR } if message[i_max][j] != FILLED { return ERROR } } for i = i_min; i <= i_max; i++ { if message[i][j_min] != FILLED { return ERROR } if message[i][j_max] != FILLED { return ERROR } } // Check Frame's Spacer. i_min = 1 i_max = message_rows_count - 2 j_min = 1 j_max = message_columns_count - 2 for j = j_min; j <= j_max; j++ { if message[i_min][j] != EMPTY { return ERROR } if message[i_max][j] != EMPTY { return ERROR } } for i = i_min; i <= i_max; i++ { if message[i][j_min] != EMPTY { return ERROR } if message[i][j_max] != EMPTY { return ERROR } } return ERROR_ALL_CLEAR } //============================================================================== // Checks Integrity of a Frame II of the Message. func check_frame_f2( message_bits_count uint64, message_columns_count uint64, message_rows_count uint64, message field_of_bits) bool { const message_columns_count_limit = math.MaxUint64 const message_rows_count_limit = math.MaxUint64 const message_rows_count_min = 8 + 1 // Rows in empty Message. const message_columns_count_min = 8 + 1 // Columns in empty Message. const ERROR_ALL_CLEAR = true // No Error. const ERROR = false var data_bits_count_required uint64 // Cursors in Message. var i uint64 // Current Row #. var i_max uint64 // var i_min uint64 // var j uint64 // Current Column #. var j_max uint64 // var j_min uint64 // // Check Input Data. data_bits_count_required = message_columns_count * message_rows_count if message_bits_count != data_bits_count_required { return ERROR } if message_columns_count > message_columns_count_limit { return ERROR } if message_rows_count > message_rows_count_limit { return ERROR } // Check Minimum Sizes. if message_rows_count < message_rows_count_min { return ERROR } if message_columns_count < message_columns_count_min { return ERROR } // Check Dimensions of Array. if uint64(len(message)) != message_rows_count { return ERROR } i_min = 0 i_max = message_rows_count - 1 for i = i_min; i <= i_max; i++ { if uint64(len(message[i])) != message_columns_count { return ERROR } } // Check Frame I. j_min = 0 j_max = message_columns_count - 1 for j = j_min; j <= j_max; j++ { if message[i_min][j] != FILLED { return ERROR } if message[i_max][j] != FILLED { return ERROR } } for i = i_min; i <= i_max; i++ { if message[i][j_min] != FILLED { return ERROR } if message[i][j_max] != FILLED { return ERROR } } // Check Frame's Spacer. i_min = 1 i_max = message_rows_count - 2 j_min = 1 j_max = message_columns_count - 2 for j = j_min; j <= j_max; j++ { if message[i_min][j] != EMPTY { return ERROR } if message[i_max][j] != EMPTY { return ERROR } } for i = i_min; i <= i_max; i++ { if message[i][j_min] != EMPTY { return ERROR } if message[i][j_max] != EMPTY { return ERROR } } // Check Frame II. i_min = 2 i_max = message_rows_count - 3 j_min = 2 j_max = message_columns_count - 3 for j = j_min; j <= j_max; j++ { if message[i_min][j] != FILLED { return ERROR } if message[i_max][j] != FILLED { return ERROR } } for i = i_min; i <= i_max; i++ { if message[i][j_min] != FILLED { return ERROR } if message[i][j_max] != FILLED { return ERROR } } // Check Frame's Spacer. i_min = 3 i_max = message_rows_count - 4 j_min = 3 j_max = message_columns_count - 4 for j = j_min; j <= j_max; j++ { if message[i_min][j] != EMPTY { return ERROR } if message[i_max][j] != EMPTY { return ERROR } } for i = i_min; i <= i_max; i++ { if message[i][j_min] != EMPTY { return ERROR } if message[i][j_max] != EMPTY { return ERROR } } return ERROR_ALL_CLEAR } //============================================================================== // Gets Data from Message with Frame I. func get_data_f1( message_bits_count uint64, message_columns_count uint64, message_rows_count uint64, message field_of_bits) (field_of_bits, bool) { const DS = 4 const DO = DS / 2 const ERROR_ALL_CLEAR = true // No Error. const ERROR = false var data field_of_bits var data_rows_count uint64 var data_columns_count uint64 var cf bool // Result of Frame Check. // Cursors in Message. var i uint64 // Current Row #. var i_min uint64 // var j uint64 // Current Column #. var j_min uint64 // // Cursors in Data. var y uint64 // Current Row #. var x uint64 // Current Column #. // Check Frame. cf = check_frame_f1(message_bits_count, message_columns_count, message_rows_count, message) if cf == ERROR { return nil, ERROR } // Prepare Data. data_rows_count = message_rows_count - DS data_columns_count = message_columns_count - DS // data = make(field_of_bits, data_rows_count) for y = 0; y < data_rows_count; y++ { data[y] = make(row_of_bits, data_columns_count) for x = 0; x < data_columns_count; x++ { data[y][x] = EMPTY } } // Get Data. i_min = DO j_min = DO i = i_min for y = 0; y < data_rows_count; y++ { j = j_min for x = 0; x < data_columns_count; x++ { data[y][x] = message[i][j] j++ } i++ } return data, ERROR_ALL_CLEAR } //============================================================================== // Gets Data from Message with Frame II. func get_data_f2( message_bits_count uint64, message_columns_count uint64, message_rows_count uint64, message field_of_bits) (field_of_bits, bool) { const DS = 8 const DO = DS / 2 const ERROR_ALL_CLEAR = true // No Error. const ERROR = false var data field_of_bits var data_rows_count uint64 var data_columns_count uint64 var cf bool // Result of Frame Check. // Cursors in Message. var i uint64 // Current Row #. var i_min uint64 // var j uint64 // Current Column #. var j_min uint64 // // Cursors in Data. var y uint64 // Current Row #. var x uint64 // Current Column #. // Check Frame. cf = check_frame_f2(message_bits_count, message_columns_count, message_rows_count, message) if cf == ERROR { return nil, ERROR } // Prepare Data. data_rows_count = message_rows_count - DS data_columns_count = message_columns_count - DS // data = make(field_of_bits, data_rows_count) for y = 0; y < data_rows_count; y++ { data[y] = make(row_of_bits, data_columns_count) for x = 0; x < data_columns_count; x++ { data[y][x] = EMPTY } } // Get Data. i_min = DO j_min = DO i = i_min for y = 0; y < data_rows_count; y++ { j = j_min for x = 0; x < data_columns_count; x++ { data[y][x] = message[i][j] j++ } i++ } return data, ERROR_ALL_CLEAR } //============================================================================== // Converts Field into Array of Bytes. func field_to_bytes( field_bits_count uint64, field_columns_count uint64, field_rows_count uint64, field field_of_bits) ([]byte, bool) { const field_columns_count_limit = math.MaxUint64 const field_rows_count_limit = math.MaxUint64 const ERROR_ALL_CLEAR = true // No Error. const ERROR = false const MSG_1 = "Warning ! The Size of the Output Data can not be stored " + "using 8-Bit Bytes ! The Size is not a Multiple of 8 !" var i uint64 var j uint64 // Cursors in Field. var y uint64 var x uint64 var array []byte var current_bit bit var current_byte byte var bytes_count uint64 var field_bits_count_required uint64 var field_column_first uint64 var field_column_last uint64 field_column_first = 0 field_column_last = field_columns_count - 1 // Check Input Data. field_bits_count_required = field_columns_count * field_rows_count if field_bits_count != field_bits_count_required { log.Println("1") return nil, ERROR } if field_columns_count > field_columns_count_limit { log.Println("2") return nil, ERROR } if field_rows_count > field_rows_count_limit { log.Println("3") return nil, ERROR } // Can be converted to Bytes ? if (field_bits_count % bits_in_byte) != 0 { fmt.Println(MSG_1) return nil, ERROR } bytes_count = field_bits_count / bits_in_byte array = make([]byte, bytes_count) x = 0 y = 0 for i = 0; i < bytes_count; i++ { current_byte = 0 // Read 8 Bits. for j = 0; j < bits_in_byte; j++ { current_bit = field[y][x] // Save Bit in Byte. if current_bit == FILLED { current_byte = current_byte | (128 >> j) } // Next Element in Field. if x == field_column_last { y++ x = field_column_first } else { x++ } } // Save to Array. array[i] = current_byte } return array, ERROR_ALL_CLEAR } //============================================================================== // Converts Array of Bytes into Field. func bytes_to_field( field_bits_count uint64, field_columns_count uint64, field_rows_count uint64, array []byte) (field_of_bits, bool) { const field_columns_count_limit = math.MaxUint64 const field_rows_count_limit = math.MaxUint64 const ERROR_ALL_CLEAR = true // No Error. const ERROR = false var i uint64 var j uint64 // Cursors in Field. var y uint64 var x uint64 var field field_of_bits var current_bit bit var current_byte byte var current_byte_tmp byte var bytes_count uint64 var field_bits_count_required uint64 var field_column_first uint64 var field_column_last uint64 field_column_first = 0 field_column_last = field_columns_count - 1 // Check Input Data. field_bits_count_required = field_columns_count * field_rows_count if field_bits_count != field_bits_count_required { return nil, ERROR } if field_columns_count > field_columns_count_limit { return nil, ERROR } if field_rows_count > field_rows_count_limit { return nil, ERROR } // Can be converted to Bytes ? if (field_bits_count % bits_in_byte) != 0 { return nil, ERROR } bytes_count = uint64(len(array)) if bytes_count*bits_in_byte != field_bits_count { return nil, ERROR } // Create an empty Field. field = make(field_of_bits, field_rows_count) for y = 0; y < field_rows_count; y++ { field[y] = make(row_of_bits, field_columns_count) for x = 0; x < field_columns_count; x++ { field[y][x] = EMPTY } } x = 0 y = 0 for i = 0; i < bytes_count; i++ { current_byte = array[i] // Read 8 Bits. for j = 0; j < bits_in_byte; j++ { current_byte_tmp = (current_byte >> (7 - j)) & 1 if current_byte_tmp == 1 { current_bit = FILLED } else { current_bit = EMPTY } // Save Bit in Field. field[y][x] = current_bit // Next Element in Field. if x == field_column_last { y++ x = field_column_first } else { x++ } } } return field, ERROR_ALL_CLEAR } //============================================================================== // Read Command Line Arguments (Keys, Flags, Switches). func read_cla() { var err error // Set Rules. cla_file_in = flag.String("fi", "input", "File Input.") cla_file_out = flag.String("fo", "output", "File Output.") cla_action_type = flag.String("a", "", "Action Type.") cla_x = flag.String("x", "0", "Columns.") cla_y = flag.String("y", "0", "Rows.") // Read C.L.A. flag.Parse() // Files. file_input_path = *cla_file_in file_output_path = *cla_file_out // Action Type. if *cla_action_type == "e1" { action_type = ACTION_ENCODE_F1 } else if *cla_action_type == "e2" { action_type = ACTION_ENCODE_F2 } else if *cla_action_type == "d1" { action_type = ACTION_DECODE_F1 } else if *cla_action_type == "d2" { action_type = ACTION_DECODE_F2 } else { action_type = ACTION_NONE } // X, Y. file_input_x, err = strconv.ParseUint(*cla_x, 10, 64) check_error(err) file_input_y, err = strconv.ParseUint(*cla_y, 10, 64) check_error(err) } //============================================================================== func check_error(err error) { if err != nil { log.Println(err) os.Exit(ERROR_1) } } //============================================================================== func check_ok(ok bool) { if !ok { log.Println("Error.") os.Exit(ERROR_1) } else { //fmt.Println("OK.") } } //============================================================================== func check_err_code(err_code uint8) { if err_code == 0 { //fmt.Println("OK.") } else { log.Println("Error.") os.Exit(ERROR_1) } } //==============================================================================
legacy-vault/tests
go/binary_frame/2/binary_frame.go
GO
gpl-3.0
29,039
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Wed Sep 20 13:37:16 2017 Author: Peiyong Jiang : jiangpeiyong@impcas.ac.cn Function: 旋转使得变换。 """ import matplotlib.pyplot as plt import tensorflow as tf import numpy as np plt.close('all') emitX=12 alphaX=-10. betaX=13. gammaX=(1.+alphaX**2)/betaX sigmaX=np.array([[betaX,-alphaX],[-alphaX,gammaX]])*emitX; numPart=np.int32(1e5); X=np.random.multivariate_normal([0.,0.],sigmaX,numPart).T plt.figure(1) plt.plot(X[0,:],X[1,:],'.') ## w=tf.Variable(tf.random_normal([1,1])) w1=tf.cos(w) w2=tf.sin(w) P_Row_1=tf.concat([w1,-w2],0) P_Row_2=tf.concat([w2,w1],0) P=tf.concat([P_Row_1,P_Row_2],1) xI=tf.placeholder(tf.float32,[2,None]) xO=tf.matmul(P,xI) xxp=tf.reduce_mean(xO[0]*xO[1]) lossAlpha=xxp**2 rateLearn=1e-4 optTotal=tf.train.AdamOptimizer(rateLearn) trainAlpha=optTotal.minimize(lossAlpha) sess = tf.InteractiveSession(config=tf.ConfigProto(log_device_placement=True)) sess.run(tf.global_variables_initializer()) sizeBatch=64 for _ in xrange(8000): startBatch=np.random.randint(0,high=numPart-sizeBatch-1) xFeed=X[:,startBatch:startBatch+sizeBatch:] sess.run(trainAlpha,feed_dict={xI:xFeed}) #print(sess.run(LambdaR)) #print('---------------------------') print(sess.run(lossAlpha,feed_dict={xI:X}),_) print('_______________________________________________') zReal=sess.run(xO,feed_dict={xI:X}) plt.figure(2) plt.plot(zReal[0,:],zReal[1,:],'r.') plt.axis('equal') plt.figure(10) plt.hold plt.plot(zReal[0,:],zReal[1,:],'r.') plt.plot(X[0,:],X[1,:],'b.') #plt.plot(zReal[0,:],zReal[1,:],'r.') plt.axis('equal') plt.figure(11) plt.hold #plt.plot(zReal[0,:],zReal[1,:],'r.') plt.plot(X[0,:],X[1,:],'b.') plt.plot(zReal[0,:],zReal[1,:],'r.') plt.axis('equal') zRealCov=np.cov(zReal) emitXReal=np.sqrt(np.linalg.det(zRealCov)) print(emitXReal)
iABC2XYZ/abc
DM_Twiss/TwissTrain9.py
Python
gpl-3.0
1,927
<?php theme()->render("2column-right", [ ["Header", "top"], ["Post", "content"], ["Comments", "content"], ["SidebarRight", "right"], ["Footer", "bottom"] ]);
erikkubica/netlime-starter-theme-v2
single.php
PHP
gpl-3.0
177
/* This file is part of Arkhados. Arkhados is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Arkhados is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Arkhados. If not, see <http://www.gnu.org/licenses/>. */ package arkhados.spell.buffs.info; import arkhados.controls.CRotation; import arkhados.controls.CTrackLocation; import arkhados.effects.BuffEffect; import com.jme3.math.Vector3f; import com.jme3.scene.Node; import com.jme3.scene.Spatial; public class MineralArmorInfo extends BuffInfo { { setIconPath("Interface/Images/SpellIcons/MineralArmor.png"); } @Override public BuffEffect createBuffEffect(BuffInfoParameters params) { MineralArmorEffect effect = new MineralArmorEffect(params.duration); effect.addToCharacter(params); return effect; } } class MineralArmorEffect extends BuffEffect { private Node centralNode = null; public MineralArmorEffect(float timeLeft) { super(timeLeft); } public void addToCharacter(BuffInfoParameters params) { Node character = (Node) params.buffControl.getSpatial(); Spatial crystals1 = assets.loadModel("Models/crystals.j3o"); Spatial crystals2 = assets.loadModel("Models/crystals.j3o"); Spatial crystals3 = assets.loadModel("Models/crystals.j3o"); Spatial crystals4 = assets.loadModel("Models/crystals.j3o"); centralNode = new Node("mineral-armor-node"); centralNode.attachChild(crystals1); centralNode.attachChild(crystals2); centralNode.attachChild(crystals3); centralNode.attachChild(crystals4); crystals1.setLocalTranslation(-7.5f, 0f, 0f); crystals2.setLocalTranslation(7.5f, 0f, 0f); crystals3.setLocalTranslation(0f, 0f, -7.5f); crystals4.setLocalTranslation(0f, 0f, 7.5f); Node world = character.getParent(); world.attachChild(centralNode); centralNode.addControl( new CTrackLocation(character, new Vector3f(0f, 10f, 0f))); centralNode.addControl(new CRotation(0f, 2f, 0f)); } @Override public void destroy() { super.destroy(); centralNode.removeFromParent(); } }
TripleSnail/Arkhados
src/arkhados/spell/buffs/info/MineralArmorInfo.java
Java
gpl-3.0
2,655
jQuery(document).ready(function(){ if( $('.cd-stretchy-nav').length > 0 ) { var stretchyNavs = $('.cd-stretchy-nav'); stretchyNavs.each(function(){ var stretchyNav = $(this), stretchyNavTrigger = stretchyNav.find('.cd-nav-trigger'); stretchyNavTrigger.on('click', function(event){ event.preventDefault(); stretchyNav.toggleClass('nav-is-visible'); }); }); $(document).on('click', function(event){ ( !$(event.target).is('.cd-nav-trigger') && !$(event.target).is('.cd-nav-trigger span') ) && stretchyNavs.removeClass('nav-is-visible'); }); }; ///toggle en contenido $(".toggle-view li").on('click', function(e){ e.currentTarget.classList.toggle("active"); }); });
GobiernoFacil/agentes-v2
public/js/main.js
JavaScript
gpl-3.0
716
#include "precomp.h" #include "stdinc.h" #include "io_sfen.h" #include "commandpacket.h" namespace godwhale { const CommandPacket::CharSeparator CommandPacket::ms_separator(" ", ""); CommandPacket::CommandPacket(CommandType type) : m_type(type), m_positionId(-1), m_position(false) { } CommandPacket::CommandPacket(CommandPacket const & other) : m_positionId(-1), m_position(false) { } CommandPacket::CommandPacket(CommandPacket && other) : m_positionId(-1), m_position(false) { } /** * @brief ƒRƒ}ƒ“ƒh‚ÌŽÀs—Dæ‡ˆÊ‚ðŽæ“¾‚µ‚Ü‚·B * * ’l‚ª‘å‚«‚¢•û‚ªA—Dæ‡ˆÊ‚͍‚‚¢‚Å‚·B */ int CommandPacket::getPriority() const { switch (m_type) { // I—¹Œn‚̃Rƒ}ƒ“ƒh‚Í‚·‚®‚ÉŽÀs case COMMAND_QUIT: case COMMAND_STOP: return 100; // ’ʏí‚̃Rƒ}ƒ“ƒh‚Í‚»‚̂܂܂̏‡‚Å case COMMAND_LOGIN: case COMMAND_SETPOSITION: case COMMAND_MAKEROOTMOVE: case COMMAND_SETPV: case COMMAND_SETMOVELIST: case COMMAND_VERIFY: return 50; // ƒGƒ‰[‚Ý‚½‚¢‚È‚à‚Ì case COMMAND_NONE: return 0; } unreachable(); return -1; } /** * @brief str‚ªtarget‚ªŽ¦‚·ƒg[ƒNƒ“‚Å‚ ‚é‚©’²‚ׂ܂·B */ bool CommandPacket::isToken(std::string const & str, std::string const & target) { return (str.compare(target) == 0); } /** * @brief RSI(remote shogi interface)‚ðƒp[ƒX‚µAƒRƒ}ƒ“ƒh‚É’¼‚µ‚Ü‚·B */ shared_ptr<CommandPacket> CommandPacket::parse(std::string const & rsi) { if (rsi.empty()) { throw new std::invalid_argument("rsi"); } Tokenizer tokens(rsi, ms_separator); std::string token = *tokens.begin(); if (isToken(token, "login")) { return parse_Login(rsi, tokens); } else if (isToken(token, "setposition")) { return parse_SetPosition(rsi, tokens); } else if (isToken(token, "makerootmove")) { return parse_MakeRootMove(rsi, tokens); } else if (isToken(token, "setmovelist")) { return parse_SetMoveList(rsi, tokens); } else if (isToken(token, "stop")) { return parse_Stop(rsi, tokens); } else if (isToken(token, "quit")) { return parse_Quit(rsi, tokens); } return shared_ptr<CommandPacket>(); } /** * @brief ƒRƒ}ƒ“ƒh‚ðRSI(remote shogi interface)‚ɕϊ·‚µ‚Ü‚·B */ std::string CommandPacket::toRSI() const { assert(m_type != COMMAND_NONE); switch (m_type) { case COMMAND_LOGIN: return toRSI_Login(); case COMMAND_SETPOSITION: return toRSI_SetPosition(); case COMMAND_MAKEROOTMOVE: return toRSI_MakeRootMove(); case COMMAND_SETMOVELIST: return toRSI_SetMoveList(); case COMMAND_STOP: return toRSI_Stop(); case COMMAND_QUIT: return toRSI_Quit(); } unreachable(); return std::string(); } #pragma region Login /** * @brief loginƒRƒ}ƒ“ƒh‚ðƒp[ƒX‚µ‚Ü‚·B * * login <address> <port> <login_id> <nthreads> */ shared_ptr<CommandPacket> CommandPacket::parse_Login(std::string const & rsi, Tokenizer & tokens) { shared_ptr<CommandPacket> result(new CommandPacket(COMMAND_LOGIN)); Tokenizer::iterator begin = ++tokens.begin(); result->m_serverAddress = *begin++; result->m_serverPort = *begin++; result->m_loginId = *begin++; return result; } /** * @brief loginƒRƒ}ƒ“ƒh‚ðRSI‚ɕϊ·‚µ‚Ü‚·B */ std::string CommandPacket::toRSI_Login() const { return (F("login %1% %2% %3%") % m_serverAddress % m_serverPort % m_loginId) .str(); } #pragma endregion #pragma region SetPosition /** * @brief setpositionƒRƒ}ƒ“ƒh‚ðƒp[ƒX‚µ‚Ü‚·B * * setposition <position_id> [sfen <sfen> | startpos] moves <move1> ... <moven> * <sfen> = <board_sfen> <turn_sfen> <hand_sfen> <nmoves> */ shared_ptr<CommandPacket> CommandPacket::parse_SetPosition(std::string const & rsi, Tokenizer & tokens) { shared_ptr<CommandPacket> result(new CommandPacket(COMMAND_SETPOSITION)); Tokenizer::iterator begin = ++tokens.begin(); result->m_positionId = lexical_cast<int>(*begin++); std::string token = *begin++; if (token == "sfen") { std::string sfen; sfen += *begin++ + " "; // board sfen += *begin++ + " "; // turn sfen += *begin++ + " "; // hand sfen += *begin++; // nmoves result->m_position = sfenToPosition(sfen); } else if (token == "startpos") { result->m_position = Position(); } // moves‚͂Ȃ¢‚±‚Æ‚ª‚ ‚è‚Ü‚·B if (begin == tokens.end()) { return result; } if (*begin++ != "moves") { throw new ParseException(F("%1%: Žw‚µŽè‚ª³‚µ‚­‚ ‚è‚Ü‚¹‚ñB") % rsi); } for (; begin != tokens.end(); ++begin) { Move move = sfenToMove(result->m_position, *begin); if (!result->m_position.makeMove(move)) { LOG_ERROR() << result->m_position; LOG_ERROR() << *begin << ": Žw‚µŽè‚ª³‚µ‚­‚ ‚è‚Ü‚¹‚ñB"; throw new ParseException(F("%1%: Žw‚µŽè‚ª³‚µ‚­‚ ‚è‚Ü‚¹‚ñB") % *begin); } } return result; } /** * @brief setpositionƒRƒ}ƒ“ƒh‚ðRSI‚ɕϊ·‚µ‚Ü‚·B */ std::string CommandPacket::toRSI_SetPosition() const { Position position = m_position; std::vector<Move> moves = position.getMoveList(); // ‹Ç–Ê‚ð‚·‚×‚Ä–ß‚µ‚Ü‚·B while (!position.getMoveList().empty()) { position.unmakeMove(); } std::string posStr; if (position.isInitial()) { posStr = " startpos"; } else { posStr = " sfen "; posStr += positionToSfen(position); } std::string movesStr; if (!moves.empty()) { movesStr += " moves"; BOOST_FOREACH(Move move, moves) { movesStr += " "; movesStr += moveToSfen(move); } } return (F("setposition %1%%2%%3%") % m_positionId % posStr % movesStr) .str(); } #pragma endregion #pragma region MakeRootMove /** * @brief makerootmoveƒRƒ}ƒ“ƒh‚ðƒp[ƒX‚µ‚Ü‚·B * * makerootmove <position_id> <old_position_id> <move> */ shared_ptr<CommandPacket> CommandPacket::parse_MakeRootMove(std::string const & rsi, Tokenizer & tokens) { shared_ptr<CommandPacket> result(new CommandPacket(COMMAND_MAKEROOTMOVE)); Tokenizer::iterator begin = ++tokens.begin(); // Å‰‚̃g[ƒNƒ“‚Í”ò‚΂µ‚Ü‚·B result->m_positionId = lexical_cast<int>(*begin++); result->m_oldPositionId = lexical_cast<int>(*begin++); // —^‚¦‚ç‚ꂽpositionId‚Ȃǂ©‚ç‹Ç–Ê‚ðŒŸõ‚µ‚Ü‚·B Position position; result->m_move = sfenToMove(position, *begin++); return result; } /** * @brief makerootmoveƒRƒ}ƒ“ƒh‚ðRSI‚ɕϊ·‚µ‚Ü‚·B */ std::string CommandPacket::toRSI_MakeRootMove() const { return (F("makerootmove %1% %2% %3%") % m_positionId % m_oldPositionId % moveToSfen(m_move)) .str(); } #pragma endregion #pragma region SetMoveList /** * @brief setmovelistƒRƒ}ƒ“ƒh‚ðƒp[ƒX‚µ‚Ü‚·B * * setmovelist <position_id> <itd> <pld> <move1> ... <moven> */ shared_ptr<CommandPacket> CommandPacket::parse_SetMoveList(std::string const & rsi, Tokenizer & tokens) { shared_ptr<CommandPacket> result(new CommandPacket(COMMAND_SETMOVELIST)); Tokenizer::iterator begin = ++tokens.begin(); // Å‰‚̃g[ƒNƒ“‚Í”ò‚΂µ‚Ü‚·B result->m_positionId = lexical_cast<int>(*begin++); result->m_iterationDepth = lexical_cast<int>(*begin++); result->m_plyDepth = lexical_cast<int>(*begin++); // —^‚¦‚ç‚ꂽpositionId‚Ȃǂ©‚ç‹Ç–Ê‚ðŒŸõ‚µ‚Ü‚·B Position position; Tokenizer::iterator end = tokens.end(); for (; begin != end; ++begin) { Move move = sfenToMove(position, *begin); if (move.isEmpty()) { throw ParseException(F("%1%: ³‚µ‚¢Žw‚µŽè‚ł͂ ‚è‚Ü‚¹‚ñB") % *begin); } result->m_moveList.push_back(move); } return result; } /** * @brief setmovelistƒRƒ}ƒ“ƒh‚ðRSI‚ɕϊ·‚µ‚Ü‚·B */ std::string CommandPacket::toRSI_SetMoveList() const { std::string movesStr; BOOST_FOREACH(Move move, m_moveList) { movesStr += " "; movesStr += moveToSfen(move); } return (F("setmovelist %1% %2% %3% %4%") % m_positionId %m_iterationDepth % m_plyDepth % movesStr) .str(); } #pragma endregion #pragma region Stop /** * @brief stopƒRƒ}ƒ“ƒh‚ðƒp[ƒX‚µ‚Ü‚·B */ shared_ptr<CommandPacket> CommandPacket::parse_Stop(std::string const & rsi, Tokenizer & tokens) { return shared_ptr<CommandPacket>(new CommandPacket(COMMAND_STOP)); } /** * @brief stopƒRƒ}ƒ“ƒh‚ðRSI‚ɕϊ·‚µ‚Ü‚·B */ std::string CommandPacket::toRSI_Stop() const { return "stop"; } #pragma endregion #pragma region Quit /** * @brief quitƒRƒ}ƒ“ƒh‚ðƒp[ƒX‚µ‚Ü‚·B */ shared_ptr<CommandPacket> CommandPacket::parse_Quit(std::string const & rsi, Tokenizer & tokens) { return shared_ptr<CommandPacket>(new CommandPacket(COMMAND_QUIT)); } /** * @brief quitƒRƒ}ƒ“ƒh‚ðRSI‚ɕϊ·‚µ‚Ü‚·B */ std::string CommandPacket::toRSI_Quit() const { return "quit"; } #pragma endregion } // namespace godwhale
ebifrier/godwhale
src/commandpacket.cpp
C++
gpl-3.0
9,268
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; using KSP; namespace panelfar { public static class PANELFARMeshSimplification { //Take the raw part geometry and simplify it so that further simplification of the entire vessel is faster public static PANELFARPartLocalMesh PreProcessLocalMesh(PANELFARPartLocalMesh mesh) { //Array of vertices; indexing must not change Vector3[] verts = new Vector3[mesh.vertexes.Length]; mesh.vertexes.CopyTo(verts, 0); //Array of triangles; each triangle points to an index in verts MeshIndexTriangle[] indexTris = new MeshIndexTriangle[mesh.triangles.Length]; mesh.triangles.CopyTo(indexTris, 0); //Array of a list of triangles that contain a given vertex; indexing is same as verts, each index in list points to an index in indexTris List<int>[] trisAttachedToVerts = GetTrisAttachedToVerts(verts, indexTris); //Array of quadrics associated with a particular vertex; indexing is same as verts Quadric[] vertQuadrics = CalculateVertQuadrics(verts, indexTris); //A list of possible vertex pairs that can be contracted into a single point MinHeap<MeshPairContraction> pairContractions = GeneratePairContractions(indexTris, verts, vertQuadrics); int faces = (int)Math.Floor(indexTris.Length * 0.5); faces = DecimateVertices(faces, ref pairContractions, ref verts, ref indexTris, ref trisAttachedToVerts, ref vertQuadrics); //This will be used to update the old array (which has many empty elements) to a new vertex array and allow the indexTris to be updated as well Dictionary<int, int> beforeIndexAfterIndex = new Dictionary<int, int>(); int currentIndex = 0; List<Vector3> newVerts = new List<Vector3>(); for (int i = 0; i < verts.Length; i++) { Vector3 v = verts[i]; if (trisAttachedToVerts[i] != null) { beforeIndexAfterIndex.Add(i, currentIndex); currentIndex++; newVerts.Add(v); } } MeshIndexTriangle[] newIndexTris = new MeshIndexTriangle[faces]; currentIndex = 0; foreach(MeshIndexTriangle tri in indexTris) { if(tri != null) { MeshIndexTriangle newTri = new MeshIndexTriangle(beforeIndexAfterIndex[tri.v0], beforeIndexAfterIndex[tri.v1], beforeIndexAfterIndex[tri.v2]); newIndexTris[currentIndex] = newTri; currentIndex++; } } mesh.vertexes = newVerts.ToArray(); mesh.triangles = newIndexTris; return mesh; } public static int DecimateVertices(int targetFaces, ref MinHeap<MeshPairContraction> pairContractions, ref Vector3[] verts, ref MeshIndexTriangle[] indexTris, ref List<int>[] trisAttachedToVerts, ref Quadric[] vertQuadrics) { int validFaces = indexTris.Length; int counter = 1; StringBuilder debug = new StringBuilder(); debug.AppendLine("Target Faces: " + targetFaces); try { while (validFaces > targetFaces) { debug.AppendLine("Iteration: " + counter + " Faces: " + validFaces); //Get the pair contraction with the least error associated with it MeshPairContraction pair = pairContractions.ExtractDominating(); debug.AppendLine("Contraction between vertices at indicies: " + pair.v0 + " and " + pair.v1); debug.AppendLine("Tris attached to v0: " + trisAttachedToVerts[pair.v0].Count + " Tris attached to v1: " + trisAttachedToVerts[pair.v1].Count); //Get faces that will be deleted / changed by contraction ComputeContraction(ref pair, indexTris, trisAttachedToVerts); //Act on faces, delete extra vertex, change all references to second vertex validFaces -= ApplyContraction(ref pair, ref pairContractions, ref verts, ref indexTris, ref trisAttachedToVerts, ref vertQuadrics); counter++; } for(int i = 0; i < indexTris.Length; i++) { MeshIndexTriangle tri = indexTris[i]; if (tri == null) continue; if (trisAttachedToVerts[tri.v0] == null) { debug.AppendLine("Tri at index " + i + " points to nonexistent vertex at index " + tri.v0); } if (trisAttachedToVerts[tri.v1] == null) { debug.AppendLine("Tri at index " + i + " points to nonexistent vertex at index " + tri.v1); } if (trisAttachedToVerts[tri.v2] == null) { debug.AppendLine("Tri at index " + i + " points to nonexistent vertex at index " + tri.v2); } } debug.AppendLine("Final: Faces: " + validFaces); } catch (Exception e) { debug.AppendLine("Error: " + e.Message); debug.AppendLine("Stack trace"); debug.AppendLine(e.StackTrace); } Debug.Log(debug.ToString()); return validFaces; } public static int ApplyContraction(ref MeshPairContraction pair, ref MinHeap<MeshPairContraction> pairContractions, ref Vector3[] verts, ref MeshIndexTriangle[] indexTris, ref List<int>[] trisAttachedToVerts, ref Quadric[] vertQuadrics) { int removedFaces = pair.deletedFaces.Count; //Move v0, clear v1 verts[pair.v0] = pair.contractedPosition; verts[pair.v1] = Vector3.zero; foreach (int triIndex in trisAttachedToVerts[pair.v1]) if (!pair.deletedFaces.Contains(triIndex) && !trisAttachedToVerts[pair.v0].Contains(triIndex)) trisAttachedToVerts[pair.v0].Add(triIndex); //Clear out all the tris attached to a non-existent vertex trisAttachedToVerts[pair.v1] = null; //Accumulate quadrics, clear unused one vertQuadrics[pair.v0] += vertQuadrics[pair.v1]; vertQuadrics[pair.v1] = new Quadric(); //Adjust deformed triangles foreach (int changedTri in pair.deformedFaces) { MeshIndexTriangle tri = indexTris[changedTri]; if (tri.v0.Equals(pair.v1)) tri.v0 = pair.v0; else if (tri.v1.Equals(pair.v1)) tri.v1 = pair.v0; else tri.v2 = pair.v0; indexTris[changedTri] = tri; } //Clear deleted triangles foreach(int deletedTri in pair.deletedFaces) { indexTris[deletedTri] = null; } List<MeshPairContraction> pairList = pairContractions.ToList(); for (int i = 0; i < pairContractions.Count; i++) { MeshPairContraction otherPair = pairList[i]; if (otherPair.v0.Equals(pair.v1)) { otherPair.v0 = pair.v0; } else if (otherPair.v1.Equals(pair.v1)) { otherPair.v1 = pair.v0; } pairList[i] = otherPair; } int count = pairList.Count; for (int i = 0; i < count; i++ ) { MeshPairContraction iItem = pairList[i]; for(int j = i + 1; j < count; j++) { if (pairList[j].Equals(iItem)) { pairList.RemoveAt(j); //Remove duplicate element count--; //Reduce length to iterate over j--; //Make sure not to skip over a duplicate } } if(iItem.v1 == iItem.v0) { pairList.RemoveAt(i); //Remove degenerate edge count--; //Reduce length to iterate over i--; //Make sure not to skip over a duplicate continue; } CalculateTargetPositionForPairContraction(ref iItem, verts, vertQuadrics); pairList[i] = iItem; } pairContractions = new MinHeap<MeshPairContraction>(pairList); return removedFaces; } public static void ComputeContraction(ref MeshPairContraction pair, MeshIndexTriangle[] indexTris, List<int>[] trisAttachedToVerts) { //This contains a list of all tris that will be changed by this contraction; boolean indicates whether they will be removed or not Dictionary<int, bool> trisToChange = new Dictionary<int, bool>(); pair.deformedFaces.Clear(); pair.deletedFaces.Clear(); //Iterate through every triangle attached to vertex 0 of this pair and add them to the dict foreach(int triIndex in trisAttachedToVerts[pair.v0]) { if(indexTris[triIndex] != null) trisToChange.Add(triIndex, false); } //Iterate through tris attached to vert 1... foreach (int triIndex in trisAttachedToVerts[pair.v1]) { if (indexTris[triIndex] == null) continue; //if the tri is already there, it will become degenerate during this contraction and should be removed if (trisToChange.ContainsKey(triIndex)) trisToChange[triIndex] = true; //else, add it and it will simply be deformed else trisToChange.Add(triIndex, false); } //Now, divide them into the appropriate lists foreach(KeyValuePair<int, bool> triIndex in trisToChange) { if (triIndex.Value) pair.deletedFaces.Add(triIndex.Key); else pair.deformedFaces.Add(triIndex.Key); } } public static MinHeap<MeshPairContraction> GeneratePairContractions(MeshIndexTriangle[] indexTris, Vector3[] verts, Quadric[] vertQuadrics) { List<MeshPairContraction> pairContractions = new List<MeshPairContraction>(); foreach(MeshIndexTriangle tri in indexTris) { MeshPairContraction e0 = new MeshPairContraction(tri.v0, tri.v1), e1 = new MeshPairContraction(tri.v1, tri.v2), e2 = new MeshPairContraction(tri.v2, tri.v0); if (!pairContractions.Contains(e0)) pairContractions.Add(e0); if (!pairContractions.Contains(e1)) pairContractions.Add(e1); if (!pairContractions.Contains(e2)) pairContractions.Add(e2); } //Calculate point that each pair contraction will contract to if it is to be done CalculateTargetPositionForAllPairContractions(ref pairContractions, verts, vertQuadrics); MinHeap<MeshPairContraction> heap = new MinHeap<MeshPairContraction>(pairContractions); return heap; } public static void CalculateTargetPositionForAllPairContractions(ref List<MeshPairContraction> pairContractions, Vector3[] verts, Quadric[] vertQuadrics) { for (int i = 0; i < pairContractions.Count; i++) { MeshPairContraction pair = pairContractions[i]; CalculateTargetPositionForPairContraction(ref pair, verts, vertQuadrics); pairContractions[i] = pair; } } public static void CalculateTargetPositionForPairContraction(ref MeshPairContraction pair, Vector3[] verts, Quadric[] vertQuadrics) { Vector3 v0 = verts[pair.v0], v1 = verts[pair.v1]; Quadric Q0 = vertQuadrics[pair.v0], Q1 = vertQuadrics[pair.v1]; Quadric Q = Q0 + Q1; if (Q.Optimize(ref pair.contractedPosition, 1e-12)) pair.error = Q.Evaluate(pair.contractedPosition); else { double ei = Q.Evaluate(v0), ej = Q.Evaluate(v1); if (ei < ej) { pair.error = ei; pair.contractedPosition = v0; } else { pair.error = ej; pair.contractedPosition = v1; } } } //This returns an array that contains (in each element) a list of indexes that specify which MeshIndexTriangles (in indexTris) are connected to which Vector3s (in verts) public static List<int>[] GetTrisAttachedToVerts(Vector3[] verts, MeshIndexTriangle[] indexTris) { List<int>[] trisAttachedToVerts = new List<int>[verts.Length]; for (int i = 0; i < trisAttachedToVerts.Length; i++) { trisAttachedToVerts[i] = new List<int>(); } for (int i = 0; i < indexTris.Length; i++) { MeshIndexTriangle tri = indexTris[i]; trisAttachedToVerts[tri.v0].Add(i); trisAttachedToVerts[tri.v1].Add(i); trisAttachedToVerts[tri.v2].Add(i); } return trisAttachedToVerts; } //Returns an array of quadrics for evaluating the error of each possible contraction public static Quadric[] CalculateVertQuadrics(Vector3[] verts, MeshIndexTriangle[] indexTris) { Quadric[] vertQuadrics = new Quadric[verts.Length]; for (int i = 0; i < vertQuadrics.Length; i++ ) vertQuadrics[i] = new Quadric(); foreach (MeshIndexTriangle tri in indexTris) { Vector3 v0, v1, v2; v0 = verts[tri.v0]; v1 = verts[tri.v1]; v2 = verts[tri.v2]; double area = PANELFARTriangleUtils.triangle_area(v0, v1, v2); Vector4 p; if (area > 0) p = PANELFARTriangleUtils.triangle_plane(v0, v1, v2); else { p = PANELFARTriangleUtils.triangle_plane(v2, v1, v0); area = -area; } Quadric Q = new Quadric(p.x, p.y, p.z, p.w, area); // Area-weight quadric and add it into the three quadrics for the corners Q *= Q.area; vertQuadrics[tri.v0] += Q; vertQuadrics[tri.v1] += Q; vertQuadrics[tri.v2] += Q; } return vertQuadrics; } } }
ferram4/PANELFAR
PANELFAR/PANELFARMeshSimplification.cs
C#
gpl-3.0
15,504
import threading import asyncio async def hello(): print('Hello world! (%s)' % threading.currentThread()) await asyncio.sleep(1) print('Hello again! (%s)' % threading.currentThread()) loop = asyncio.get_event_loop() tasks = [hello(), hello()] loop.run_until_complete(asyncio.wait(tasks)) loop.close()
IIIIIIIIll/sdy_notes_liaoxf
LiaoXueFeng/as_IO/async_await.py
Python
gpl-3.0
325
#include <iostream> #include <string> class Shape { public : virtual void draw (void) = 0; static Shape *Create (std::string type); }; class circle : public Shape { public : void draw(void){ std::cout << "circle" << std::endl; } }; class square : public Shape { public : void draw(void){ std::cout << "square" << std::endl; } }; Shape * Shape::Create (std::string type){ if(type == "circle"){ std::cout << "creating circle" << std::endl; return new circle(); } if(type == "square") { std::cout << "creating circle" << std::endl; return new square(); } return NULL; }; int main (){ Shape *cir = Shape::Create("circle"); if ( cir != NULL ) cir->draw(); return 0; }
selvagit/experiments
computing/cpp/factory_method.cpp
C++
gpl-3.0
709
/* Author: Juan Rada-Vilela, Ph.D. Copyright (C) 2010-2014 FuzzyLite Limited All rights reserved This file is part of fuzzylite. fuzzylite is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. fuzzylite is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with fuzzylite. If not, see <http://www.gnu.org/licenses/>. fuzzylite™ is a trademark of FuzzyLite Limited. */ #include "../../fl/defuzzifier/IntegralDefuzzifier.h" namespace fl { int IntegralDefuzzifier::_defaultResolution = 200; void IntegralDefuzzifier::setDefaultResolution(int defaultResolution) { _defaultResolution = defaultResolution; } int IntegralDefuzzifier::defaultResolution() { return _defaultResolution; } IntegralDefuzzifier::IntegralDefuzzifier(int resolution) : Defuzzifier(), _resolution(resolution) { } IntegralDefuzzifier::~IntegralDefuzzifier() { } void IntegralDefuzzifier::setResolution(int resolution) { this->_resolution = resolution; } int IntegralDefuzzifier::getResolution() const { return this->_resolution; } }
senabhishek/fuzzyliteAndSwift
FuzzyLiteTemplate/fuzzylite/src/defuzzifier/IntegralDefuzzifier.cpp
C++
gpl-3.0
1,554
""" Tests are performed against csr1000v-universalk9.03.15.00.S.155-2.S-std. """ import unittest from iosxe.iosxe import IOSXE from iosxe.exceptions import AuthError node = '172.16.92.134' username = 'cisco' password = 'cisco' port = 55443 class TestIOSXE(unittest.TestCase): def setUp(self): self.xe = IOSXE(node=node, username=username, password=password, disable_warnings=True) def test_iosxe_is_a_IOSXE(self): self.assertIsInstance(self.xe, IOSXE) def test_invalid_user_pass_returns_auth_error(self): self.assertRaises(AuthError, IOSXE, node=node, username='stuff', password='things', disable_warnings=True) def test_url_base(self): self.assertEqual(self.xe.url_base, 'https://{0}:{1}/api/v1'.format(node, port)) def test_token_uri(self): self.assertEqual(self.xe.token_uri, '/auth/token-services') def test_save_config_success(self): resp = self.xe.save_config() self.assertEqual(204, resp.status_code)
bobthebutcher/iosxe
tests/test_iosxe.py
Python
gpl-3.0
1,026
//This program is free software: you can redistribute it and/or modify //it under the terms of the GNU General Public License as published by //the Free Software Foundation, either version 3 of the License, or //(at your option) any later version. //This program is distributed in the hope that it will be useful, //but WITHOUT ANY WARRANTY; without even the implied warranty of //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //GNU General Public License for more details. #ifndef APIQUERYRESULT_HPP #define APIQUERYRESULT_HPP #include "definitions.hpp" #include <QString> #include <QList> #include <QHash> #include "queryresult.hpp" namespace Huggle { //! Key/value node for data from API queries //! \todo Currently value is provided even for nodes that shouldn't have it class HUGGLE_EX_CORE ApiQueryResultNode { public: ApiQueryResultNode(); ~ApiQueryResultNode(); /*! * \brief GetAttribute Return the specified attribute if it exists, otherwise return the default * \param name Name of attribute * \param default_val Value to return if the attribute is not found * \return Value of attribute or default value */ QString GetAttribute(const QString &name, const QString &default_val = ""); //! Name of attribute QString Name; //! Value of attribute QString Value; //! Hashtable of attribtues QHash<QString, QString> Attributes; QList<ApiQueryResultNode*> ChildNodes; }; //! Api queries have their own result class so that we can use it to parse them //! this is a universal result class that uses same format for all known //! formats we are going to use, including XML or JSON, so that it shouldn't //! matter which one we use, we always get this structure as output class HUGGLE_EX_CORE ApiQueryResult : public QueryResult { public: ApiQueryResult(); //! Frees the results from memory ~ApiQueryResult() override; /*! * \brief Process Process the data into Nodes and handle any warnings / errors */ void Process(); /*! * \brief GetNode Get the first node with the specified name * IMPORTANT: do not delete this node, it's a pointer to item in a list which get deleted in destructor of class * \param node_name Name of node * \return The specified node or a null pointer if none found */ ApiQueryResultNode *GetNode(const QString& node_name); /*! * \brief GetNodes Get all nodes with the specified name * IMPORTANT: do not delete these nodes, they point to items in a list which get deleted in destructor of class * \param node_name Name of node * \return QList of pointers to found nodes */ QList<ApiQueryResultNode*> GetNodes(const QString& node_name); QString GetNodeValue(const QString &node_name, const QString &default_value = ""); /*! * \brief HasWarnings Return if the API has returned any warnings * \return True if there are warnings, false otherwise */ bool HasWarnings(); //! List of result nodes unsorted with no hierarchy QList<ApiQueryResultNode*> Nodes; ApiQueryResultNode *Root; //! Warning from API query QString Warning; //! If any error was encountered during the query bool HasErrors = false; }; } #endif // APIQUERYRESULT_HPP
huggle/huggle3-qt-lx
src/huggle_core/apiqueryresult.hpp
C++
gpl-3.0
3,741
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = versionTransform; var _path2 = require('path'); var _path3 = _interopRequireDefault(_path2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var packagePath = _path3.default.resolve(process.cwd(), './package.json'); var _require = require(packagePath); var version = _require.version; function versionTransform() { return { visitor: { Identifier: function Identifier(path) { if (path.node.name === 'VERSION') { path.replaceWithSourceString('"' + version + '"'); } } } }; };
cassiane/KnowledgePlatform
Implementacao/nodejs-tcc/node_modules/babel-plugin-version-transform/lib/index.js
JavaScript
gpl-3.0
675
from __future__ import absolute_import from pywb.framework.wbrequestresponse import WbResponse, WbRequest from pywb.framework.archivalrouter import ArchivalRouter from six.moves.urllib.parse import urlsplit import base64 import socket import ssl from io import BytesIO from pywb.rewrite.url_rewriter import SchemeOnlyUrlRewriter, UrlRewriter from pywb.rewrite.rewrite_content import RewriteContent from pywb.utils.wbexception import BadRequestException from pywb.utils.bufferedreaders import BufferedReader from pywb.utils.loaders import to_native_str from pywb.framework.proxy_resolvers import ProxyAuthResolver, CookieResolver, IPCacheResolver from tempfile import SpooledTemporaryFile #================================================================= class ProxyArchivalRouter(ArchivalRouter): """ A router which combines both archival and proxy modes support First, request is treated as a proxy request using ProxyRouter Second, if not handled by the router, it is treated as a regular archival mode request. """ def __init__(self, routes, **kwargs): super(ProxyArchivalRouter, self).__init__(routes, **kwargs) self.proxy = ProxyRouter(routes, **kwargs) def __call__(self, env): response = self.proxy(env) if response: return response response = super(ProxyArchivalRouter, self).__call__(env) if response: return response #================================================================= class ProxyRouter(object): """ A router which supports http proxy mode requests Handles requests of the form: GET http://example.com The router returns latest capture by default. However, if Memento protocol support is enabled, the memento Accept-Datetime header can be used to select specific capture. See: http://www.mementoweb.org/guide/rfc/#Pattern1.3 for more details. """ BLOCK_SIZE = 4096 DEF_MAGIC_NAME = 'pywb.proxy' BUFF_RESPONSE_MEM_SIZE = 1024*1024 CERT_DL_PEM = '/pywb-ca.pem' CERT_DL_P12 = '/pywb-ca.p12' CA_ROOT_FILE = './ca/pywb-ca.pem' CA_ROOT_NAME = 'pywb https proxy replay CA' CA_CERTS_DIR = './ca/certs/' EXTRA_HEADERS = {'cache-control': 'no-cache', 'connection': 'close', 'p3p': 'CP="NOI ADM DEV COM NAV OUR STP"'} def __init__(self, routes, **kwargs): self.error_view = kwargs.get('error_view') proxy_options = kwargs.get('config', {}) if proxy_options: proxy_options = proxy_options.get('proxy_options', {}) self.magic_name = proxy_options.get('magic_name') if not self.magic_name: self.magic_name = self.DEF_MAGIC_NAME proxy_options['magic_name'] = self.magic_name self.extra_headers = proxy_options.get('extra_headers') if not self.extra_headers: self.extra_headers = self.EXTRA_HEADERS proxy_options['extra_headers'] = self.extra_headers res_type = proxy_options.get('cookie_resolver', True) if res_type == 'auth' or not res_type: self.resolver = ProxyAuthResolver(routes, proxy_options) elif res_type == 'ip': self.resolver = IPCacheResolver(routes, proxy_options) #elif res_type == True or res_type == 'cookie': # self.resolver = CookieResolver(routes, proxy_options) else: self.resolver = CookieResolver(routes, proxy_options) self.use_banner = proxy_options.get('use_banner', True) self.use_wombat = proxy_options.get('use_client_rewrite', True) self.proxy_cert_dl_view = proxy_options.get('proxy_cert_download_view') if not proxy_options.get('enable_https_proxy'): self.ca = None return try: from certauth.certauth import CertificateAuthority except ImportError: #pragma: no cover print('HTTPS proxy is not available as the "certauth" module ' + 'is not installed') print('Please install via "pip install certauth" ' + 'to enable HTTPS support') self.ca = None return # HTTPS Only Options ca_file = proxy_options.get('root_ca_file', self.CA_ROOT_FILE) # attempt to create the root_ca_file if doesn't exist # (generally recommended to create this seperately) ca_name = proxy_options.get('root_ca_name', self.CA_ROOT_NAME) certs_dir = proxy_options.get('certs_dir', self.CA_CERTS_DIR) self.ca = CertificateAuthority(ca_file=ca_file, certs_dir=certs_dir, ca_name=ca_name) self.use_wildcard = proxy_options.get('use_wildcard_certs', True) def __call__(self, env): is_https = (env['REQUEST_METHOD'] == 'CONNECT') ArchivalRouter.ensure_rel_uri_set(env) # for non-https requests, check non-proxy urls if not is_https: url = env['REL_REQUEST_URI'] if not url.startswith(('http://', 'https://')): return None env['pywb.proxy_scheme'] = 'http' route = None coll = None matcher = None response = None ts = None # check resolver, for pre connect resolve if self.resolver.pre_connect: route, coll, matcher, ts, response = self.resolver.resolve(env) if response: return response # do connect, then get updated url if is_https: response = self.handle_connect(env) if response: return response url = env['REL_REQUEST_URI'] else: parts = urlsplit(env['REL_REQUEST_URI']) hostport = parts.netloc.split(':', 1) env['pywb.proxy_host'] = hostport[0] env['pywb.proxy_port'] = hostport[1] if len(hostport) == 2 else '' env['pywb.proxy_req_uri'] = parts.path if parts.query: env['pywb.proxy_req_uri'] += '?' + parts.query env['pywb.proxy_query'] = parts.query if self.resolver.supports_switching: env['pywb_proxy_magic'] = self.magic_name # route (static) and other resources to archival replay if env['pywb.proxy_host'] == self.magic_name: env['REL_REQUEST_URI'] = env['pywb.proxy_req_uri'] # special case for proxy install response = self.handle_cert_install(env) if response: return response return None # check resolver, post connect if not self.resolver.pre_connect: route, coll, matcher, ts, response = self.resolver.resolve(env) if response: return response rel_prefix = '' custom_prefix = env.get('HTTP_PYWB_REWRITE_PREFIX', '') if custom_prefix: host_prefix = custom_prefix urlrewriter_class = UrlRewriter abs_prefix = True # always rewrite to absolute here rewrite_opts = dict(no_match_rel=True) else: host_prefix = env['pywb.proxy_scheme'] + '://' + self.magic_name urlrewriter_class = SchemeOnlyUrlRewriter abs_prefix = False rewrite_opts = {} # special case for proxy calendar if (env['pywb.proxy_host'] == 'query.' + self.magic_name): url = env['pywb.proxy_req_uri'][1:] rel_prefix = '/' if ts is not None: url = ts + '/' + url wbrequest = route.request_class(env, request_uri=url, wb_url_str=url, coll=coll, host_prefix=host_prefix, rel_prefix=rel_prefix, wburl_class=route.handler.get_wburl_type(), urlrewriter_class=urlrewriter_class, use_abs_prefix=abs_prefix, rewrite_opts=rewrite_opts, is_proxy=True) if matcher: route.apply_filters(wbrequest, matcher) # full rewrite and banner if self.use_wombat and self.use_banner: wbrequest.wb_url.mod = '' elif self.use_banner: # banner only, no rewrite wbrequest.wb_url.mod = 'bn_' else: # unaltered, no rewrite or banner wbrequest.wb_url.mod = 'uo_' response = route.handler(wbrequest) if not response: return None # add extra headers for replay responses if wbrequest.wb_url and wbrequest.wb_url.is_replay(): response.status_headers.replace_headers(self.extra_headers) # check for content-length res = response.status_headers.get_header('content-length') try: if int(res) > 0: return response except: pass # need to either chunk or buffer to get content-length if env.get('SERVER_PROTOCOL') == 'HTTP/1.1': response.status_headers.remove_header('content-length') response.status_headers.headers.append(('Transfer-Encoding', 'chunked')) response.body = self._chunk_encode(response.body) else: response.body = self._buffer_response(response.status_headers, response.body) return response @staticmethod def _chunk_encode(orig_iter): for chunk in orig_iter: if not len(chunk): continue chunk_len = b'%X\r\n' % len(chunk) yield chunk_len yield chunk yield b'\r\n' yield b'0\r\n\r\n' @staticmethod def _buffer_response(status_headers, iterator): out = SpooledTemporaryFile(ProxyRouter.BUFF_RESPONSE_MEM_SIZE) size = 0 for buff in iterator: size += len(buff) out.write(buff) content_length_str = str(size) # remove existing content length status_headers.replace_header('Content-Length', content_length_str) out.seek(0) return RewriteContent.stream_to_gen(out) def get_request_socket(self, env): if not self.ca: return None sock = None if env.get('uwsgi.version'): # pragma: no cover try: import uwsgi fd = uwsgi.connection_fd() conn = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM) try: sock = socket.socket(_sock=conn) except: sock = conn except Exception as e: pass elif env.get('gunicorn.socket'): # pragma: no cover sock = env['gunicorn.socket'] if not sock: # attempt to find socket from wsgi.input input_ = env.get('wsgi.input') if input_: if hasattr(input_, '_sock'): # pragma: no cover raw = input_._sock sock = socket.socket(_sock=raw) # pragma: no cover elif hasattr(input_, 'raw'): sock = input_.raw._sock return sock def handle_connect(self, env): sock = self.get_request_socket(env) if not sock: return WbResponse.text_response('HTTPS Proxy Not Supported', '405 HTTPS Proxy Not Supported') sock.send(b'HTTP/1.0 200 Connection Established\r\n') sock.send(b'Proxy-Connection: close\r\n') sock.send(b'Server: pywb proxy\r\n') sock.send(b'\r\n') hostname, port = env['REL_REQUEST_URI'].split(':') if not self.use_wildcard: certfile = self.ca.cert_for_host(hostname) else: certfile = self.ca.get_wildcard_cert(hostname) try: ssl_sock = ssl.wrap_socket(sock, server_side=True, certfile=certfile, #ciphers="ALL", suppress_ragged_eofs=False, ssl_version=ssl.PROTOCOL_SSLv23 ) env['pywb.proxy_ssl_sock'] = ssl_sock buffreader = BufferedReader(ssl_sock, block_size=self.BLOCK_SIZE) statusline = to_native_str(buffreader.readline().rstrip()) except Exception as se: raise BadRequestException(se.message) statusparts = statusline.split(' ') if len(statusparts) < 3: raise BadRequestException('Invalid Proxy Request: ' + statusline) env['REQUEST_METHOD'] = statusparts[0] env['REL_REQUEST_URI'] = ('https://' + env['REL_REQUEST_URI'].replace(':443', '') + statusparts[1]) env['SERVER_PROTOCOL'] = statusparts[2].strip() env['pywb.proxy_scheme'] = 'https' env['pywb.proxy_host'] = hostname env['pywb.proxy_port'] = port env['pywb.proxy_req_uri'] = statusparts[1] queryparts = env['REL_REQUEST_URI'].split('?', 1) env['PATH_INFO'] = queryparts[0] env['QUERY_STRING'] = queryparts[1] if len(queryparts) > 1 else '' env['pywb.proxy_query'] = env['QUERY_STRING'] while True: line = to_native_str(buffreader.readline()) if line: line = line.rstrip() if not line: break parts = line.split(':', 1) if len(parts) < 2: continue name = parts[0].strip() value = parts[1].strip() name = name.replace('-', '_').upper() if name not in ('CONTENT_LENGTH', 'CONTENT_TYPE'): name = 'HTTP_' + name env[name] = value env['wsgi.input'] = buffreader #remain = buffreader.rem_length() #if remain > 0: #remainder = buffreader.read() #env['wsgi.input'] = BufferedReader(BytesIO(remainder)) #remainder = buffreader.read(self.BLOCK_SIZE) #env['wsgi.input'] = BufferedReader(ssl_sock, # block_size=self.BLOCK_SIZE, # starting_data=remainder) def handle_cert_install(self, env): if env['pywb.proxy_req_uri'] in ('/', '/index.html', '/index.html'): available = (self.ca is not None) if self.proxy_cert_dl_view: return (self.proxy_cert_dl_view. render_response(available=available, pem_path=self.CERT_DL_PEM, p12_path=self.CERT_DL_P12)) elif env['pywb.proxy_req_uri'] == self.CERT_DL_PEM: if not self.ca: return None buff = b'' with open(self.ca.ca_file, 'rb') as fh: buff = fh.read() content_type = 'application/x-x509-ca-cert' headers = [('Content-Length', str(len(buff)))] return WbResponse.bin_stream([buff], content_type=content_type, headers=headers) elif env['pywb.proxy_req_uri'] == self.CERT_DL_P12: if not self.ca: return None buff = self.ca.get_root_PKCS12() content_type = 'application/x-pkcs12' headers = [('Content-Length', str(len(buff)))] return WbResponse.bin_stream([buff], content_type=content_type, headers=headers)
pombredanne/pywb
pywb/framework/proxy.py
Python
gpl-3.0
16,139
/* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'image', 'eo', { alertUrl: 'Bonvolu tajpi la retadreson de la bildo', alt: 'Anstataŭiga Teksto', border: 'Bordero', btnUpload: 'Sendu al Servilo', button2Img: 'Ĉu vi volas transformi la selektitan bildbutonon en simplan bildon?', hSpace: 'Horizontala Spaco', img2Button: 'Ĉu vi volas transformi la selektitan bildon en bildbutonon?', infoTab: 'Informoj pri Bildo', linkTab: 'Ligilo', lockRatio: 'Konservi Proporcion', menu: 'Atributoj de Bildo', resetSize: 'Origina Grando', title: 'Atributoj de Bildo', titleButton: 'Bildbutonaj Atributoj', upload: 'Alŝuti', urlMissing: 'La fontretadreso de la bildo mankas.', vSpace: 'Vertikala Spaco', validateBorder: 'La bordero devas esti entjera nombro.', validateHSpace: 'La horizontala spaco devas esti entjera nombro.', validateVSpace: 'La vertikala spaco devas esti entjera nombro.' });
tsmaryka/hitc
public/javascripts/ckeditor/plugins/image/lang/eo.js
JavaScript
gpl-3.0
1,029
/** * Copyright (c) 2010-11 The AEminium Project (see AUTHORS file) * * This file is part of Plaid Programming Language. * * Plaid Programming Language is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Plaid Programming Language is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Plaid Programming Language. If not, see <http://www.gnu.org/licenses/>. */ package aeminium.runtime.tools.benchmark; public class RTBench { private static Benchmark[] benchmarks = { new TaskCreationBenchmark(), new IndependentTaskGraph(), new LinearTaskGraph(), new FixedParallelMaxDependencies(), new ChildTaskBenchmark(), new FibonacciBenchmark() }; public static void usage() { System.out.println(); System.out.println("java aeminium.runtime.tools.benchmark.RTBench COMMAND"); System.out.println(""); System.out.println("COMMANDS:"); System.out.println(" list - List available benchmarks."); System.out.println(" run BENCHMARK - Run specified benchmark."); System.out.println(); } public static void main(String[] args) { if ( args.length == 0 ) { usage(); return; } if ( args[0].equals("list") ) { for( Benchmark benchmark : benchmarks ) { System.out.println(benchmark.getName()); } } else if ( args[0].equals("run") && args.length == 2 ) { Benchmark benchmark = null; for ( Benchmark b : benchmarks ) { if ( b.getName().equals(args[1])) { benchmark = b; } } if ( benchmark != null ) { Reporter reporter = new StringBuilderReporter(); reporter.startBenchmark(benchmark.getName()); benchmark.run(reporter); reporter.stopBenchmark(benchmark.getName()); reporter.flush(); } else { usage(); } } else { usage(); } } protected static void reportVMStats(Reporter reporter) { reporter.reportLn(String.format("Memory (TOTAL/MAX/FREE) (%d,%d,%d)", Runtime.getRuntime().totalMemory(), Runtime.getRuntime().maxMemory(), Runtime.getRuntime().freeMemory())); } }
AEminium/AeminiumRuntime
src/aeminium/runtime/tools/benchmark/RTBench.java
Java
gpl-3.0
2,591
<h1><?php the_issuu_message('Document'); ?></h1> <form action="" method="post" id="document-upload"> <input type="hidden" name="name" value="<?= $doc->name; ?>"> <table class="form-table"> <tbody> <tr> <th><label for="title"><?php the_issuu_message('Title'); ?></label></th> <td><input type="text" name="title" id="title" class="regular-text code" value="<?= $doc->title; ?>"></td> </tr> <tr> <th><label for="description"><?php the_issuu_message('Description'); ?></label></th> <td> <textarea name="description" id="description" cols="45" rows="6"><?= $doc->description; ?></textarea> </td> </tr> <tr> <th><label for="tags">Tags</label></th> <td> <textarea name="tags" id="tags" cols="45" rows="6"><?= $tags; ?></textarea> <p class="description"> <?php the_issuu_message('Use commas to separate tags. Do not use spaces.'); ?> </p> </td> </tr> <tr> <th><label><?php the_issuu_message('Publish date'); ?></label></th> <td> <input type="text" name="pub[day]" id="dia" placeholder="<?php the_issuu_message('Day'); ?>" class="small-text" maxlength="2" value="<?= date('d', strtotime($doc->publishDate)); ?>"> / <input type="text" name="pub[month]" id="mes" placeholder="<?php the_issuu_message('Month'); ?>" class="small-text" maxlength="2" value="<?= date('m', strtotime($doc->publishDate)); ?>"> / <input type="text" name="pub[year]" id="ano" placeholder="<?php the_issuu_message('Year'); ?>" class="small-text" maxlength="4" value="<?= date('Y', strtotime($doc->publishDate)); ?>"> <p class="description"> <?php the_issuu_message('Date of publication of the document.<br><strong>NOTE:</strong> If you do not enter a value, the current date will be used'); ?> </p> </td> </tr> <tr> <th><label for="commentsAllowed"><?php the_issuu_message('Allow comments'); ?></label></th> <td> <input type="checkbox" name="commentsAllowed" id="commentsAllowed" value="true" <?= ($doc->commentsAllowed == true)? 'checked' : ''; ?>> </td> </tr> <tr> <th><label for="downloadable"><?php the_issuu_message('Allow file download'); ?></label></th> <td> <input type="checkbox" name="downloadable" id="downloadable" value="true" <?= ($doc->downloadable == true)? 'checked' : ''; ?>> </td> </tr> <tr> <th><label><?php the_issuu_message('Access'); ?></label></th> <td> <?php if ($doc->access == 'private') : ?> <p><strong><?php the_issuu_message('Private'); ?></strong></p> <p class="description"> <?php the_issuu_message('To publish this document <a href="http://issuu.com/home/publications" target="_blank">click here</a>'); ?> </p> <?php else: ?> <p><strong><?php the_issuu_message('Public'); ?></strong></p> <?php endif; ?> </td> </tr> <tr> <th> <input type="submit" class="button-primary" value="<?php the_issuu_message('Update'); ?>"> <h3> <a href="admin.php?page=issuu-document-admin" style="text-decoration: none;"> <?php the_issuu_message('Back'); ?> </a> </h3> </th> </tr> </tbody> </table> </form>
wp-plugins/issuu-panel
menu/documento/forms/update.php
PHP
gpl-3.0
3,277
#include "component.h" #include "entity.h" namespace entity { Component::Component(Entity* parent) : QObject(parent) { if (parent != NULL) { parent->addComponent(this); } } } uint qHash(entity::HashableComponent* key, uint seed) { return key == 0 ? 0 : key->hash(seed); }
alaineman/PowerGrid
src/EntityFramework/entity/component.cpp
C++
gpl-3.0
312
import java.util.List; import java.util.LinkedList; import java.util.ArrayList; import java.util.Arrays; import java.io.File; import java.io.BufferedReader; import java.io.FileReader; import java.util.Scanner; import java.io.IOException; import java.io.FileNotFoundException; import java.lang.NumberFormatException; import java.util.Collections; public class FanMapMaker { private static class IntList extends ArrayList<Integer> {} private void printChargesArray(int[] distribution, int size) { int percent; System.out.println("temp2tcharge:"); for(int i = 0; i <= size; i++) { // retlw .248 ;31 PWM=97% percent = (100*i)/60; System.out.println("\tretlw\t\t." + distribution[percent] + "\t\t; " + i + " " + percent + "%"); } } private void printChargesArrayStatAll(int[] distribution, int size) { int percent; System.out.println("temp2tcharge_tab:"); for(int i = 0; i <= size; i++) { percent = (100*i)/size; System.out.println("\XORLW\t\t."+i+"\n"+ "\tBTFSC\t\tSTATUS,Z\n"+ "\tMOVLW\t\t."+distribution[percent]+"\t\t; [" + i + "] " + percent + "%\n" ); } System.out.println("\tGOTO\t\ttemp2tcharge_tab_end"); } private void printChargesArrayStatic(int[] distribution, int size) { int percent; String tmpRegName = "TMP0"; String endLabel = "temp2tcharge_tab_end"; System.out.println("temp2tcharge_tab:"); System.out.println("\tMOVLW\t\t.255\n\tMOVF\t\t"+tmpRegName+",F\n\tBTFSS\t\tSTATUS,Z\n\tGOTO\t\tnext1\n\tGOTO\t\t"+endLabel); for(int i = 1; i <= size; i++) { // retlw .248 ;31 PWM=97% percent = (100*i)/60; //System.out.println("\tretlw\t\t." + distribution[percent] + "\t\t; " + i + " " + percent + "%"); System.out.println("next"+i+":\n\tMOVLW\t\t."+ distribution[percent]+"\t\t; [" + i + "] " + percent + "%\n\tDECFSZ\t\t"+tmpRegName+",F\n\tBTFSS\t\tSTATUS,Z\n\tGOTO\t\t"+ ((i<size) ? "next"+(i+1) : endLabel) + "\n\tGOTO\t\t"+endLabel); } } public static void main(String[] a) { FanMapMaker fmp = new FanMapMaker(); IntList percentToCharge[] = new IntList[101]; int res[] = new int[101]; for(int i = 0; i < percentToCharge.length; i++) percentToCharge[i] = new IntList(); File decFile = new File("allDec.dat"); File incFile = new File("allInc.dat"); BufferedReader decReader = null; BufferedReader incReader = null; Integer tchrg; Integer fanPercx; Float sum; Float fanPerc; try { //decReader = new BufferedReader(new FileReader(decFile)); //incReader = new BufferedReader(new FileReader(incFile)); Scanner decScan = new Scanner(decFile); Scanner incScan = new Scanner(incFile); int cnt = 0; while (decScan.hasNext()) { tchrg = decScan.nextInt(); fanPerc = 0.0f; for(int i = 0; i < 3; i++) { fanPerc += decScan.nextFloat(); } fanPerc /= 3.0f; fanPercx = Math.round(fanPerc); percentToCharge[fanPercx].add(tchrg); //new Float(decScan.nextFloat()) //System.out.println(tchrg + " " + fanPercx); } while (incScan.hasNext()) { tchrg = incScan.nextInt(); fanPerc = 0.0f; for(int i = 0; i < 3; i++) { fanPerc += incScan.nextFloat(); } fanPerc /= 3.0f; fanPercx = Math.round(fanPerc); percentToCharge[fanPercx].add(tchrg); //new Float(decScan.nextFloat()) //System.out.println(tchrg + " " + fanPercx); } for (int i = 0; i < percentToCharge.length; i++) { Collections.sort(percentToCharge[i]); //System.out.print("" + i + " " + "["); for(Integer e: percentToCharge[i]) { //System.out.print(e + " "); } //System.out.println("]"); } int last = 1; for (int i = percentToCharge.length - 1; i >= 0; i--) { if(percentToCharge[i].size() > 0) { res[i] = percentToCharge[i].get(0); last = res[i]; } else { res[i] = last; } //System.out.println(i + " " + res[i]); } fmp.printChargesArrayStatAll(res, 50); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (NumberFormatException e) { e.printStackTrace(); } finally { /*try { if (decReader != null) { //decReader.close(); } } //catch (IOException e) { //} try { if (incReader != null) { //incReader.close(); } } //catch (IOException e) { //} */ } } }
pworkshop/FanReg
tools/FanMapMaker.java
Java
gpl-3.0
4,595
# -*- coding: utf-8 -*- import os from pygal import * def listeEuler(f, x0, y0, pas, n): x, y, L = x0, y0, [] for k in range(n): L += [(x, y)] x += pas y += pas * f(x, y) return L def euler(f, x0, y0, xf, n): pas = (xf - x0) / n courbe = XY() courbe.title = "Methode d Euler" courbe.add("Solution approchee", listeEuler(f, x0, y0, pas, n)) courbe.render_to_file("courbeEulerPython.svg") os.system("pause")
NicovincX2/Python-3.5
Analyse (mathématiques)/Analyse fonctionnelle/Équation différentielle/euler.py
Python
gpl-3.0
468
vti_encoding:SR|utf8-nl vti_timelastmodified:TW|14 Aug 2014 12:39:17 -0000 vti_extenderversion:SR|12.0.0.0 vti_author:SR|Office-PC\\Rafael vti_modifiedby:SR|Office-PC\\Rafael vti_timecreated:TR|01 Nov 2014 09:09:36 -0000 vti_backlinkinfo:VX| vti_nexttolasttimemodified:TW|14 Aug 2014 12:39:17 -0000 vti_cacheddtm:TX|03 Nov 2015 21:05:11 -0000 vti_filesize:IR|554 vti_cachedneedsrewrite:BR|false vti_cachedhasbots:BR|false vti_cachedhastheme:BR|false vti_cachedhasborder:BR|false vti_charset:SR|utf-8 vti_syncofs_mydatalogger.de\:22/%2fvar/www/vhosts/s16851491.onlinehome-server.info/kaufreund.de:TW|14 Aug 2014 12:39:17 -0000 vti_syncwith_mydatalogger.de\:22/%2fvar/www/vhosts/s16851491.onlinehome-server.info/kaufreund.de:TW|03 Nov 2015 21:05:11 -0000
Vitronic/kaufreund.de
admin/language/english/openbay/_vti_cnf/amazonus_overview.php
PHP
gpl-3.0
753
// Copyright © 2014, 2015, Travis Snoozy // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. #include "cuisyntax.hpp" #include <boost/spirit/include/qi_parse.hpp> #include <cstdlib> #include <iostream> #include <iomanip> // Boost modules // Asio // Program Options namespace aha { namespace pawn { namespace testtool { std::ostream& operator<<(std::ostream& os, const aha::pawn::testtool::hex128_t& hex) { std::ios save(NULL); save.copyfmt(os); os << std::hex << std::setfill('0') << std::setw(8) << hex.byte1 << std::setw(8) << hex.byte2 << std::setw(8) << hex.byte3 << std::setw(8) << hex.byte4; os.copyfmt(save); return os; } std::ostream& operator<<(std::ostream& os, const aha::pawn::testtool::node_data_t& data) { std::ios save(NULL); save.copyfmt(os); os << std::setfill(' ') << std::left << std::setw(22) << "Key" << data.key << "\n" << std::setw(22) << "TX IV" << data.txiv << "\n" << std::setw(22) << "RX IV" << data.rxiv << "\n"; std::ios save2(NULL); save2.copyfmt(os); os << std::setw(22) << "Timeslot" << std::hex << std::setfill('0') << std::setw(4) << data.timeslot << "\n"; os.copyfmt(save2); os << std::setw(22) << "Timeslot enable" << data.enable_timeslot << "\n" << std::setw(22) << "TX encryption enable" << data.enable_tx_encryption << "\n" << std::setw(22) << "RX decryption enable" << data.enable_rx_decryption << "\n"; os.copyfmt(save); return os; } enum class option_visitor_result { SUCCESS, DOES_NOT_EXIST, ALREADY_EXISTS, INVALID_COMMAND, UNEXPECTED_DATA }; class option_visitor : public boost::static_visitor<option_visitor_result> { private: boost::spirit::qi::symbols<char, node_data_t> nodes; public: option_visitor_result operator()(const option_display_command_t& cmd) { nodes.for_each([](std::string& key, node_data_t& value){ std::cout << "Node " << key << "\n" << value << std::endl; }); return option_visitor_result::SUCCESS; } option_visitor_result operator()(const option_display_node_command_t& cmd) { node_data_t* node = nodes.find(cmd.node); if(node == NULL) { return option_visitor_result::DOES_NOT_EXIST; } std::cout << "Node " << cmd.node << "\n" << *node << std::endl; return option_visitor_result::SUCCESS; } option_visitor_result operator()(const option_set_node_command_t& cmd) { node_data_t* node = nodes.find(cmd.node); if(node == NULL) { return option_visitor_result::DOES_NOT_EXIST; } switch(cmd.param) { case option_set_node_param::KEY: node->key = boost::get<hex128_t>(cmd.data); break; case option_set_node_param::RXDECRYPT: node->enable_rx_decryption = boost::get<bool>(cmd.data); break; case option_set_node_param::RXIV: node->rxiv = boost::get<hex128_t>(cmd.data); break; case option_set_node_param::TIMESLOT: if(cmd.data.type() == typeid(bool)) { node->enable_timeslot = boost::get<bool>(cmd.data); } else if(cmd.data.type() == typeid(hex128_t)) { node->timeslot = (uint16_t)boost::get<hex128_t>(cmd.data).byte4; } else { return option_visitor_result::UNEXPECTED_DATA; } break; case option_set_node_param::TXENCRYPT: node->enable_tx_encryption = boost::get<bool>(cmd.data); break; case option_set_node_param::TXIV: node->txiv = boost::get<hex128_t>(cmd.data); break; default: return option_visitor_result::INVALID_COMMAND; } return option_visitor_result::SUCCESS; } option_visitor_result operator()(const option_create_node_command_t& cmd) { if(nodes.find(cmd.node) != NULL) { return option_visitor_result::ALREADY_EXISTS; } nodes.at(cmd.node); return option_visitor_result::SUCCESS; } option_visitor_result operator()(const transmit_command_t& cmd) { node_data_t* node = nodes.find(cmd.node); if(node == NULL) { return option_visitor_result::DOES_NOT_EXIST; } // TODO: Write this out to the designated serial port. return option_visitor_result::SUCCESS; } }; }}} using aha::pawn::testtool::option_visitor_result; int main(int argc, char** argv) { std::string input; std::string message; aha::pawn::testtool::command_t* command; std::string::const_iterator begin, end; aha::pawn::testtool::grammar::cui_grammar<std::string::const_iterator> grammar; std::getline(std::cin, input); aha::pawn::testtool::option_visitor option_visitor; while(input != "quit") { command = new aha::pawn::testtool::command_t(); begin = input.begin(); end = input.end(); bool result = boost::spirit::qi::phrase_parse( begin, end, grammar, boost::spirit::ascii::space, (*command)); if(result && begin == end) { switch(boost::apply_visitor(option_visitor, *command)) { case option_visitor_result::SUCCESS: std::cout << "OK."; break; case option_visitor_result::DOES_NOT_EXIST: std::cout << "Node does not exist."; break; case option_visitor_result::ALREADY_EXISTS: std::cout << "Node already exists."; break; case option_visitor_result::INVALID_COMMAND: case option_visitor_result::UNEXPECTED_DATA: std::cout << "An unexpected error occurred."; break; } std::cout << std::endl; } else { std::cout << "Could not parse that." << std::endl; } delete command; std::getline(std::cin, input); } return EXIT_SUCCESS; } // vim: set expandtab ts=4 sts=4 sw=4 fileencoding=utf-8:
Travis-Snoozy/AffordableHomeAutomation
c/pawn-testtool/main.cpp
C++
gpl-3.0
7,041
import {Injectable} from '@angular/core'; import {SnackBarService} from './snack-bar.service'; import {LangChangeEvent, TranslateService} from '@ngx-translate/core'; @Injectable({ providedIn: 'root' }) export class TranslatableSnackBarService { /** * @param snackBarService * @param translateService */ constructor(private snackBarService: SnackBarService, private translateService: TranslateService) { this.translateService.onLangChange.subscribe((event: LangChangeEvent) => { this.translateService.get('snackbarMessages.dismiss').subscribe((res: string) => { this.snackBarService.setDefaultAction(res); }); }); } /** * Emit snackbar with given duration * @param {string} key * @param {Object} interpolateParams * @param {number} duration */ open(key: string, interpolateParams: Object = {}, duration: number = SnackBarService.defaultDuration): void { this.translateService.get(key, interpolateParams).subscribe((message: string) => { this.snackBarService.open(message, duration); }); } /** * Emit snackbar with duration short * @param {string} key * @param {Object} interpolateParams */ openShort(key: string, interpolateParams: Object = {}): void { this.open(key, interpolateParams, SnackBarService.durationShort); } /** * Emit snackbar with duration long * @param {string} key * @param {Object} interpolateParams */ openLong(key: string, interpolateParams: Object = {}): void { this.open(key, interpolateParams, SnackBarService.durationLong); } }
h-da/geli
app/webFrontend/src/app/shared/services/translatable-snack-bar.service.ts
TypeScript
gpl-3.0
1,580
import { AccessToken, Project, User, UserFeatureFlag, UserRole } from '@dev/translatr-model'; import { map } from 'rxjs/operators'; // General export const isAdmin = (user?: User): boolean => user !== undefined && user.role === UserRole.Admin; // Users export const hasCreateUserPermission = () => map(isAdmin); export const hasUserPermissionToDeleteUser = (me: User, user: User) => me !== undefined && me.id !== user.id && isAdmin(me); export const hasEditUserPermission = (user: User) => map((me?: User) => (me !== undefined && me.id === user.id) || isAdmin(me)); export const hasDeleteUserPermission = (user: User) => map((me?: User) => hasUserPermissionToDeleteUser(me, user)); export const hasDeleteAllUsersPermission = (users: User[]) => map((me?: User) => users .map((user: User) => hasUserPermissionToDeleteUser(me, user)) .reduce((acc: boolean, next: boolean) => acc && next, true) ); // Projects export const hasUserPermissionToDeleteProject = (me: User, project: Project) => (me !== undefined && me.id === project.ownerId) || isAdmin(me); export const hasEditProjectPermission = (project: Project) => map((me?: User) => (me !== undefined && me.id === project.ownerId) || isAdmin(me)); export const hasDeleteProjectPermission = (project: Project) => map((me?: User) => hasUserPermissionToDeleteProject(me, project)); export const hasDeleteAllProjectsPermission = (projects: Project[]) => map((me?: User) => projects .map((project: Project) => hasUserPermissionToDeleteProject(me, project)) .reduce((acc: boolean, next: boolean) => acc && next, true) ); // Access Tokens export const hasUserPermissionToEditAccessToken = (me: User, accessToken: AccessToken) => (me !== undefined && me.id === accessToken.userId) || isAdmin(me); export const hasUserPermissionToDeleteAccessToken = (me: User, accessToken: AccessToken) => (me !== undefined && me.id === accessToken.userId) || isAdmin(me); export const hasEditAccessTokenPermission = (accessToken: AccessToken) => map((me?: User) => hasUserPermissionToEditAccessToken(me, accessToken)); export const hasDeleteAccessTokenPermission = (accessToken: AccessToken) => map((me?: User) => hasUserPermissionToDeleteAccessToken(me, accessToken)); export const hasDeleteAllAccessTokensPermission = (accessTokens: AccessToken[]) => map((me?: User) => accessTokens .map((accessToken: AccessToken) => hasUserPermissionToDeleteAccessToken(me, accessToken)) .reduce((acc: boolean, next: boolean) => acc && next, true) ); // Feature Flags export const hasUserPermissionToEditFeatureFlag = (me: User, featureFlag: UserFeatureFlag) => (me !== undefined && me.id === featureFlag.userId) || isAdmin(me); export const hasUserPermissionToDeleteFeatureFlag = (me: User, featureFlag: UserFeatureFlag) => (me !== undefined && me.id === featureFlag.userId) || isAdmin(me); export const hasEditFeatureFlagPermission = (featureFlag: UserFeatureFlag) => map((me?: User) => hasUserPermissionToEditFeatureFlag(me, featureFlag)); export const hasDeleteFeatureFlagPermission = (featureFlag: UserFeatureFlag) => map((me?: User) => hasUserPermissionToDeleteFeatureFlag(me, featureFlag)); export const hasDeleteAllFeatureFlagsPermission = (featureFlags: UserFeatureFlag[]) => map((me?: User) => featureFlags .map((featureFlag: UserFeatureFlag) => hasUserPermissionToDeleteFeatureFlag(me, featureFlag)) .reduce((acc: boolean, next: boolean) => acc && next, true) );
resamsel/translatr
ui/libs/translatr-sdk/src/lib/shared/permissions.ts
TypeScript
gpl-3.0
3,518
package com.bytezone.diskbrowser.nufx; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import com.bytezone.diskbrowser.prodos.write.DiskFullException; import com.bytezone.diskbrowser.prodos.write.FileAlreadyExistsException; import com.bytezone.diskbrowser.prodos.write.ProdosDisk; import com.bytezone.diskbrowser.prodos.write.VolumeCatalogFullException; // -----------------------------------------------------------------------------------// public class Binary2 // -----------------------------------------------------------------------------------// { private static final String UNDERLINE = "------------------------------------------------------" + "-----------------------"; Binary2Header binary2Header; byte[] buffer; List<Binary2Header> headers = new ArrayList<> (); int totalBlocks; String fileName; // ---------------------------------------------------------------------------------// public Binary2 (Path path) throws IOException // ---------------------------------------------------------------------------------// { fileName = path.toFile ().getName (); buffer = Files.readAllBytes (path); read (buffer); } // ---------------------------------------------------------------------------------// private void read (byte[] buffer) // ---------------------------------------------------------------------------------// { int ptr = 0; do { binary2Header = new Binary2Header (buffer, ptr); System.out.println (binary2Header); headers.add (binary2Header); totalBlocks += binary2Header.totalBlocks; ptr += ((binary2Header.eof - 1) / 128 + 1) * 128 + 128; } while (binary2Header.filesToFollow > 0); } // ---------------------------------------------------------------------------------// public byte[] getDiskBuffer () throws DiskFullException, VolumeCatalogFullException, FileAlreadyExistsException, IOException // ---------------------------------------------------------------------------------// { ProdosDisk disk = new ProdosDisk (800, "DiskBrowser"); for (Binary2Header header : headers) { byte[] dataBuffer = new byte[header.eof]; // this sux System.arraycopy (buffer, header.ptr + 128, dataBuffer, 0, dataBuffer.length); disk.addFile (header.fileName, header.fileType, header.auxType, header.created, header.modified, dataBuffer, header.eof); } disk.close (); return disk.getBuffer (); } // ---------------------------------------------------------------------------------// @Override public String toString () // ---------------------------------------------------------------------------------// { StringBuilder text = new StringBuilder (); text.append (String.format ( " %-15.15s Files:%5d%n%n", fileName, headers.size ())); text.append (" Name Type Auxtyp Modified" + " Fmat Length\n"); text.append (String.format ("%s%n", UNDERLINE)); for (Binary2Header header : headers) text.append (String.format ("%s%n", header.getLine ())); text.append (String.format ("%s%n", UNDERLINE)); return text.toString (); } }
dmolony/DiskBrowser
src/com/bytezone/diskbrowser/nufx/Binary2.java
Java
gpl-3.0
3,371
package componentes; import javax.swing.JTextField; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.PlainDocument; public class JTextFieldPrazo extends PlainDocument { /** * */ private static final long serialVersionUID = -8020852662258513751L; private int iMaxLength; private JTextField txt; private long num; public JTextFieldPrazo(int pMaxLen, JTextField pText) { super(); iMaxLength = pMaxLen; txt = pText; } public void insertString(int pOffSet, String pString, AttributeSet pAttributSet) throws BadLocationException { if (pString == null) return; if (iMaxLength <= 0) {// aceitara qualquer no. de caracteres super.insertString(pOffSet, pString, pAttributSet); return; } long ilen = (getLength() + pString.length()); try { if(pString.length()==1 && !pString.equals("-")) setNum(Long.parseLong(pString)); if(pString.equals("0") && txt.getText().length() == 0){ /**return;*/ } if (ilen <= iMaxLength) // se o comprimento final for menor... super.insertString(pOffSet, pString, pAttributSet); // ...aceita str else if (getLength() == iMaxLength) return; // nada a fazer else { String newStr = pString.substring(0, (iMaxLength - getLength())); super.insertString(pOffSet, newStr, pAttributSet); } } catch(Exception e) {} } public long getNum() { return num; } public void setNum(long num) { this.num = num; } }
DiegoEveling/RHFacil
src/componentes/JTextFieldPrazo.java
Java
gpl-3.0
1,557
using System; using System.IO; using System.Linq; namespace FocalLengthAnalyzer { public class Program { public void Main(string[] args) { if (args.Count()<1) { Console.WriteLine("Please pass the path to the directory with jpeg files as the first argument."); return; } if (!Directory.Exists(args[0])) { Console.WriteLine($"Error: directory {args[0]} does not exits."); return; } var analyzer = new Analyzer(); analyzer.AnalyzeDirectoryContent(args[0]); } } }
mkorz/FocalLengthAnalyzer
src/FocalLengthAnalyzer/Program.cs
C#
gpl-3.0
641
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import argparse import pprint import proteindf_bridge as bridge import logging import logging.config def get_rest_of_frame_molecule(frame_molecule, selected_molecule): # calc the rest selector = bridge.Select_AtomGroup(selected_molecule) selected = frame_molecule.select(selector) rest_molecule = frame_molecule ^ selected return rest_molecule def assign_rest_molecule(rest_molecule, output_atom_group, model_id="model_1", chain_id="Z", res_name="UNK"): chain = bridge.AtomGroup() res = bridge.AtomGroup() res.name = res_name atom_id = 1 for atom in rest_molecule.get_atom_list(): res.set_atom(atom_id, atom) atom_id += 1 chain.set_group(1, res) output_atom_group[model_id].set_group(chain_id, chain) def main(): parser = argparse.ArgumentParser( description='restructure brd file by reference file') parser.add_argument('target_brd_path', nargs=1, help='target brd file') parser.add_argument('ref_brd_path', nargs=1, help='reference brd file') parser.add_argument('-o', '--output_path', nargs=1, default=["output.brd"]) parser.add_argument('-r', '--range', nargs=1, default=[1.0E-5]) parser.add_argument('-v', '--verbose', action='store_true', default=False) args = parser.parse_args() # print(args) target_brd_path = args.target_brd_path[0] ref_brd_path = args.ref_brd_path[0] output_path = args.output_path[0] range = float(args.range[0]) verbose = args.verbose if verbose: print("target: {}".format(target_brd_path)) print("reference: {}".format(ref_brd_path)) # load target_ag = bridge.load_atomgroup(target_brd_path) ref_ag = bridge.load_atomgroup(ref_brd_path) # matching #target_selector = bridge.Select_AtomGroup(target_ag) #restructured = ref_ag.select(target_selector) # calc the rest #rest_of_target = get_rest_of_frame_molecule(target_ag, restructured) #assign_rest_molecule(rest_of_target, restructured) restructured = target_ag.restructure(ref_ag, range) if output_path: if verbose: print("output brd file: {}".format(output_path)) bridge.save_atomgroup(restructured, output_path) if __name__ == '__main__': #import cProfile #pr = cProfile.Profile() # pr.enable() main() # pr.disable() # pr.dump_stats('program.profile')
ProteinDF/ProteinDF_bridge
scripts/brd-restructure.py
Python
gpl-3.0
2,717
package se.vidstige.jadb; import se.vidstige.jadb.managers.Bash; import java.io.*; import java.util.ArrayList; import java.util.List; public class JadbDevice { public enum State { Unknown, Offline, Device, Recovery, BootLoader }; private final String serial; private final ITransportFactory transportFactory; JadbDevice(String serial, String type, ITransportFactory tFactory) { this.serial = serial; this.transportFactory = tFactory; } static JadbDevice createAny(JadbConnection connection) { return new JadbDevice(connection); } private JadbDevice(ITransportFactory tFactory) { serial = null; this.transportFactory = tFactory; } private State convertState(String type) { switch (type) { case "device": return State.Device; case "offline": return State.Offline; case "bootloader": return State.BootLoader; case "recovery": return State.Recovery; default: return State.Unknown; } } private Transport getTransport() throws IOException, JadbException { Transport transport = transportFactory.createTransport(); if (serial == null) { transport.send("host:transport-any"); transport.verifyResponse(); } else { transport.send("host:transport:" + serial); transport.verifyResponse(); } return transport; } public String getSerial() { return serial; } public State getState() throws IOException, JadbException { Transport transport = transportFactory.createTransport(); if (serial == null) { transport.send("host:get-state"); transport.verifyResponse(); } else { transport.send("host-serial:" + serial + ":get-state"); transport.verifyResponse(); } State state = convertState(transport.readString()); transport.close(); return state; } /** <p>Execute a shell command.</p> * * <p>For Lollipop and later see: {@link #execute(String, String...)}</p> * * @param command main command to run. E.g. "ls" * @param args arguments to the command. * @return combined stdout/stderr stream. * @throws IOException * @throws JadbException */ public InputStream executeShell(String command, String... args) throws IOException, JadbException { Transport transport = getTransport(); StringBuilder shellLine = buildCmdLine(command, args); send(transport, "shell:" + shellLine.toString()); return new AdbFilterInputStream(new BufferedInputStream(transport.getInputStream())); } /** * * @deprecated Use InputStream executeShell(String command, String... args) method instead. Together with * Stream.copy(in, out), it is possible to achieve the same effect. */ @Deprecated public void executeShell(OutputStream output, String command, String... args) throws IOException, JadbException { Transport transport = getTransport(); StringBuilder shellLine = buildCmdLine(command, args); send(transport, "shell:" + shellLine.toString()); if (output != null) { AdbFilterOutputStream out = new AdbFilterOutputStream(output); try { transport.readResponseTo(out); } finally { out.close(); } } } /** <p>Execute a command with raw binary output.</p> * * <p>Support for this command was added in Lollipop (Android 5.0), and is the recommended way to transmit binary * data with that version or later. For earlier versions of Android, use * {@link #executeShell(String, String...)}.</p> * * @param command main command to run, e.g. "screencap" * @param args arguments to the command, e.g. "-p". * @return combined stdout/stderr stream. * @throws IOException * @throws JadbException */ public InputStream execute(String command, String... args) throws IOException, JadbException { Transport transport = getTransport(); StringBuilder shellLine = buildCmdLine(command, args); send(transport, "exec:" + shellLine.toString()); return new BufferedInputStream(transport.getInputStream()); } /** * Builds a command line string from the command and its arguments. * * @param command the command. * @param args the list of arguments. * @return the command line. */ private StringBuilder buildCmdLine(String command, String... args) { StringBuilder shellLine = new StringBuilder(command); for (String arg : args) { shellLine.append(" "); shellLine.append(Bash.quote(arg)); } return shellLine; } public List<RemoteFile> list(String remotePath) throws IOException, JadbException { Transport transport = getTransport(); SyncTransport sync = transport.startSync(); sync.send("LIST", remotePath); List<RemoteFile> result = new ArrayList<RemoteFile>(); for (RemoteFileRecord dent = sync.readDirectoryEntry(); dent != RemoteFileRecord.DONE; dent = sync.readDirectoryEntry()) { result.add(dent); } return result; } private int getMode(File file) { //noinspection OctalInteger return 0664; } public void push(InputStream source, long lastModified, int mode, RemoteFile remote) throws IOException, JadbException { Transport transport = getTransport(); SyncTransport sync = transport.startSync(); sync.send("SEND", remote.getPath() + "," + Integer.toString(mode)); sync.sendStream(source); sync.sendStatus("DONE", (int) lastModified); sync.verifyStatus(); } public void push(File local, RemoteFile remote) throws IOException, JadbException { FileInputStream fileStream = new FileInputStream(local); push(fileStream, local.lastModified(), getMode(local), remote); fileStream.close(); } public void pull(RemoteFile remote, OutputStream destination) throws IOException, JadbException { Transport transport = getTransport(); SyncTransport sync = transport.startSync(); sync.send("RECV", remote.getPath()); sync.readChunksTo(destination); } public void pull(RemoteFile remote, File local) throws IOException, JadbException { FileOutputStream fileStream = new FileOutputStream(local); pull(remote, fileStream); fileStream.close(); } private void send(Transport transport, String command) throws IOException, JadbException { transport.send(command); transport.verifyResponse(); } @Override public String toString() { return "Device: " + serial; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((serial == null) ? 0 : serial.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; JadbDevice other = (JadbDevice) obj; if (serial == null) { if (other.serial != null) return false; } else if (!serial.equals(other.serial)) return false; return true; } }
Echtzeitsysteme/mindroid
impl/serverApp/src/main/java/se/vidstige/jadb/JadbDevice.java
Java
gpl-3.0
7,644
import RPi.GPIO as GPIO KnockPin = 11 LedPin = 12 Led_status = 1 def setup(): GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location GPIO.setup(LedPin, GPIO.OUT) # Set LedPin's mode is output GPIO.setup(KnockPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.output(LedPin, GPIO.HIGH) # Set LedPin high(+3.3V) to off led def swLed(ev=None): global Led_status Led_status = not Led_status GPIO.output(LedPin, Led_status) # switch led status(on-->off; off-->on) print "LED: " + ("on" if Led_status else "off") def loop(): GPIO.add_event_detect(KnockPin, GPIO.FALLING, callback=swLed, bouncetime=200) # wait for falling while True: pass # Don't do anything def destroy(): GPIO.output(LedPin, GPIO.LOW) # led off GPIO.cleanup() # Release resource if __name__ == '__main__': # Program start from here setup() try: loop() except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed. destroy()
bicard/raspberrypi
quad-store-sensors/37in1/knock-rgb-led-smd.py
Python
gpl-3.0
1,005
/* * Copyright (c) 2016 The Ontario Institute for Cancer Research. All rights reserved. * * This program and the accompanying materials are made available under the terms of the GNU Public License v3.0. * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.icgc.dcc.submission.server.repository; import static org.icgc.dcc.submission.core.model.QUser.user; import java.util.List; import org.icgc.dcc.submission.core.model.QUser; import org.icgc.dcc.submission.core.model.User; import org.mongodb.morphia.Datastore; import org.mongodb.morphia.Morphia; import org.springframework.beans.factory.annotation.Autowired; import lombok.NonNull; public class UserRepository extends AbstractRepository<User, QUser> { @Autowired public UserRepository(@NonNull Morphia morphia, @NonNull Datastore datastore) { super(morphia, datastore, user); } public List<User> findUsers() { return list(); } public User findUserByUsername(@NonNull String username) { return uniqueResult(entity.username.eq(username)); } public User saveUser(@NonNull User user) { save(user); return user; } public User updateUser(@NonNull User user) { return findAndModify( createQuery() .filter("username", user.getUsername()), createUpdateOperations() .set("failedAttempts", user.getFailedAttempts()), false, false); } }
icgc-dcc/dcc-submission
dcc-submission-server/src/main/java/org/icgc/dcc/submission/server/repository/UserRepository.java
Java
gpl-3.0
2,841
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (C) 2018 David Arroyo Menéndez # Author: David Arroyo Menéndez <davidam@gnu.org> # Maintainer: David Arroyo Menéndez <davidam@gnu.org> # This file is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # This file is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with GNU Emacs; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301 USA, # Python program to check if the input year is a leap year or not year = 2000 # To get year (integer input) from the user # year = int(input("Enter a year: ")) if (year % 4) == 0: if (year % 100) == 0: if (year % 400) == 0: print("{0} is a leap year".format(year)) else: print("{0} is not a leap year".format(year)) else: print("{0} is a leap year".format(year)) else: print("{0} is not a leap year".format(year))
davidam/python-examples
basics/leap.py
Python
gpl-3.0
1,385
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Code.Domain; /** * * @author Andres Orduz Grimaldo */ public class Jornada { private int id; private String nombre; private TipoJornada tipoJornada; private Anio anio; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public TipoJornada getTipoJornada() { return tipoJornada; } public void setTipoJornada(TipoJornada tipoJornada) { this.tipoJornada = tipoJornada; } public Anio getAnio() { return anio; } public void setAnio(Anio anio) { this.anio = anio; } }
LayneGranados/Colegios
GestionColegios/Codigo/GestionColegiosCliente/src/Code/Domain/Jornada.java
Java
gpl-3.0
950
<?php /* * Copyright (c) 2013 Algolia * http://www.algolia.com/ * * 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. * * */ namespace WC_Order_Search_Admin\AlgoliaSearch; use Exception; class ClientContext { /** * @var string */ public $applicationID; /** * @var string */ public $apiKey; /** * @var array */ public $readHostsArray; /** * @var array */ public $writeHostsArray; /** * @var resource */ public $curlMHandle; /** * @var string */ public $adminAPIKey; /** * @var string */ public $endUserIP; /** * @var string */ public $algoliaUserToken; /** * @var int */ public $connectTimeout; /** * @var FailingHostsCache */ private $failingHostsCache; /** * @param string|null $applicationID * @param string|null $apiKey * @param array|null $hostsArray * @param bool $placesEnabled * @param FailingHostsCache|null $failingHostsCache * * @throws Exception */ public function __construct($applicationID = null, $apiKey = null, $hostsArray = null, $placesEnabled = false, \WC_Order_Search_Admin\AlgoliaSearch\FailingHostsCache $failingHostsCache = null) { // connect timeout of 1s by default $this->connectTimeout = 1; // global timeout of 30s by default $this->readTimeout = 30; // search timeout of 5s by default $this->searchTimeout = 5; $this->applicationID = $applicationID; $this->apiKey = $apiKey; $this->readHostsArray = $hostsArray; $this->writeHostsArray = $hostsArray; if ($this->readHostsArray == null || count($this->readHostsArray) == 0) { $this->readHostsArray = $this->getDefaultReadHosts($placesEnabled); $this->writeHostsArray = $this->getDefaultWriteHosts(); } if (($this->applicationID == null || mb_strlen($this->applicationID) == 0) && $placesEnabled === false) { throw new \Exception('AlgoliaSearch requires an applicationID.'); } if (($this->apiKey == null || mb_strlen($this->apiKey) == 0) && $placesEnabled === false) { throw new \Exception('AlgoliaSearch requires an apiKey.'); } $this->curlMHandle = null; $this->adminAPIKey = null; $this->endUserIP = null; $this->algoliaUserToken = null; $this->rateLimitAPIKey = null; $this->headers = array(); if ($failingHostsCache === null) { $this->failingHostsCache = new \WC_Order_Search_Admin\AlgoliaSearch\InMemoryFailingHostsCache(); } else { $this->failingHostsCache = $failingHostsCache; } $this->rotateHosts(); } /** * @param bool $placesEnabled * * @return array */ private function getDefaultReadHosts($placesEnabled) { if ($placesEnabled) { $hosts = array('places-1.algolianet.com', 'places-2.algolianet.com', 'places-3.algolianet.com'); shuffle($hosts); array_unshift($hosts, 'places-dsn.algolia.net'); return $hosts; } $hosts = array($this->applicationID . '-1.algolianet.com', $this->applicationID . '-2.algolianet.com', $this->applicationID . '-3.algolianet.com'); shuffle($hosts); array_unshift($hosts, $this->applicationID . '-dsn.algolia.net'); return $hosts; } /** * @return array */ private function getDefaultWriteHosts() { $hosts = array($this->applicationID . '-1.algolianet.com', $this->applicationID . '-2.algolianet.com', $this->applicationID . '-3.algolianet.com'); shuffle($hosts); array_unshift($hosts, $this->applicationID . '.algolia.net'); return $hosts; } /** * Closes eventually opened curl handles. */ public function __destruct() { if (is_resource($this->curlMHandle)) { curl_multi_close($this->curlMHandle); } } /** * @param $curlHandle * * @return resource */ public function getMHandle($curlHandle) { if (!is_resource($this->curlMHandle)) { $this->curlMHandle = curl_multi_init(); } curl_multi_add_handle($this->curlMHandle, $curlHandle); return $this->curlMHandle; } /** * @param $curlHandle */ public function releaseMHandle($curlHandle) { curl_multi_remove_handle($this->curlMHandle, $curlHandle); } /** * @param string $ip */ public function setForwardedFor($ip) { $this->endUserIP = $ip; } /** * @param string $token */ public function setAlgoliaUserToken($token) { $this->algoliaUserToken = $token; } /** * @param string $adminAPIKey * @param string $endUserIP * @param string $rateLimitAPIKey */ public function setRateLimit($adminAPIKey, $endUserIP, $rateLimitAPIKey) { $this->adminAPIKey = $adminAPIKey; $this->endUserIP = $endUserIP; $this->rateLimitAPIKey = $rateLimitAPIKey; } /** * Disables the rate limit. */ public function disableRateLimit() { $this->adminAPIKey = null; $this->endUserIP = null; $this->rateLimitAPIKey = null; } /** * @param string $key * @param string $value */ public function setExtraHeader($key, $value) { $this->headers[$key] = $value; } /** * @param string $host */ public function addFailingHost($host) { $this->failingHostsCache->addFailingHost($host); } /** * @return FailingHostsCache */ public function getFailingHostsCache() { return $this->failingHostsCache; } /** * This method is called to pass on failing hosts. * If the host is first either in the failingHosts array, we * rotate the array to ensure the next API call will be directly made with a working * host. This mainly ensures we don't add the equivalent of the connection timeout value to each * request to the API. */ public function rotateHosts() { $failingHosts = $this->failingHostsCache->getFailingHosts(); $i = 0; while ($i <= count($this->readHostsArray) && in_array($this->readHostsArray[0], $failingHosts)) { $i++; $this->readHostsArray[] = array_shift($this->readHostsArray); } $i = 0; while ($i <= count($this->writeHostsArray) && in_array($this->writeHostsArray[0], $failingHosts)) { $i++; $this->writeHostsArray[] = array_shift($this->writeHostsArray); } } }
rayrutjes/wc-order-search-admin
libs/vendor/algolia/algoliasearch-client-php/src/AlgoliaSearch/ClientContext.php
PHP
gpl-3.0
7,874
<?php /* @var $this yii\web\View */ use yii\data\ActiveDataProvider; use yii\widgets\ListView; /* @var $books array */ /* @var $book \app\models\Books */ /* @var $booksPhotos \app\models\BooksPhotos */ /* @var $booksDataProvider ActiveDataProvider */ /* @var $popularBooksDataProvider ActiveDataProvider */ $this->title = Yii::t('seo','{appName} - Coding books | Programming Library', ['appName' => \Yii::$app->name]); $this->registerMetaTag([ 'name' => 'description', 'content' => Yii::t('seo', 'CoBooks is an online library consisting of books about programming, management of IT projects and other areas related to IT. Site for free online reading and downloading books in different formats.') ]); ?> <div class="row clearfix text-center"> <h2 class="title-one"> <?= Yii::t('seo', 'Free IT e-library') ?> </h2> <div id="books-categories" class="portfolio-filter"> <ul class="nav nav-pills text-center"> <li class="active"> <a data-toggle="pill" href="#popular-books"> <?= Yii::t('books', 'Popular Books') ?> </a> </li> <li> <a data-toggle="pill" href="#last-books"> <?= Yii::t('categories', 'Novelties') ?> </a> </li> </ul> </div> <div class="tab-content"> <div id="popular-books" class="tab-pane fade in active"> <div class="books-box"> <?= ListView::widget([ 'dataProvider' => $popularBooksDataProvider, 'summary' => false, 'layout' => '{items}', 'itemView' => '/parts/book', ]); ?> <a class="btn btn-default" href="<?= \yii\helpers\Url::to(['/book/popular']) ?>"> <?= Yii::t('app', 'View all') ?> </a> </div> </div> <div id="last-books" class="tab-pane fade"> <div class="books-box"> <?= ListView::widget([ 'dataProvider' => $booksDataProvider, 'summary' => false, 'layout' => '{items}', 'itemView' => '/parts/book', ]); ?> <a class="btn btn-default" href="<?= \yii\helpers\Url::to(['/book/last']) ?>"> <?= Yii::t('app', 'View all') ?> </a> </div> </div> </div> </div>
coding-books/website
views/site/index.php
PHP
gpl-3.0
2,499
function drawChart(len){ var box = document.createElement('div'); box.setAttribute('style','width:500px;height:500px;border:1px solid black;display:flex;flex-direction:column'); for(var i=0; i<len; i++){ var row = document.createElement('div'); if(i<len-1){ row.setAttribute('style','border-bottom:1px solid black;display:flex;box-sizing: border-box; flex: 1;'); } else{ row.setAttribute('style','display:flex;box-sizing: border-box; flex: 1;'); } for(var j=0; j<len; j++){ var col = document.createElement('div'); if(i%2===0){ if(j%2===0){ col.setAttribute('style','background-color:white; flex: 1;'); } else{ col.setAttribute('style','background-color:black; flex: 1;'); } }else{ if(j%2===0){ col.setAttribute('style','background-color:black; flex: 1;'); } else{ col.setAttribute('style','background-color:white; flex: 1;'); } } row.appendChild(col); } box.appendChild(row); } document.body.appendChild(box); } drawChart(5);
shashankKeshava/effective-enigma
jobCrunch/chess.js
JavaScript
gpl-3.0
1,186
package com.tage.rpgutil.client.gui; import net.minecraftforge.client.event.RenderGameOverlayEvent; import cpw.mods.fml.common.eventhandler.Cancelable; import cpw.mods.fml.common.eventhandler.Event; import cpw.mods.fml.common.eventhandler.EventPriority; @Cancelable public class GuiHealth extends Event { public static enum ElementType { ARMOR, HEALTH, } }
T4ge/RPGUtils
src/main/java/com/tage/rpgutil/client/gui/GuiHealth.java
Java
gpl-3.0
386
using System; using System.Linq; using System.Collections.Generic; using System.Reflection; using System.Xml; using log4net; using System.ComponentModel; using System.Xml.Serialization; using System.Text; using System.IO; using common; using jm726.lib.wrapper; using jm726.lib.wrapper.logger; namespace jm726.lib.wrapper.logger { /// <summary> /// Class which uses the ISpy interface to record all method calls to a given object. These are recorded to Xml. /// Can also play back recordings /// /// ONLY PUBLIC PROPERTIES WITH GETTERS _AND_ SETTERS WILL BE LOGGED CORRECTLY /// </summary> /// <typeparam name="TToLog">The interface which is being logged.</typeparam> public class XmlLogWriter<TToLog> : Wrapper<TToLog>, IXmlLogWriter<TToLog> where TToLog : class { #region Private Fields /// <summary> /// The log4net logger object used to log information to the console or log events. /// </summary> private readonly ILog _logger; /// <summary> /// The name of this logger. This is the name of the type being logged with '_Logger' added onto the end. /// </summary> private readonly string _name; /// <summary> /// The XML document which stores the event logging document as it is being built. /// </summary> private XmlDocument _doc; /// <summary> /// The root XML node to which all events are to be appended as children. /// </summary> private XmlNode _root; /// <summary> /// The XML document being built up to log all the events happening to the wrapped instance of TToLog. /// </summary> private DateTime _lastEvent; /// <summary> /// Wether or not events are to be logged currently. /// </summary> private bool _logging; /// <summary> /// Whether or not to serialize the return value of the method. /// </summary> private bool _recordForPlayback; #endregion #region XmlLogWriter Properties /// <inheritdoc /> public XmlDocument Log { get { return _doc; } } #endregion #region Constructor /// <summary> /// Constructor which creates a generic logger. Instantiates a series of helper fields and stores the TToLog instance which is to be wrapped by this logger. /// </summary> /// <param name="spy">The instance of TToLog which this logger will log calls to.</param> public XmlLogWriter(TToLog instance, bool recordForPlayback = false, bool recursive = true) : base(instance, "XmlLogWriter", recursive) { _lastEvent = default(DateTime); _recordForPlayback = recordForPlayback; _name = typeof(TToLog).FullName + "_Logger"; _logger = LogManager.GetLogger(_name); _doc = new XmlDocument(); XmlNode declaration = _doc.CreateXmlDeclaration("1.0", "utf-8", "yes"); _doc.AppendChild(declaration); } #endregion #region Override Abstract Methods from Wrapper public override void ReportMethodCallVoid(string methodName, object[] parameters) { if (!_logging) { CallMethod(methodName, parameters); return; } MethodCall m = new MethodCall(GetMethod(methodName, parameters), WrappedInstance, parameters); if (_recordForPlayback && !m.Type.Equals("Method") && !m.Type.Equals("PropertySet")) return; XmlNode callNode = m.Serialize(_doc, SwitchArgument); callNode.Attributes.Append(GetTimeAttr()); _root.AppendChild(callNode); } public override object ReportMethodCallReturn(string methodName, object[] parameters) { if (!_logging) return CallMethod(methodName, parameters); MethodCall m = new MethodCall(GetMethod(methodName, parameters), WrappedInstance, parameters); if (_recordForPlayback && !m.Type.Equals("Method") && !m.Type.Equals("PropertySet")) return m.Return; XmlNode callNode = m.Serialize(_doc, SwitchArgument, _recordForPlayback); callNode.Attributes.Append(GetTimeAttr()); _root.AppendChild(callNode); return m.Return; } public override void ReportEventTriggered(string eventName, object[] parameters) { //Do Nothing } /// <summary> /// Log the time at which a method call was made. /// </summary> private XmlAttribute GetTimeAttr() { XmlAttribute time = _doc.CreateAttribute("Time"); if (_lastEvent.Equals(default(DateTime))) time.Value = "0"; else time.Value = DateTime.Now.Subtract(_lastEvent).TotalMilliseconds + ""; _lastEvent = DateTime.Now; return time; } #endregion #region XmlLogWriter Methods /// <inheritdoc /> public void StartRecording() { if (_root != null) _doc.RemoveChild(_root); XmlNode root = _doc.CreateElement("Events"); _doc.AppendChild(root); StartRecording(_doc); } public void StartRecording(XmlDocument doc) { XmlNodeList roots = doc.GetElementsByTagName("Events"); if (roots.Count == 0) throw new ArgumentException("Unable to append events to supplied XML document. Document is not in the correct format"); _doc = doc; _doc.NodeInserted += (source, args) => { if (args.NewParent.Name.Equals("Events")) _lastEvent = DateTime.Now; }; _root = roots[0]; _lastEvent = default(DateTime); _logging = true; } /// <inheritdoc /> public void StopRecording() { _logging = false; } /// <inheritdoc /> public void PauseRecording() { _lastEvent = DateTime.Now; _logging = false; } /// <inheritdoc /> public void RestartRecording() { _logging = false; } #endregion #region Util /// <summary> /// Used for extensibility. /// /// Override this and check the type of the argument to define special behaviour for special types. /// Original defined so that instance specific IDs can be swapped to general but less unique names in the XML /// which can then be resolved back to new specific IDs when the sequence is played back. /// </summary> /// <param name="arg">The argument to swap for a different type.</param> /// <returns>The type to swap the argument to.</returns> protected virtual XmlNode SwitchArgument(ParameterInfo param, object arg) { return null; } #endregion } }
JohnMcCaffery/RoutingIsland
Source/Diagrams/jm726.lib/Wrapper/Logger/XmlLogWriter.cs
C#
gpl-3.0
7,090
/*! \file \author Igor Mironchik (igor.mironchik at gmail dot com). Copyright (c) 2017 Igor Mironchik This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef TREE__CAMERA_CONTROLLER_HPP__INCLUDED #define TREE__CAMERA_CONTROLLER_HPP__INCLUDED // Qt include. #include <Qt3DCore/QEntity> // C++ include. #include <memory> QT_BEGIN_NAMESPACE namespace Qt3DRender { class QCamera; } QT_END_NAMESPACE // // CameraController // class CameraControllerPrivate; class CameraController Q_DECL_FINAL : public Qt3DCore::QEntity { Q_OBJECT public: CameraController( Qt3DRender::QCamera * camera, Qt3DCore::QEntity * parent ); ~CameraController(); private slots: void _q_onTriggered( float ); private: friend class CameraControllerPrivate; Q_DISABLE_COPY( CameraController ) std::unique_ptr< CameraControllerPrivate > d; }; // class CameraController #endif // TREE__CAMERA_CONTROLLER_HPP__INCLUDED
igormironchik/3Dtree
3Dtree/camera_controller.hpp
C++
gpl-3.0
1,494
# Copyright 2015 Allen Institute for Brain Science # This file is part of Allen SDK. # # Allen SDK is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, version 3 of the License. # # Allen SDK is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Allen SDK. If not, see <http://www.gnu.org/licenses/>. from allensdk.api.api import Api import os, json from collections import OrderedDict class BiophysicalPerisomaticApi(Api): _NWB_file_type = 'NWB' _SWC_file_type = '3DNeuronReconstruction' _MOD_file_type = 'BiophysicalModelDescription' _FIT_file_type = 'NeuronalModelParameters' def __init__(self, base_uri=None): super(BiophysicalPerisomaticApi, self).__init__(base_uri) self.cache_stimulus = True self.ids = {} self.sweeps = [] self.manifest = {} def build_rma(self, neuronal_model_id, fmt='json'): '''Construct a query to find all files related to a neuronal model. Parameters ---------- neuronal_model_id : integer or string representation key of experiment to retrieve. fmt : string, optional json (default) or xml Returns ------- string RMA query url. ''' include_associations = ''.join([ 'neuronal_model_template(well_known_files(well_known_file_type)),', 'specimen', '(ephys_result(well_known_files(well_known_file_type)),' 'neuron_reconstructions(well_known_files(well_known_file_type)),', 'ephys_sweeps),', 'well_known_files(well_known_file_type)']) criteria_associations = ''.join([ ("[id$eq%d]," % (neuronal_model_id)), include_associations]) return ''.join([self.rma_endpoint, '/query.', fmt, '?q=', 'model::NeuronalModel,', 'rma::criteria,', criteria_associations, ',rma::include,', include_associations]) def read_json(self, json_parsed_data): '''Get the list of well_known_file ids from a response body containing nested sample,microarray_slides,well_known_files. Parameters ---------- json_parsed_data : dict Response from the Allen Institute Api RMA. Returns ------- list of strings Well known file ids. ''' self.ids = { 'stimulus': {}, 'morphology': {}, 'modfiles': {}, 'fit': {} } self.sweeps = [] if 'msg' in json_parsed_data: for neuronal_model in json_parsed_data['msg']: if 'well_known_files' in neuronal_model: for well_known_file in neuronal_model['well_known_files']: if ('id' in well_known_file and 'path' in well_known_file and self.is_well_known_file_type(well_known_file, BiophysicalPerisomaticApi._FIT_file_type)): self.ids['fit'][str(well_known_file['id'])] = \ os.path.split(well_known_file['path'])[1] if 'neuronal_model_template' in neuronal_model: neuronal_model_template = neuronal_model['neuronal_model_template'] if 'well_known_files' in neuronal_model_template: for well_known_file in neuronal_model_template['well_known_files']: if ('id' in well_known_file and 'path' in well_known_file and self.is_well_known_file_type(well_known_file, BiophysicalPerisomaticApi._MOD_file_type)): self.ids['modfiles'][str(well_known_file['id'])] = \ os.path.join('modfiles', os.path.split(well_known_file['path'])[1]) if 'specimen' in neuronal_model: specimen = neuronal_model['specimen'] if 'neuron_reconstructions' in specimen: for neuron_reconstruction in specimen['neuron_reconstructions']: if 'well_known_files' in neuron_reconstruction: for well_known_file in neuron_reconstruction['well_known_files']: if ('id' in well_known_file and 'path' in well_known_file and self.is_well_known_file_type(well_known_file, BiophysicalPerisomaticApi._SWC_file_type)): self.ids['morphology'][str(well_known_file['id'])] = \ os.path.split(well_known_file['path'])[1] if 'ephys_result' in specimen: ephys_result = specimen['ephys_result'] if 'well_known_files' in ephys_result: for well_known_file in ephys_result['well_known_files']: if ('id' in well_known_file and 'path' in well_known_file and self.is_well_known_file_type(well_known_file, BiophysicalPerisomaticApi._NWB_file_type)): self.ids['stimulus'][str(well_known_file['id'])] = \ "%d.nwb" % (ephys_result['id']) self.sweeps = [sweep['sweep_number'] for sweep in specimen['ephys_sweeps'] if sweep['stimulus_name'] != 'Test'] return self.ids def is_well_known_file_type(self, wkf, name): '''Check if a structure has the expected name. Parameters ---------- wkf : dict A well-known-file structure with nested type information. name : string The expected type name See Also -------- read_json: where this helper function is used. ''' try: return wkf['well_known_file_type']['name'] == name except: return False def get_well_known_file_ids(self, neuronal_model_id): '''Query the current RMA endpoint with a neuronal_model id to get the corresponding well known file ids. Returns ------- list A list of well known file id strings. ''' rma_builder_fn = self.build_rma json_traversal_fn = self.read_json return self.do_query(rma_builder_fn, json_traversal_fn, neuronal_model_id) def create_manifest(self, fit_path='', stimulus_filename='', swc_morphology_path='', sweeps=[]): '''Generate a json configuration file with parameters for a a biophysical experiment. Parameters ---------- fit_path : string filename of a json configuration file with cell parameters. stimulus_filename : string path to an NWB file with input currents. swc_morphology_path : string file in SWC format. sweeps : array of integers which sweeps in the stimulus file are to be used. ''' self.manifest = OrderedDict() self.manifest['biophys'] = [{ 'model_file': [ 'manifest.json', fit_path ] }] self.manifest['runs'] = [{ 'sweeps': sweeps }] self.manifest['neuron'] = [{ 'hoc': [ 'stdgui.hoc', 'import3d.hoc' ] }] self.manifest['manifest'] = [ { 'type': 'dir', 'spec': '.', 'key': 'BASEDIR' }, { 'type': 'dir', 'spec': 'work', 'key': 'WORKDIR', 'parent': 'BASEDIR' }, { 'type': 'file', 'spec': swc_morphology_path, 'key': 'MORPHOLOGY' }, { 'type': 'dir', 'spec': 'modfiles', 'key': 'MODFILE_DIR' }, { 'type': 'file', 'format': 'NWB', 'spec': stimulus_filename, 'key': 'stimulus_path' }, { 'parent_key': 'WORKDIR', 'type': 'file', 'format': 'NWB', 'spec': stimulus_filename, 'key': 'output' } ] def cache_data(self, neuronal_model_id, working_directory=None): '''Take a an experiment id, query the Api RMA to get well-known-files download the files, and store them in the working directory. Parameters ---------- neuronal_model_id : int or string representation found in the neuronal_model table in the api working_directory : string Absolute path name where the downloaded well-known files will be stored. ''' if working_directory is None: working_directory = self.default_working_directory try: os.stat(working_directory) except: os.mkdir(working_directory) work_dir = os.path.join(working_directory, 'work') try: os.stat(work_dir) except: os.mkdir(work_dir) modfile_dir = os.path.join(working_directory, 'modfiles') try: os.stat(modfile_dir) except: os.mkdir(modfile_dir) well_known_file_id_dict = self.get_well_known_file_ids(neuronal_model_id) for key, id_dict in well_known_file_id_dict.items(): if (not self.cache_stimulus) and (key == 'stimulus'): continue for well_known_id, filename in id_dict.items(): well_known_file_url = self.construct_well_known_file_download_url(well_known_id) cached_file_path = os.path.join(working_directory, filename) self.retrieve_file_over_http(well_known_file_url, cached_file_path) fit_path = self.ids['fit'].values()[0] stimulus_filename = self.ids['stimulus'].values()[0] swc_morphology_path = self.ids['morphology'].values()[0] sweeps = sorted(self.sweeps) self.create_manifest(fit_path, stimulus_filename, swc_morphology_path, sweeps) manifest_path = os.path.join(working_directory, 'manifest.json') with open(manifest_path, 'wb') as f: f.write(json.dumps(self.manifest, indent=2))
wvangeit/AllenSDK
allensdk/api/queries/biophysical_perisomatic_api.py
Python
gpl-3.0
12,180
/* eslint-disable no-self-assign */ import Game from '../../../../gui/html/js/game'; import { Plugin } from '../../../../gui/html/js/plugin'; import Translator from '../../../../gui/html/js/translator'; jest.mock('../../../../gui/html/js/dom'); jest.mock('../../../../gui/html/js/filters'); describe('Game', () => { const l10n = new Translator(); const defaultDerivedPluginMetadata = { name: 'test', isActive: false, isDirty: false, isEmpty: false, isMaster: false, isLightPlugin: false, loadsArchive: false, messages: [], suggestedTags: [], currentTags: [] }; const gameData = { folder: 'test', generalMessages: [ { type: 'say', text: 'test', language: 'en', condition: '' } ], masterlist: { revision: '0', date: '' }, groups: { masterlist: [], userlist: [] }, plugins: [defaultDerivedPluginMetadata], bashTags: [] }; describe('#constructor()', () => { test("should set folder to the object's value", () => { const game = new Game(gameData, l10n); expect(game.folder).toBe('test'); }); test("should set generalMessages to the object's value", () => { const game = new Game(gameData, l10n); expect(game.generalMessages).toEqual([ { type: 'say', text: 'test', language: 'en', condition: '' } ]); }); test("should set masterlist to the object's value", () => { const game = new Game(gameData, l10n); expect(game.masterlist).toEqual({ revision: '0', date: '' }); }); test("should construct plugins from the object's plugins value", () => { const game = new Game(gameData, l10n); expect(game.plugins.length).toBe(1); expect(game.plugins[0]).toHaveProperty('update'); expect(game.plugins[0].name).toBe('test'); expect(game.plugins[0].cardZIndex).toBe(1); }); test("should set oldLoadOrder to an empty array even if the object's value if defined", () => { const game = new Game(gameData, l10n); expect(game.oldLoadOrder).toEqual([]); }); }); describe('#folder', () => { let game: Game; // It's not worth the hassle of defining and checking the event type in test // code. // eslint-disable-next-line @typescript-eslint/no-explicit-any let handleEvent: (evt: any) => void; beforeEach(() => { game = new Game(gameData, l10n); }); afterEach(() => { document.removeEventListener('loot-game-folder-change', handleEvent); }); test('setting value should not dispatch an event if the new value is equal to the old one', done => { handleEvent = () => { done(new Error('Should not have fired an event')); }; document.addEventListener('loot-game-folder-change', handleEvent); game.folder = game.folder; setTimeout(done, 100); }); test('setting value should dispatch an event if the new value differs from the old one', done => { handleEvent = evt => { expect(evt.detail.folder).toBe('other test'); done(); }; document.addEventListener('loot-game-folder-change', handleEvent); game.folder = 'other test'; }); }); describe('#generalMessages', () => { let game: Game; // It's not worth the hassle of defining and checking the event type in test // code. // eslint-disable-next-line @typescript-eslint/no-explicit-any let handleEvent: (evt: any) => void; beforeEach(() => { game = new Game(gameData, l10n); }); afterEach(() => { document.removeEventListener( 'loot-game-global-messages-change', handleEvent ); }); test('setting value should not dispatch an event if the new value is equal to the old one', done => { handleEvent = () => { done(new Error('Should not have fired an event')); }; document.addEventListener( 'loot-game-global-messages-change', handleEvent ); game.generalMessages = game.generalMessages; setTimeout(done, 100); }); test('setting value should dispatch an event if the new and old message strings differ', done => { const newMessages = [ { type: 'say', text: 'bar', language: 'en', condition: '' } ]; handleEvent = evt => { expect(evt.detail.messages).toEqual(newMessages); expect(evt.detail.totalDiff).toBe(0); expect(evt.detail.errorDiff).toBe(0); expect(evt.detail.warningDiff).toBe(0); done(); }; document.addEventListener( 'loot-game-global-messages-change', handleEvent ); game.generalMessages = newMessages; }); test('setting value should dispatch an event if the new and old message type counts differ', done => { const newMessages = [ { type: 'warn', text: 'foo', language: 'en', condition: '' }, { type: 'error', text: 'bar', language: 'en', condition: '' } ]; game.generalMessages = []; handleEvent = evt => { expect(evt.detail.messages).toEqual(newMessages); expect(evt.detail.totalDiff).toBe(2); expect(evt.detail.errorDiff).toBe(1); expect(evt.detail.warningDiff).toBe(1); done(); }; document.addEventListener( 'loot-game-global-messages-change', handleEvent ); game.generalMessages = newMessages; }); }); describe('#masterlist', () => { let game: Game; // It's not worth the hassle of defining and checking the event type in test // code. // eslint-disable-next-line @typescript-eslint/no-explicit-any let handleEvent: (evt: any) => void; beforeEach(() => { game = new Game(gameData, l10n); }); afterEach(() => { document.removeEventListener('loot-game-masterlist-change', handleEvent); }); test('setting value should not dispatch an event if the new value is equal to the old one', done => { handleEvent = () => { done(new Error('Should not have fired an event')); }; document.addEventListener('loot-game-masterlist-change', handleEvent); game.masterlist = game.masterlist; setTimeout(done, 100); }); test('setting value should dispatch an event if the new value differs from the old one', done => { const newMasterlist = { revision: 'foo', date: 'bar' }; handleEvent = evt => { expect(evt.detail).toEqual(newMasterlist); done(); }; document.addEventListener('loot-game-masterlist-change', handleEvent); game.masterlist = newMasterlist; }); }); describe('#plugins', () => { let game: Game; // It's not worth the hassle of defining and checking the event type in test // code. // eslint-disable-next-line @typescript-eslint/no-explicit-any let handleEvent: (evt: any) => void; beforeEach(() => { game = new Game(gameData, l10n); }); afterEach(() => { document.removeEventListener('loot-game-plugins-change', handleEvent); }); test('setting value should dispatch an event if the new value is equal to the old one', done => { handleEvent = () => { done(); }; document.addEventListener('loot-game-plugins-change', handleEvent); game.plugins = game.plugins; }); test('setting value should dispatch an event if the new value differs from the old one', done => { const newMessages = [ { type: 'warn', text: 'foo', language: 'en', condition: '' }, { type: 'error', text: 'bar', language: 'en', condition: '' } ]; const newPlugins = [ new Plugin({ ...defaultDerivedPluginMetadata, name: 'a', isActive: true, messages: [newMessages[0]] }), new Plugin({ ...defaultDerivedPluginMetadata, name: 'b', isDirty: true, messages: [{ ...newMessages[0], type: 'say' }] }) ]; handleEvent = evt => { expect(evt.detail.valuesAreTotals).toBe(true); expect(evt.detail.totalMessageNo).toBe(4); expect(evt.detail.warnMessageNo).toBe(2); expect(evt.detail.errorMessageNo).toBe(1); expect(evt.detail.totalPluginNo).toBe(2); expect(evt.detail.activePluginNo).toBe(1); expect(evt.detail.dirtyPluginNo).toBe(1); done(); }; document.addEventListener('loot-game-plugins-change', handleEvent); game.generalMessages = newMessages; game.plugins = newPlugins; }); }); describe('groups', () => { test("get should return the game's groups", () => { const groups = { masterlist: [{ name: 'a', after: [] }], userlist: [{ name: 'b', after: [] }] }; const game = new Game({ ...gameData, groups }, l10n); expect(game.groups).toStrictEqual([ { name: 'a', after: [], isUserAdded: false }, { name: 'b', after: [], isUserAdded: true } ]); }); }); describe('#setGroups()', () => { // It's not worth the hassle of defining and checking the event type in test // code. // eslint-disable-next-line @typescript-eslint/no-explicit-any let handleEvent: (evt: any) => void; afterEach(() => { document.removeEventListener('loot-game-groups-change', handleEvent); }); test('should merge the given masterlist and userlist groups arrays', () => { const game = new Game(gameData, l10n); const groups = { masterlist: [{ name: 'a', after: [] }], userlist: [{ name: 'b', after: [] }] }; game.setGroups(groups); expect(game.groups).toStrictEqual([ { name: 'a', after: [], isUserAdded: false }, { name: 'b', after: [], isUserAdded: true } ]); }); test('should dispatch an event', done => { handleEvent = () => { done(); }; document.addEventListener('loot-game-groups-change', handleEvent); const game = new Game(gameData, l10n); const groups = { masterlist: [{ name: 'a', after: [] }], userlist: [{ name: 'b', after: [] }] }; game.setGroups(groups); }); }); describe('#getContent()', () => { let game: Game; beforeEach(() => { game = new Game(gameData, l10n); }); test('should return an object of two empty arrays if there is no game data', () => { game.plugins = []; game.generalMessages = []; expect(game.getContent()).toEqual({ messages: [], plugins: [] }); }); test('should return a structure containing converted plugin and message structures', () => { game.generalMessages = [ { type: 'say', condition: 'file("foo.esp")', language: 'fr', text: 'Bonjour le monde' } ]; game.plugins = [ new Plugin({ name: 'foo', crc: 0xdeadbeef, version: '1.0', isActive: true, isEmpty: true, isMaster: false, isLightPlugin: false, loadsArchive: true, group: 'group1', messages: [ { type: 'warn', condition: 'file("bar.esp")', language: 'en', text: 'Hello world' } ], currentTags: [ { name: 'Relev', isAddition: true, condition: '' } ], suggestedTags: [ { name: 'Delev', isAddition: true, condition: '' } ], isDirty: true }) ]; expect(game.getContent()).toEqual({ messages: game.generalMessages, plugins: [ { name: game.plugins[0].name, crc: game.plugins[0].crc, version: game.plugins[0].version, isActive: game.plugins[0].isActive, isEmpty: game.plugins[0].isEmpty, loadsArchive: game.plugins[0].loadsArchive, group: game.plugins[0].group, messages: game.plugins[0].messages, currentTags: game.plugins[0].currentTags, suggestedTags: game.plugins[0].suggestedTags, isDirty: game.plugins[0].isDirty } ] }); }); }); describe('#getPluginNames()', () => { let game: Game; beforeEach(() => { game = new Game(gameData, l10n); }); test('should return an empty array if there are no plugins', () => { game.plugins = []; expect(game.getPluginNames().length).toBe(0); }); test('should return an array of plugin filenames if there are plugins', () => { game.plugins = [ new Plugin({ ...defaultDerivedPluginMetadata, name: 'foo', isActive: true, messages: [{ type: 'warn', text: '', language: 'en', condition: '' }] }) ]; expect(game.getPluginNames()).toEqual(['foo']); }); }); describe('#getGroupPluginNames()', () => { let game: Game; beforeEach(() => { const plugins = [ new Plugin({ ...defaultDerivedPluginMetadata, name: 'foo', group: 'test group' }), new Plugin({ ...defaultDerivedPluginMetadata, name: 'bar', group: 'other group' }), new Plugin({ ...defaultDerivedPluginMetadata, name: 'foobar', group: 'test group' }) ]; game = new Game({ ...gameData, plugins }, l10n); }); test('should return an empty array if there are no plugins in the given group', () => { expect(game.getGroupPluginNames('empty group').length).toBe(0); }); test('should return an array of filenames of plugins in the given group', () => { expect(game.getGroupPluginNames('test group')).toEqual(['foo', 'foobar']); }); }); describe('#setSortedPlugins', () => { let game: Game; // It's not worth the hassle of defining and checking the event type in test // code. // eslint-disable-next-line @typescript-eslint/no-explicit-any let handleEvent: (evt: any) => void; beforeEach(() => { game = new Game(gameData, l10n); }); afterEach(() => { document.removeEventListener('loot-game-plugins-change', handleEvent); }); test('should append new plugins to the plugins array', () => { game.setSortedPlugins([ new Plugin({ ...defaultDerivedPluginMetadata, name: 'foo' }) ]); expect(game.plugins[0].name).toBe('foo'); }); test('should update existing plugins with new data', () => { game.plugins = [ new Plugin({ ...defaultDerivedPluginMetadata, name: 'foo', isActive: true, messages: [{ type: 'warn', text: '', language: 'en', condition: '' }] }) ]; game.setSortedPlugins([ new Plugin({ ...defaultDerivedPluginMetadata, name: 'foo', crc: 0xdeadbeef }) ]); expect(game.plugins[0].crc).toBe(0xdeadbeef); expect(game.plugins[0].isActive).toBe(false); }); test('should reorder plugins to given order', () => { game.plugins = [ new Plugin({ ...defaultDerivedPluginMetadata, name: 'foo' }), new Plugin({ ...defaultDerivedPluginMetadata, name: 'bar' }) ]; game.setSortedPlugins([ new Plugin({ ...defaultDerivedPluginMetadata, name: 'bar' }), new Plugin({ ...defaultDerivedPluginMetadata, name: 'foo' }) ]); expect(game.plugins[0].name).toBe('bar'); expect(game.plugins[1].name).toBe('foo'); }); test('should store old load order', () => { game.plugins = [ new Plugin({ ...defaultDerivedPluginMetadata, name: 'foo' }), new Plugin({ ...defaultDerivedPluginMetadata, name: 'bar' }) ]; game.setSortedPlugins([ new Plugin({ ...defaultDerivedPluginMetadata, name: 'bar' }), new Plugin({ ...defaultDerivedPluginMetadata, name: 'foo' }) ]); expect(game.oldLoadOrder[0].name).toBe('foo'); expect(game.oldLoadOrder[1].name).toBe('bar'); }); test('should dispatch an event', done => { handleEvent = () => { done(); }; document.addEventListener('loot-game-plugins-change', handleEvent); game.setSortedPlugins([ new Plugin({ ...defaultDerivedPluginMetadata, name: 'foo' }) ]); }); }); describe('#applySort', () => { let game: Game; beforeEach(() => { game = new Game(gameData, l10n); }); test('should delete the stored old load order', () => { game.oldLoadOrder = gameData.plugins.map(p => new Plugin(p)); game.applySort(); expect(game.oldLoadOrder).toEqual([]); }); }); describe('#cancelSort', () => { let game: Game; beforeEach(() => { game = new Game(gameData, l10n); }); test('should set the current load order to the given plugins', () => { const oldLoadOrder = [ new Plugin({ ...defaultDerivedPluginMetadata, name: 'foo' }), new Plugin({ ...defaultDerivedPluginMetadata, name: 'bar' }), new Plugin({ ...defaultDerivedPluginMetadata, name: 'baz' }) ]; game.oldLoadOrder = oldLoadOrder; game.plugins = [oldLoadOrder[2], oldLoadOrder[1], oldLoadOrder[0]]; game.cancelSort( [{ name: 'baz', loadOrderIndex: 0 }, { name: 'foo' }], [] ); expect(game.plugins).toEqual([oldLoadOrder[2], oldLoadOrder[0]]); }); test('should delete the stored old load order', () => { game.oldLoadOrder = [ new Plugin({ ...defaultDerivedPluginMetadata, name: 'foo' }), new Plugin({ ...defaultDerivedPluginMetadata, name: 'bar' }) ]; game.cancelSort([], []); expect(game.oldLoadOrder).toEqual([]); }); test('should set plugin load order indices using the array passed as the first parameter', () => { game.oldLoadOrder = [ new Plugin({ ...defaultDerivedPluginMetadata, name: 'foo', loadOrderIndex: 1 }), new Plugin({ ...defaultDerivedPluginMetadata, name: 'bar', loadOrderIndex: 0 }) ]; game.cancelSort( [ { name: 'bar', loadOrderIndex: 0 }, { name: 'foo', loadOrderIndex: 2 } ], [] ); expect(game.plugins[0].name).toBe('bar'); expect(game.plugins[0].loadOrderIndex).toBe(0); expect(game.plugins[1].name).toBe('foo'); expect(game.plugins[1].loadOrderIndex).toBe(2); }); test('should set the general messages to the second passed parameter', () => { game.oldLoadOrder = [ new Plugin({ ...defaultDerivedPluginMetadata, name: 'foo', loadOrderIndex: 1 }), new Plugin({ ...defaultDerivedPluginMetadata, name: 'bar', loadOrderIndex: 0 }) ]; const messages = [ { type: 'say', text: 'foo', language: 'en', condition: '' } ]; game.cancelSort([], messages); expect(game.generalMessages).toEqual(messages); }); }); describe('#clearMetadata', () => { let game: Game; beforeEach(() => { game = new Game(gameData, l10n); }); test('should delete stored userlist data for existing plugins', () => { game.plugins = [ new Plugin({ ...defaultDerivedPluginMetadata, name: 'foo', userlist: { name: '', after: [], req: [], inc: [], msg: [], tag: [], dirty: [], clean: [], url: [] } }) ]; game.clearMetadata([ new Plugin({ ...defaultDerivedPluginMetadata, name: 'foo' }) ]); expect(game.plugins[0].userlist).toBe(undefined); }); test('should update existing plugin data', () => { game.plugins = [ new Plugin({ ...defaultDerivedPluginMetadata, name: 'foo', isActive: true }) ]; game.clearMetadata([ new Plugin({ ...defaultDerivedPluginMetadata, name: 'foo', crc: 0xdeadbeef }) ]); expect(game.plugins[0].crc).toBe(0xdeadbeef); expect(game.plugins[0].isActive).toBe(false); }); }); });
silentdark/loot
src/tests/gui/html/js/test_game.ts
TypeScript
gpl-3.0
21,385
# == Schema Information # # Table name: causes # # id :integer not null, primary key # name :string not null # description :string # image_id :integer # created_at :datetime not null # updated_at :datetime not null # require 'rails_helper' RSpec.describe Cause, type: :model do pending "add some examples to (or delete) #{__FILE__}" end
LuizEdgar/SerVoluntarioAPI
spec/models/cause_spec.rb
Ruby
gpl-3.0
403
<?php /** * The template part for displaying single archive from hospital posts * * @package Twenty-Sixteen-Child * * */ ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <header class="entry-header"> <?php the_title( sprintf( '<h2 class="entry-title-hospital"><a href="%s" rel="bookmark">', esc_url( get_permalink() ) ), '</a></h2>' );?> </header><!-- .entry-header --> <div class="entry-content-hospital"> <?php $review_description = get_post_meta($post->ID); if(!empty($review_description['reviewer_name'][0])){ $reviewer_name = $review_description['reviewer_name'][0]; echo '<h3>'.$reviewer_name.'</h3>'; } the_post_thumbnail('thumbnail'); the_content(); echo '</br>'; echo get_the_tag_list( '<br>Tags: ', ', ','<br>' ); echo '</br>'; edit_post_link( ); ?> </div><!-- .entry-content-hospital --> </article><!-- #post-## -->
umeshramya/Twenty-Sixteen-Hospital
template-parts/content-reviews-archive.php
PHP
gpl-3.0
906
#!/usr/bin/env python # # This file is protected by Copyright. Please refer to the COPYRIGHT file # distributed with this source distribution. # # This file is part of GNUHAWK. # # GNUHAWK is free software: you can redistribute it and/or modify is under the # terms of the GNU General Public License as published by the Free Software # Foundation, either version 3 of the License, or (at your option) any later # version. # # GNUHAWK is distributed in the hope that it will be useful, but WITHOUT ANY # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR # A PARTICULAR PURPOSE. See the GNU General Public License for more details. # You should have received a copy of the GNU General Public License along with # this program. If not, see http://www.gnu.org/licenses/. # import unittest import ossie.utils.testing import os from omniORB import any class ComponentTests(ossie.utils.testing.ScaComponentTestCase): """Test for all component implementations in sig_source_i""" def testScaBasicBehavior(self): ####################################################################### # Launch the component with the default execparams execparams = self.getPropertySet(kinds=("execparam",), modes=("readwrite", "writeonly"), includeNil=False) execparams = dict([(x.id, any.from_any(x.value)) for x in execparams]) self.launch(execparams) ####################################################################### # Verify the basic state of the component self.assertNotEqual(self.comp, None) self.assertEqual(self.comp.ref._non_existent(), False) self.assertEqual(self.comp.ref._is_a("IDL:CF/Resource:1.0"), True) self.assertEqual(self.spd.get_id(), self.comp.ref._get_identifier()) ####################################################################### # Simulate regular component startup # Verify that initialize nor configure throw errors self.comp.initialize() configureProps = self.getPropertySet(kinds=("configure",), modes=("readwrite", "writeonly"), includeNil=False) self.comp.configure(configureProps) ####################################################################### # Validate that query returns all expected parameters # Query of '[]' should return the following set of properties expectedProps = [] expectedProps.extend(self.getPropertySet(kinds=("configure", "execparam"), modes=("readwrite", "readonly"), includeNil=True)) expectedProps.extend(self.getPropertySet(kinds=("allocate",), action="external", includeNil=True)) props = self.comp.query([]) props = dict((x.id, any.from_any(x.value)) for x in props) # Query may return more than expected, but not less for expectedProp in expectedProps: self.assertEquals(props.has_key(expectedProp.id), True) ####################################################################### # Verify that all expected ports are available for port in self.scd.get_componentfeatures().get_ports().get_uses(): port_obj = self.comp.getPort(str(port.get_usesname())) self.assertNotEqual(port_obj, None) self.assertEqual(port_obj._non_existent(), False) self.assertEqual(port_obj._is_a("IDL:CF/Port:1.0"), True) for port in self.scd.get_componentfeatures().get_ports().get_provides(): port_obj = self.comp.getPort(str(port.get_providesname())) self.assertNotEqual(port_obj, None) self.assertEqual(port_obj._non_existent(), False) self.assertEqual(port_obj._is_a(port.get_repid()), True) ####################################################################### # Make sure start and stop can be called without throwing exceptions self.comp.start() self.comp.stop() ####################################################################### # Simulate regular component shutdown self.comp.releaseObject() # TODO Add additional tests here # # See: # ossie.utils.bulkio.bulkio_helpers, # ossie.utils.bluefile.bluefile_helpers # for modules that will assist with testing components with BULKIO ports if __name__ == "__main__": ossie.utils.testing.main("../sig_source_i.spd.xml") # By default tests all implementations
RedhawkSDR/integration-gnuhawk
components/sig_source_i/tests/test_sig_source_i.py
Python
gpl-3.0
4,531
#include "trayicon.h" #include <QApplication> #include <QMenu> #include <QTimer> #include <conf/addressgroup.h> #include <conf/appgroup.h> #include <conf/confmanager.h> #include <conf/firewallconf.h> #include <form/controls/mainwindow.h> #include <fortsettings.h> #include <manager/hotkeymanager.h> #include <manager/windowmanager.h> #include <user/iniuser.h> #include <util/guiutil.h> #include <util/iconcache.h> #include "traycontroller.h" namespace { const char *const eventSingleClick = "singleClick"; const char *const eventDoubleClick = "doubleClick"; const char *const eventMiddleClick = "middleClick"; const char *const actionShowPrograms = "Programs"; const char *const actionShowOptions = "Options"; const char *const actionShowStatistics = "Statistics"; const char *const actionShowTrafficGraph = "TrafficGraph"; const char *const actionSwitchFilterEnabled = "FilterEnabled"; const char *const actionSwitchStopTraffic = "StopTraffic"; const char *const actionSwitchStopInetTraffic = "StopInetTraffic"; const char *const actionSwitchAutoAllowPrograms = "AutoAllowPrograms"; QString clickNameByType(TrayIcon::ClickType clickType) { switch (clickType) { case TrayIcon::SingleClick: return eventSingleClick; case TrayIcon::DoubleClick: return eventDoubleClick; case TrayIcon::MiddleClick: return eventMiddleClick; default: return QString(); } } QString actionNameByType(TrayIcon::ActionType actionType) { switch (actionType) { case TrayIcon::ActionShowPrograms: return actionShowPrograms; case TrayIcon::ActionShowOptions: return actionShowOptions; case TrayIcon::ActionShowStatistics: return actionShowStatistics; case TrayIcon::ActionShowTrafficGraph: return actionShowTrafficGraph; case TrayIcon::ActionSwitchFilterEnabled: return actionSwitchFilterEnabled; case TrayIcon::ActionSwitchStopTraffic: return actionSwitchStopTraffic; case TrayIcon::ActionSwitchStopInetTraffic: return actionSwitchStopInetTraffic; case TrayIcon::ActionSwitchAutoAllowPrograms: return actionSwitchAutoAllowPrograms; default: return QString(); } } TrayIcon::ActionType actionTypeByName(const QString &name) { if (name.isEmpty()) return TrayIcon::ActionNone; if (name == actionShowPrograms) return TrayIcon::ActionShowPrograms; if (name == actionShowOptions) return TrayIcon::ActionShowOptions; if (name == actionShowStatistics) return TrayIcon::ActionShowStatistics; if (name == actionShowTrafficGraph) return TrayIcon::ActionShowTrafficGraph; if (name == actionSwitchFilterEnabled) return TrayIcon::ActionSwitchFilterEnabled; if (name == actionSwitchStopTraffic) return TrayIcon::ActionSwitchStopTraffic; if (name == actionSwitchStopInetTraffic) return TrayIcon::ActionSwitchStopInetTraffic; if (name == actionSwitchAutoAllowPrograms) return TrayIcon::ActionSwitchAutoAllowPrograms; return TrayIcon::ActionNone; } TrayIcon::ActionType defaultActionTypeByClick(TrayIcon::ClickType clickType) { switch (clickType) { case TrayIcon::SingleClick: return TrayIcon::ActionShowPrograms; case TrayIcon::DoubleClick: return TrayIcon::ActionShowOptions; case TrayIcon::MiddleClick: return TrayIcon::ActionShowStatistics; default: return TrayIcon::ActionNone; } } void setActionCheckable(QAction *action, bool checked = false, const QObject *receiver = nullptr, const char *member = nullptr) { action->setCheckable(true); action->setChecked(checked); if (receiver) { QObject::connect(action, SIGNAL(toggled(bool)), receiver, member); } } QAction *addAction(QWidget *widget, const QIcon &icon, const QString &text, const QObject *receiver = nullptr, const char *member = nullptr, bool checkable = false, bool checked = false) { auto action = new QAction(icon, text, widget); if (receiver) { QObject::connect(action, SIGNAL(triggered(bool)), receiver, member); } if (checkable) { setActionCheckable(action, checked); } widget->addAction(action); return action; } } TrayIcon::TrayIcon(QObject *parent) : QSystemTrayIcon(parent), m_trayTriggered(false), m_ctrl(new TrayController(this)) { setupUi(); setupController(); connect(this, &QSystemTrayIcon::activated, this, &TrayIcon::onTrayActivated); } TrayIcon::~TrayIcon() { delete m_menu; } FortSettings *TrayIcon::settings() const { return ctrl()->settings(); } ConfManager *TrayIcon::confManager() const { return ctrl()->confManager(); } FirewallConf *TrayIcon::conf() const { return ctrl()->conf(); } IniOptions *TrayIcon::ini() const { return ctrl()->ini(); } IniUser *TrayIcon::iniUser() const { return ctrl()->iniUser(); } HotKeyManager *TrayIcon::hotKeyManager() const { return ctrl()->hotKeyManager(); } WindowManager *TrayIcon::windowManager() const { return ctrl()->windowManager(); } void TrayIcon::onMouseClicked(TrayIcon::ClickType clickType) { QAction *action = m_clickActions[clickType]; if (action) { action->trigger(); } } void TrayIcon::onTrayActivated(QSystemTrayIcon::ActivationReason reason) { switch (reason) { case QSystemTrayIcon::Trigger: m_trayTriggered = true; QTimer::singleShot(QApplication::doubleClickInterval(), this, [&] { if (m_trayTriggered) { m_trayTriggered = false; onMouseClicked(SingleClick); } }); break; case QSystemTrayIcon::DoubleClick: if (m_trayTriggered) { m_trayTriggered = false; onMouseClicked(DoubleClick); } break; case QSystemTrayIcon::MiddleClick: m_trayTriggered = false; onMouseClicked(MiddleClick); break; case QSystemTrayIcon::Context: m_trayTriggered = false; showTrayMenu(QCursor::pos()); break; default: break; } } void TrayIcon::updateTrayIcon(bool alerted) { const auto icon = alerted ? GuiUtil::overlayIcon(":/icons/sheild-96.png", ":/icons/error.png") : IconCache::icon(":/icons/sheild-96.png"); this->setIcon(icon); } void TrayIcon::showTrayMenu(const QPoint &pos) { m_menu->popup(pos); } void TrayIcon::updateTrayMenu(bool onlyFlags) { if (!onlyFlags) { updateAppGroupActions(); } updateTrayMenuFlags(); updateHotKeys(); } void TrayIcon::setupController() { connect(windowManager(), &WindowManager::optWindowChanged, this, &TrayIcon::updateTrayMenuFlags); connect(windowManager(), &WindowManager::graphWindowChanged, m_graphAction, &QAction::setChecked); connect(settings(), &FortSettings::passwordCheckedChanged, this, &TrayIcon::updateTrayMenuFlags); connect(ctrl(), &TrayController::retranslateUi, this, &TrayIcon::retranslateUi); retranslateUi(); } void TrayIcon::retranslateUi() { m_programsAction->setText(tr("Programs")); m_optionsAction->setText(tr("Options")); m_statisticsAction->setText(tr("Statistics")); m_zonesAction->setText(tr("Zones")); m_graphAction->setText(tr("Traffic Graph")); m_filterEnabledAction->setText(tr("Filter Enabled")); m_stopTrafficAction->setText(tr("Stop Traffic")); m_stopInetTrafficAction->setText(tr("Stop Internet Traffic")); m_autoAllowProgsAction->setText(tr("Auto-Allow New Programs")); m_quitAction->setText(tr("Quit")); } void TrayIcon::setupUi() { this->setToolTip(QApplication::applicationDisplayName()); setupTrayMenu(); updateTrayMenu(); updateTrayIcon(); updateClickActions(); } void TrayIcon::setupTrayMenu() { m_menu = new QMenu(); m_programsAction = addAction(m_menu, IconCache::icon(":/icons/application.png"), QString(), windowManager(), SLOT(showProgramsWindow())); addHotKey(m_programsAction, iniUser()->hotKeyPrograms()); m_optionsAction = addAction(m_menu, IconCache::icon(":/icons/cog.png"), QString(), windowManager(), SLOT(showOptionsWindow())); addHotKey(m_optionsAction, iniUser()->hotKeyOptions()); m_statisticsAction = addAction(m_menu, IconCache::icon(":/icons/chart_bar.png"), QString(), windowManager(), SLOT(showStatisticsWindow())); addHotKey(m_statisticsAction, iniUser()->hotKeyStatistics()); m_graphAction = addAction(m_menu, IconCache::icon(":/icons/action_log.png"), QString(), windowManager(), SLOT(switchGraphWindow()), true, !!windowManager()->graphWindow()); addHotKey(m_graphAction, iniUser()->hotKeyGraph()); m_zonesAction = addAction(m_menu, IconCache::icon(":/icons/ip_class.png"), QString(), windowManager(), SLOT(showZonesWindow())); addHotKey(m_zonesAction, iniUser()->hotKeyZones()); m_menu->addSeparator(); m_filterEnabledAction = addAction(m_menu, QIcon(), QString(), this, SLOT(switchTrayFlag(bool)), true); addHotKey(m_filterEnabledAction, iniUser()->hotKeyFilter()); m_stopTrafficAction = addAction(m_menu, QIcon(), QString(), this, SLOT(switchTrayFlag(bool)), true); addHotKey(m_stopTrafficAction, iniUser()->hotKeyStopTraffic()); m_stopInetTrafficAction = addAction(m_menu, QIcon(), QString(), this, SLOT(switchTrayFlag(bool)), true); addHotKey(m_stopInetTrafficAction, iniUser()->hotKeyStopInetTraffic()); m_autoAllowProgsAction = addAction(m_menu, QIcon(), QString(), this, SLOT(switchTrayFlag(bool)), true); addHotKey(m_autoAllowProgsAction, iniUser()->hotKeyAllowAllNew()); m_menu->addSeparator(); for (int i = 0; i < MAX_APP_GROUP_COUNT; ++i) { QAction *a = addAction(m_menu, QIcon(), QString(), this, SLOT(switchTrayFlag(bool)), true); if (i < 12) { const QString shortcutText = iniUser()->hotKeyAppGroupModifiers() + "+F" + QString::number(i + 1); addHotKey(a, shortcutText); } m_appGroupActions.append(a); } m_menu->addSeparator(); m_quitAction = addAction(m_menu, QIcon(), tr("Quit"), this, SLOT(quitProgram())); addHotKey(m_quitAction, iniUser()->hotKeyQuit()); } void TrayIcon::updateTrayMenuFlags() { const bool editEnabled = (!settings()->isPasswordRequired() && !windowManager()->optWindow()); m_filterEnabledAction->setEnabled(editEnabled); m_stopTrafficAction->setEnabled(editEnabled); m_stopInetTrafficAction->setEnabled(editEnabled); m_autoAllowProgsAction->setEnabled(editEnabled); m_filterEnabledAction->setChecked(conf()->filterEnabled()); m_stopTrafficAction->setChecked(conf()->stopTraffic()); m_stopInetTrafficAction->setChecked(conf()->stopInetTraffic()); m_autoAllowProgsAction->setChecked(conf()->allowAllNew()); int appGroupIndex = 0; for (QAction *action : qAsConst(m_appGroupActions)) { if (!action->isVisible()) break; const bool appGroupEnabled = conf()->appGroupEnabled(appGroupIndex++); action->setEnabled(editEnabled); action->setChecked(appGroupEnabled); } } void TrayIcon::updateAppGroupActions() { const int appGroupsCount = conf()->appGroups().count(); for (int i = 0; i < MAX_APP_GROUP_COUNT; ++i) { QAction *action = m_appGroupActions.at(i); QString menuLabel; bool visible = false; if (i < appGroupsCount) { const AppGroup *appGroup = conf()->appGroups().at(i); menuLabel = appGroup->menuLabel(); visible = true; } action->setText(menuLabel); action->setVisible(visible); action->setEnabled(visible); } } void TrayIcon::saveTrayFlags() { conf()->setFilterEnabled(m_filterEnabledAction->isChecked()); conf()->setStopTraffic(m_stopTrafficAction->isChecked()); conf()->setStopInetTraffic(m_stopInetTrafficAction->isChecked()); conf()->setAllowAllNew(m_autoAllowProgsAction->isChecked()); int i = 0; for (AppGroup *appGroup : conf()->appGroups()) { const QAction *action = m_appGroupActions.at(i++); appGroup->setEnabled(action->isChecked()); } confManager()->saveFlags(); } void TrayIcon::switchTrayFlag(bool checked) { if (iniUser()->confirmTrayFlags()) { const auto action = qobject_cast<QAction *>(sender()); Q_ASSERT(action); if (!windowManager()->showQuestionBox( tr("Are you sure to switch the \"%1\"?").arg(action->text()))) { action->setChecked(!checked); return; } } saveTrayFlags(); } void TrayIcon::quitProgram() { if (iniUser()->confirmQuit()) { if (!windowManager()->showQuestionBox(tr("Are you sure you want to quit the program?"))) return; } windowManager()->quitByCheckPassword(); } void TrayIcon::addHotKey(QAction *action, const QString &shortcutText) { if (shortcutText.isEmpty()) return; const QKeySequence shortcut = QKeySequence::fromString(shortcutText); hotKeyManager()->addAction(action, shortcut); } void TrayIcon::updateHotKeys() { hotKeyManager()->setEnabled(iniUser()->hotKeyEnabled()); } void TrayIcon::removeHotKeys() { hotKeyManager()->removeActions(); } TrayIcon::ActionType TrayIcon::clickEventActionType(ClickType clickType) const { const QString eventName = clickNameByType(clickType); const QString actionName = iniUser()->trayAction(eventName); const ActionType actionType = actionTypeByName(actionName); return (actionType != ActionNone) ? actionType : defaultActionTypeByClick(clickType); } void TrayIcon::setClickEventActionType(ClickType clickType, ActionType actionType) { const QString eventName = clickNameByType(clickType); const QString actionName = actionNameByType(actionType); iniUser()->setTrayAction(eventName, actionName); updateClickActions(); } void TrayIcon::updateClickActions() { m_clickActions[SingleClick] = clickActionFromIni(SingleClick); m_clickActions[DoubleClick] = clickActionFromIni(DoubleClick); m_clickActions[MiddleClick] = clickActionFromIni(MiddleClick); } QAction *TrayIcon::clickActionFromIni(ClickType clickType) const { const ActionType actionType = clickEventActionType(clickType); return clickActionByType(actionType); } QAction *TrayIcon::clickActionByType(ActionType actionType) const { switch (actionType) { case TrayIcon::ActionShowPrograms: return m_programsAction; case TrayIcon::ActionShowOptions: return m_optionsAction; case TrayIcon::ActionShowStatistics: return m_statisticsAction; case TrayIcon::ActionShowTrafficGraph: return m_graphAction; case TrayIcon::ActionSwitchFilterEnabled: return m_filterEnabledAction; case TrayIcon::ActionSwitchStopTraffic: return m_stopTrafficAction; case TrayIcon::ActionSwitchStopInetTraffic: return m_stopInetTrafficAction; case TrayIcon::ActionSwitchAutoAllowPrograms: return m_autoAllowProgsAction; } return nullptr; }
tnodir/fort
src/ui/form/tray/trayicon.cpp
C++
gpl-3.0
15,320
package at.ltd.tools.fw.peer2peerFirewall.backend.entities.comparator; @FunctionalInterface public interface ComparatorLambda<T> { int comp(T t1, T t2); }
a-frankdank/peer2peerFirewall
peer2peerFirewall-pom/peer2peerFirewall-backend-poc/src/main/java/at/ltd/tools/fw/peer2peerFirewall/backend/entities/comparator/ComparatorLambda.java
Java
gpl-3.0
163
// Obdi - a REST interface and GUI for deploying software // Copyright (C) 2014 Mark Clarkson // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. package main import ( "encoding/json" "fmt" "net" "net/rpc" "os" ) type PostedData struct { Hostname string } // *************************************************************************** // GO RPC PLUGIN // *************************************************************************** func (t *Plugin) GetRequest(args *Args, response *[]byte) error { // List all keys if len(args.QueryString["env_id"]) == 0 { ReturnError("'env_id' must be set", response) return nil } sa := ScriptArgs{ ScriptName: "saltkey-showkeys.sh", CmdArgs: "", EnvVars: "", EnvCapDesc: "SALT_WORKER", Type: 2, } var jobid int64 var err error if jobid, err = t.RunScript(args, sa, response); err != nil { // RunScript wrote the error return nil } reply := Reply{jobid, "", SUCCESS, ""} jsondata, err := json.Marshal(reply) if err != nil { ReturnError("Marshal error: "+err.Error(), response) return nil } *response = jsondata return nil } func (t *Plugin) PostRequest(args *Args, response *[]byte) error { // Check for required query string entries if len(args.QueryString["hostname"]) == 0 { ReturnError("'type' must be set", response) return nil } if len(args.QueryString["type"]) == 0 { ReturnError("'type' must be set", response) return nil } if len(args.QueryString["env_id"]) == 0 { ReturnError("'env_id' must be set", response) return nil } // Get the ScriptId from the scripts table for: scriptName := "" if args.QueryString["type"][0] == "accept" { scriptName = "saltkey-acceptkeys.sh" } else { scriptName = "saltkey-rejectkeys.sh" } var jobid int64 sa := ScriptArgs{ ScriptName: scriptName, CmdArgs: args.QueryString["hostname"][0], EnvVars: "", EnvCapDesc: "SALT_WORKER", Type: 2, } var err error if jobid, err = t.RunScript(args, sa, response); err != nil { // RunScript wrote the error return nil } reply := Reply{jobid, "", SUCCESS, ""} jsondata, err := json.Marshal(reply) if err != nil { ReturnError("Marshal error: "+err.Error(), response) return nil } *response = jsondata return nil } func (t *Plugin) DeleteRequest(args *Args, response *[]byte) error { // Check for required query string entries if len(args.QueryString["env_id"]) == 0 { ReturnError("'env_id' must be set", response) return nil } var jobid int64 sa := ScriptArgs{ ScriptName: "saltkey-deletekeys.sh", CmdArgs: args.PathParams["id"], EnvVars: "", EnvCapDesc: "SALT_WORKER", Type: 2, } var err error if jobid, err = t.RunScript(args, sa, response); err != nil { // RunScript wrote the error return nil } reply := Reply{jobid, "", SUCCESS, ""} jsondata, err := json.Marshal(reply) if err != nil { ReturnError("Marshal error: "+err.Error(), response) return nil } *response = jsondata return nil } func (t *Plugin) HandleRequest(args *Args, response *[]byte) error { // All plugins must have this. if len(args.QueryType) > 0 { switch args.QueryType { case "GET": t.GetRequest(args, response) return nil case "POST": t.PostRequest(args, response) return nil case "DELETE": t.DeleteRequest(args, response) return nil } ReturnError("Internal error: Invalid HTTP request type for this plugin "+ args.QueryType, response) return nil } else { ReturnError("Internal error: HTTP request type was not set", response) return nil } } func main() { //logit("Plugin starting") plugin := new(Plugin) rpc.Register(plugin) listener, err := net.Listen("tcp", ":"+os.Args[1]) if err != nil { txt := fmt.Sprintf("Listen error. ", err) logit(txt) } //logit("Plugin listening on port " + os.Args[1]) if conn, err := listener.Accept(); err != nil { txt := fmt.Sprintf("Accept error. ", err) logit(txt) } else { //logit("New connection established") rpc.ServeConn(conn) } }
mclarkson/obdi-saltkeymanager
go/saltkeys.go
GO
gpl-3.0
4,629