code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
package com.projectreddog.machinemod.container; import com.projectreddog.machinemod.inventory.SlotBlazePowder; import com.projectreddog.machinemod.inventory.SlotNotBlazePowder; import com.projectreddog.machinemod.inventory.SlotOutputOnlyTurobFurnace; import com.projectreddog.machinemod.tileentities.TileEntityTurboFurnace; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.Container; import net.minecraft.inventory.IContainerListener; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; ; public class ContainerTurboFurnace extends Container { protected TileEntityTurboFurnace turbofurnace; protected int lastFuleBurnTimeRemaining = 0; protected int lastProcessingTimeRemaining = 0; public ContainerTurboFurnace(InventoryPlayer inventoryPlayer, TileEntityTurboFurnace turbofurnace) { this.turbofurnace = turbofurnace; lastFuleBurnTimeRemaining = -1; lastProcessingTimeRemaining = -1; // for (int i = 0; i < 1; i++) { // for (int j = 0; j < 3; j++) { addSlotToContainer(new SlotNotBlazePowder(turbofurnace, 0, 47, 34)); addSlotToContainer(new SlotOutputOnlyTurobFurnace(inventoryPlayer.player, turbofurnace, 1, 110, 53)); addSlotToContainer(new SlotBlazePowder(turbofurnace, 2, 47, 74)); // } // } // commonly used vanilla code that adds the player's inventory bindPlayerInventory(inventoryPlayer); } @Override public boolean canInteractWith(EntityPlayer player) { return turbofurnace.isUsableByPlayer(player); } protected void bindPlayerInventory(InventoryPlayer inventoryPlayer) { for (int i = 0; i < 3; i++) { for (int j = 0; j < 9; j++) { addSlotToContainer(new Slot(inventoryPlayer, j + i * 9 + 9, 8 + j * 18, 139 + i * 18)); } } for (int i = 0; i < 9; i++) { addSlotToContainer(new Slot(inventoryPlayer, i, 8 + i * 18, 197)); } } @Override public ItemStack transferStackInSlot(EntityPlayer player, int slot) { ItemStack stack = ItemStack.EMPTY; Slot slotObject = (Slot) inventorySlots.get(slot); // null checks and checks if the item can be stacked (maxStackSize > 1) if (slotObject != null && slotObject.getHasStack()) { ItemStack stackInSlot = slotObject.getStack(); stack = stackInSlot.copy(); // merges the item into player inventory since its in the Entity if (slot < 3) { if (!this.mergeItemStack(stackInSlot, 3, this.inventorySlots.size(), true)) { return ItemStack.EMPTY; } slotObject.onSlotChange(stackInSlot, stack); } // places it into the tileEntity is possible since its in the player // inventory else if (!this.mergeItemStack(stackInSlot, 0, 3, false)) { return ItemStack.EMPTY; } if (stackInSlot.getCount() == 0) { slotObject.putStack(ItemStack.EMPTY); } else { slotObject.onSlotChanged(); } if (stackInSlot.getCount() == stack.getCount()) { return ItemStack.EMPTY; } slotObject.onTake(player, stackInSlot); } return stack; } /** * Looks for changes made in the container, sends them to every listener. */ public void detectAndSendChanges() { super.detectAndSendChanges(); for (int i = 0; i < this.listeners.size(); ++i) { IContainerListener icrafting = (IContainerListener) this.listeners.get(i); if (this.lastFuleBurnTimeRemaining != this.turbofurnace.getField(0)) { icrafting.sendWindowProperty(this, 0, this.turbofurnace.getField(0)); } if (this.lastProcessingTimeRemaining != this.turbofurnace.getField(1)) { icrafting.sendWindowProperty(this, 1, this.turbofurnace.getField(1)); } } this.lastFuleBurnTimeRemaining = this.turbofurnace.getField(0); this.lastProcessingTimeRemaining = this.turbofurnace.getField(1); } @SideOnly(Side.CLIENT) public void updateProgressBar(int id, int data) { this.turbofurnace.setField(id, data); } }
TechStack/TechStack-s-HeavyMachineryMod
src/main/java/com/projectreddog/machinemod/container/ContainerTurboFurnace.java
Java
gpl-3.0
3,980
<div class="panel panel-default bio"> <div class="panel-body tight-inner"> <table class="table table-responsive table-ac-bordered table-hover"> <thead> <tr> <th data-bind="click: function(){sortBy('name');}" class="col-md-7"> Feature <span data-bind="css: sortArrow('name')"></span> </th> <th data-bind="click: function(){sortBy('characterClass');}" class="col-md-4"> Class <span data-bind="css: sortArrow('characterClass')"></span> </th> <th class="col-md-1"> <a data-toggle="modal" data-target="#addFeature" href="#"> <i class="fa fa-plus fa-color"></i> </a> </th> </tr> </thead> <tbody> <!-- ko foreach: filteredAndSortedFeatures --> <tr class="clickable"> <td data-bind="text: name, click: $parent.editFeature" href="#"></td> <td data-bind="text: characterClass, click: $parent.editFeature" href="#"></td> <td class="col-content-vertical"> <a data-bind="click: $parent.removeFeature" href="#"> <i class="fa fa-trash-o fa-color-hover"> </i> </a> </td> </tr> <!-- /ko --> <!-- ko if: filteredAndSortedFeatures().length == 0 --> <tr class="clickable"> <td data-toggle="modal" data-target="#addFeature" href="#" colspan="12" class="text-center"> <i class="fa fa-plus fa-color"></i> Add a new Feature </td> </tr> <!-- /ko --> </tbody> </table> </div> </div> <!-- Add Modal --> <div class="modal fade" id="addFeature" tabindex="-1" role="dialog" data-bind="modal: { onopen: modalFinishedOpening, onclose: modalFinishedClosing}"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <h4 class="modal-title" id="addFeatureLabel">Add a new Feature.</h4> </div> <div class="modal-body"> <form class="form-horizontal"> <div class="form-group"> <label for="name" class="col-sm-2 control-label">Name</label> <div class="col-sm-10"> <input type="text" class="form-control" id="featureName" placeholder="Rage" data-bind='textInput: blankFeature().name, autocomplete: { source: featuresPrePopFilter, onselect: populateFeature }, hasFocus: firstModalElementHasFocus'> </div> </div> <div class="form-group"> <label for="class" class="col-sm-2 control-label">Class</label> <div class="col-sm-10"> <input type="text" class="form-control" id="class" placeholder="Barbarian" data-bind='textInput: blankFeature().characterClass, autocomplete: { source: classOptions, onselect: populateClass }'> </div> </div> <div class="form-group"> <label for="level" class="col-sm-2 control-label">Level</label> <div class="col-sm-10"> <input type="number" class="form-control" id="class" placeholder="1" data-bind='textInput: blankFeature().level'> </div> </div> <div class="form-group"> <label for="featureDescription" class="col-sm-2 control-label">Description</label> <div class="col-sm-10"> <textarea type="password" class="form-control" id="featureDescription" rows="4" placeholder="While you are not wearing any armor, your Armor Class..." data-bind='textInput: blankFeature().description'> </textarea> </div> </div> <div class="form-group"> <label for="featureDescription" class="col-sm-3 control-label content-left"> <span class="fa fa-info-circle" style="cursor:pointer;" data-bind="popover: { content: trackedPopoverText }"></span>&nbsp;Tracked?</label> <div class="col-sm-7"> <input type="checkbox" class="form-control" id="tracked" data-bind='checked: blankFeature().isTracked'> </div> </div> <div data-bind="visible: blankFeature().isTracked"> <div class="form-group"> <div class="col-sm-1 col-content-vertical" style="border-right:5px ridge #dce4ec;height:40px"> </div> <label for="bonus" class="col-sm-2 control-label">Max</label> <div class="col-sm-9"> <input type="number" class="form-control" id="max" min="1" data-bind='textInput: blankTracked().maxUses'> </div> </div> <div class="form-group"> <div class="col-sm-1 col-content-vertical" style="border-right:5px ridge #dce4ec;height:50px"> </div> <label class="col-sm-2 control-label">Resets on...</label> <div class="col-sm-9"> <div class="btn-group btn-group-justified" role="group"> <label class="btn btn-default" data-bind="css: { active: blankTracked().resetsOn() == 'short'}"> <input type="radio" class="hide-block" name="blankresetsOnShort" value="short" data-bind="checked: blankTracked().resetsOn"/> <img class="action-bar-icon" data-bind="attr: { src: meditation }"></img> &nbsp;&nbsp;&nbsp;Short Rest </label> <label class="btn btn-default" data-bind="css: { active: blankTracked().resetsOn() == 'long'}"> <input type="radio" class="hide-block" name="blankresetsOnLong" value="long" data-bind="checked: blankTracked().resetsOn"/> <img class="action-bar-icon" data-bind="attr: { src: campingTent }"></img> &nbsp;&nbsp;&nbsp;Long Rest </label> </div> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-primary" data-bind='click: addFeature' data-dismiss="modal">Add</button> <p class="text-muted text-left" data-bind='visible: shouldShowDisclaimer'> <sm><i>This data is distributed under the <a href='http://media.wizards.com/2016/downloads/DND/SRD-OGL_V5.1.pdf' target='_blank'> OGL</a><br/> Open Game License v 1.0a Copyright 2000, Wizards of the Coast, LLC. </i><sm> </p> </div> </form> </div> <!-- Modal Body --> </div> <!-- Modal Content --> </div> <!-- Modal Dialog --> </div> <!-- Modal Fade --> <!-- ViewEdit Modal --> <div class="modal fade" id="viewWeapon" tabindex="-1" role="dialog" data-bind="modal: { open: modalOpen, onopen: modalFinishedOpening, onclose: modalFinishedClosing }"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <h4 class="modal-title">Edit a Feature.</h4> </div> <div class="modal-body"> <!-- Begin Tabs --> <ul class="nav nav-tabs tabs"> <li role="presentation" data-bind="click: selectPreviewTab, css: previewTabStatus"> <a href="#" aria-controls="featureModalPreview" role="tab" data-toggle="tab"> <b>Preview</b> </a> </li> <li role="presentation" data-bind="click: selectEditTab, css: editTabStatus"> <a href="#" aria-controls="featureModalEdit" role="tab" data-toggle="tab"> <b>Edit</b> </a> </li> </ul> <div class="tab-content" data-bind="with: currentEditItem"> <div role="tabpanel" data-bind="css: $parent.previewTabStatus" class="tab-pane"> <div class="h3"> <span data-bind="text: name"></span> </div> <div class="row"> <div class="col-sm-6 col-xs-12"><b>Class: </b>&nbsp; <span data-bind="text: characterClass"></span> </div> <div class="col-sm-6 col-xs-12"><b>Level: </b>&nbsp; <span data-bind="text: level"></span> </div> </div> <!-- ko if: isTracked --> <div class="row" > <div class="col-sm-6 col-xs-12"> <b>Max Uses:</b>&nbsp; <span data-bind="text: $parent.currentEditTracked().maxUses"></span> </div> <div class="col-sm-6 col-xs-12"> <b>Resets on:</b>&nbsp; <span data-bind="visible: $parent.currentEditTracked().resetsOn() === 'short'"> Short Rest </span> <span data-bind="visible: $parent.currentEditTracked().resetsOn() === 'long'"> Long Rest </span> </div> </div> <!-- /ko --> <hr /> <div class="row row-padded"> <div class="col-xs-12 col-padded"> <div data-bind="markdownPreview: description" class="preview-modal-overflow-sm"> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-primary" data-dismiss="modal">Done</button> </div> </div> <!-- End Preview Tab --> <div role="tabpanel" data-bind="css: $parent.editTabStatus" class="tab-pane"> <form class="form-horizontal"> <div class="form-group"> <label for="name" class="col-sm-2 control-label">Name</label> <div class="col-sm-10"> <input type="text" class="form-control" id="featureName" placeholder="Rage" data-bind='textInput: name, hasFocus: $parent.editFirstModalElementHasFocus'> </div> </div> <div class="form-group"> <label for="class" class="col-sm-2 control-label">Class</label> <div class="col-sm-10"> <input type="text" class="form-control" id="class" placeholder="Barbarian" data-bind='textInput: characterClass, autocomplete: { source: $parent.classOptions, onselect: $parent.populateClassEdit }'> </div> </div> <div class="form-group"> <label for="level" class="col-sm-2 control-label">Level</label> <div class="col-sm-10"> <input type="number" class="form-control" id="class" placeholder="1" data-bind='textInput: level'> </div> </div> <div class="form-group"> <label for="featureDescription" class="col-sm-2 control-label">Description</label> <div class="col-sm-10"> <textarea type="text" rows="6" class="form-control" placeholder="While you are not wearing any armor, your Armor Class..." data-bind='value: description, markdownEditor: true'></textarea> </div> </div> <div class="form-group"> <label for="featureDescription" class="col-sm-2 control-label">Tracked?</label> <div class="col-sm-10"> <input type="checkbox" class="form-control" id="tracked" data-bind='checked: isTracked'> </div> </div> <!-- ko if: isTracked --> <div class="form-group"> <div class="col-sm-1 col-content-vertical" style="border-right:5px ridge #dce4ec;height:40px"> </div> <label for="bonus" class="col-sm-2 control-label">Max</label> <div class="col-sm-9"> <input type="number" class="form-control" id="max" min="1" data-bind='textInput: $parent.currentEditTracked().maxUses'> </div> </div> <div class="form-group"> <div class="col-sm-1 col-content-vertical" style="border-right:5px ridge #dce4ec;height:50px"> </div> <label class="col-sm-2 control-label">Resets on...</label> <div class="col-sm-9"> <div class="btn-group btn-group-justified" role="group"> <label class="btn btn-default" data-bind="css: { active: $parent.currentEditTracked().resetsOn() == 'short'}"> <input type="radio" class="hide-block" name="blankresetsOnShort" value="short" data-bind="checked: $parent.currentEditTracked().resetsOn"/> <img class="action-bar-icon" data-bind="attr: { src: $parent.meditation }"></img> &nbsp;&nbsp;&nbsp;Short Rest </label> <label class="btn btn-default" data-bind="css: { active: $parent.currentEditTracked().resetsOn() != 'short'}"> <input type="radio" class="hide-block" name="blankresetsOnLong" value="long" data-bind="checked: $parent.currentEditTracked().resetsOn"/> <img class="action-bar-icon" data-bind="attr: { src: $parent.campingTent }"></img> &nbsp;&nbsp;&nbsp;Long Rest </label> </div> </div> </div> <!-- /ko --> <div class="modal-footer"> <button type="button" class="btn btn-primary" data-dismiss="modal">Done</button> </div> </form> </div> </div> </div> <!-- Modal Body --> </div> <!-- Modal Content --> </div> <!-- Modal Dialog --> </div> <!-- Modal Fade -->
Sonictherocketman/charactersheet
src/charactersheet/viewmodels/character/features/index.html
HTML
gpl-3.0
15,832
/** Copyright (c) 2014-2015 "M-Way Solutions GmbH" FruityMesh - Bluetooth Low Energy mesh protocol [http://mwaysolutions.com/] This file is part of FruityMesh FruityMesh 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 <adv_packets.h> #include <AdvertisingController.h> #include <AdvertisingModule.h> #include <Logger.h> #include <Utility.h> #include <Storage.h> extern "C"{ #include <app_error.h> } //This module allows a number of advertising messages to be configured. //These will be broadcasted periodically /* TODO: Who's responsible for restoring the mesh-advertising packet? This module or the Node? * */ AdvertisingModule::AdvertisingModule(u8 moduleId, Node* node, ConnectionManager* cm, const char* name, u16 storageSlot) : Module(moduleId, node, cm, name, storageSlot) { //Register callbacks n' stuff //Save configuration to base class variables //sizeof configuration must be a multiple of 4 bytes configurationPointer = &configuration; configurationLength = sizeof(AdvertisingModuleConfiguration); //Start module configuration loading LoadModuleConfiguration(); } void AdvertisingModule::ConfigurationLoadedHandler() { //Does basic testing on the loaded configuration Module::ConfigurationLoadedHandler(); //Version migration can be added here if(configuration.moduleVersion == 1){/* ... */}; //Do additional initialization upon loading the config //Start the Module... logt("ADVMOD", "Config set"); } void AdvertisingModule::TimerEventHandler(u16 passedTime, u32 appTimer) { //Do stuff on timer... } void AdvertisingModule::ResetToDefaultConfiguration() { //Set default configuration values configuration.moduleId = moduleId; configuration.moduleActive = true; configuration.moduleVersion = 1; memset(configuration.messageData[0].messageData, 0, 31); advStructureFlags flags; advStructureName name; flags.len = SIZEOF_ADV_STRUCTURE_FLAGS-1; flags.type = BLE_GAP_AD_TYPE_FLAGS; flags.flags = BLE_GAP_ADV_FLAG_LE_GENERAL_DISC_MODE | BLE_GAP_ADV_FLAG_BR_EDR_NOT_SUPPORTED; name.len = SIZEOF_ADV_STRUCTURE_NAME-1; name.type = BLE_GAP_AD_TYPE_COMPLETE_LOCAL_NAME; name.name[0] = 'A'; name.name[1] = 'B'; configuration.advertisingIntervalMs = 100; configuration.messageCount = 1; configuration.messageData[0].messageLength = 31; memcpy(configuration.messageData[0].messageData, &flags, SIZEOF_ADV_STRUCTURE_FLAGS); memcpy(configuration.messageData[0].messageData+SIZEOF_ADV_STRUCTURE_FLAGS, &name, SIZEOF_ADV_STRUCTURE_NAME); } void AdvertisingModule::NodeStateChangedHandler(discoveryState newState) { if(newState == discoveryState::BACK_OFF || newState == discoveryState::DISCOVERY_OFF){ //Activate our advertising //This is a small packet for debugging a node's state if(Config->advertiseDebugPackets){ u8 buffer[31]; memset(buffer, 0, 31); advStructureFlags* flags = (advStructureFlags*)buffer; flags->len = SIZEOF_ADV_STRUCTURE_FLAGS-1; flags->type = BLE_GAP_AD_TYPE_FLAGS; flags->flags = BLE_GAP_ADV_FLAG_LE_GENERAL_DISC_MODE | BLE_GAP_ADV_FLAG_BR_EDR_NOT_SUPPORTED; advStructureManufacturer* manufacturer = (advStructureManufacturer*)(buffer+3); manufacturer->len = 26; manufacturer->type = BLE_GAP_AD_TYPE_MANUFACTURER_SPECIFIC_DATA; manufacturer->companyIdentifier = 0x24D; AdvertisingModuleDebugMessage* msg = (AdvertisingModuleDebugMessage*)(buffer+7); msg->debugPacketIdentifier = 0xDE; msg->senderId = node->persistentConfig.nodeId; msg->connLossCounter = node->persistentConfig.connectionLossCounter; for(int i=0; i<Config->meshMaxConnections; i++){ if(cm->connections[i]->handshakeDone()){ msg->partners[i] = cm->connections[i]->partnerId; msg->rssiVals[i] = cm->connections[i]->rssiAverage; msg->droppedVals[i] = cm->connections[i]->droppedPackets; } else { msg->partners[i] = 0; msg->rssiVals[i] = 0; msg->droppedVals[i] = 0; } } char strbuffer[200]; Logger::getInstance().convertBufferToHexString(buffer, 31, strbuffer, 200); logt("ADVMOD", "ADV set to %s", strbuffer); u32 err = sd_ble_gap_adv_data_set(buffer, 31, NULL, 0); if(err != NRF_SUCCESS){ logt("ADVMOD", "Debug Packet corrupt"); } AdvertisingController::SetAdvertisingState(advState::ADV_STATE_HIGH); } else if(configuration.messageCount > 0){ u32 err = sd_ble_gap_adv_data_set(configuration.messageData[0].messageData, configuration.messageData[0].messageLength, NULL, 0); if(err != NRF_SUCCESS){ logt("ADVMOD", "Adv msg corrupt"); } char buffer[200]; Logger::getInstance().convertBufferToHexString((u8*)configuration.messageData[0].messageData, 31, buffer, 200); logt("ADVMOD", "ADV set to %s", buffer); if(configuration.messageData[0].forceNonConnectable) { AdvertisingController::SetNonConnectable(); } //Now, start advertising //TODO: Use advertising parameters from config to advertise AdvertisingController::SetAdvertisingState(advState::ADV_STATE_HIGH); } } else if (newState == discoveryState::DISCOVERY) { //Do not trigger custom advertisings anymore, reset to node's advertising node->UpdateJoinMePacket(); } } bool AdvertisingModule::TerminalCommandHandler(string commandName, vector<string> commandArgs) { if(commandArgs.size() >= 2 && commandArgs[1] == moduleName) { if(commandName == "action") { if(commandArgs[1] != moduleName) return false; if(commandArgs[2] == "broadcast_debug") { Config->advertiseDebugPackets = !Config->advertiseDebugPackets; logt("ADVMOD", "Debug Packets are now set to %u", Config->advertiseDebugPackets); return true; } } } //Must be called to allow the module to get and set the config return Module::TerminalCommandHandler(commandName, commandArgs); }
Informatic/fruitymesh
src/modules/AdvertisingModule.cpp
C++
gpl-3.0
6,350
/* * Copyright (C) 2004 NNL Technology AB * Visit www.infonode.net for information about InfoNode(R) * products and how to contact NNL Technology AB. * * 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, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, * MA 02111-1307, USA. */ // $Id: Info.java,v 1.6 2004/09/22 14:31:39 jesper Exp $ package com.supermap.desktop.ui.docking.info; import com.supermap.desktop.ui.docking.DockingWindowsReleaseInfo; import net.infonode.gui.ReleaseInfoDialog; import net.infonode.gui.laf.InfoNodeLookAndFeelReleaseInfo; import net.infonode.tabbedpanel.TabbedPanelReleaseInfo; import net.infonode.util.ReleaseInfo; /** * Program that shows InfoNode Docking Windows release information in a dialog. * * @author $Author: jesper $ * @version $Revision: 1.6 $ */ public class Info { private Info() { } public static final void main(String[] args) { ReleaseInfoDialog.showDialog(new ReleaseInfo[]{DockingWindowsReleaseInfo.getReleaseInfo(), TabbedPanelReleaseInfo.getReleaseInfo(), InfoNodeLookAndFeelReleaseInfo.getReleaseInfo()}, null); System.exit(0); } }
highsad/iDesktop-Cross
Controls/src/com/supermap/desktop/ui/docking/info/Info.java
Java
gpl-3.0
1,846
<?php /** * @package Joomla.Plugin * @subpackage Content.Jtf * * @author Guido De Gobbis <[email protected]> * @copyright (c) 2017 JoomTools.de - All rights reserved. * @license GNU General Public License version 3 or later */ defined('_JEXEC') or die; extract($displayData); /** * Make thing clear * * @var JForm $form The form instance for render the section * @var string $basegroup The base group name * @var string $group Current group name * @var string $unique_subform_id Unique subform id * @var array $buttons Array of the buttons that will be rendered */ $subformClass = !empty($form->getAttribute('class')) ? ' ' . $form->getAttribute('class') : ' uk-width-1-1 uk-width-1-2@s uk-width-1-4@m'; ?> <div class="subform-repeatable-group uk-margin-large-bottom<?php echo $subformClass; ?> subform-repeatable-group-<?php echo $unique_subform_id; ?>" data-base-name="<?php echo $basegroup; ?>" data-group="<?php echo $group; ?>"> <?php foreach ($form->getGroup('') as $field) : ?> <?php echo $field->renderField(); ?> <?php endforeach; ?> <?php if (!empty($buttons)) : ?> <div class="uk-margin-top uk-width-1-1 uk-text-right"> <div class="uk-button-group"> <?php if (!empty($buttons['add'])) : ?><a class="group-add uk-button uk-button-small uk-button-secondary group-add-<?php echo $unique_subform_id; ?>" aria-label="<?php echo JText::_('JGLOBAL_FIELD_ADD'); ?>"><span uk-icon="plus"></span> </a><?php endif; ?> <?php if (!empty($buttons['remove'])) : ?><a class="group-remove uk-button uk-button-small uk-button-danger group-remove-<?php echo $unique_subform_id; ?>" aria-label="<?php echo JText::_('JGLOBAL_FIELD_REMOVE'); ?>"><span uk-icon="minus"></span> </a><?php endif; ?> <?php if (!empty($buttons['move'])) : ?><a class="group-move uk-button uk-button-small uk-button-primary group-move-<?php echo $unique_subform_id; ?>" aria-label="<?php echo JText::_('JGLOBAL_FIELD_MOVE'); ?>"><span uk-icon="move"></span> </a><?php endif; ?> </div> </div> <?php endif; ?> </div>
JoomTools/plg_content_jtf
src/plugins/content/jtf/layouts/joomla/form/field/subform/repeatable/section.uikit3.php
PHP
gpl-3.0
2,183
package net.seabears.game.entities.normalmap; import static java.util.stream.IntStream.range; import java.io.IOException; import java.util.List; import org.joml.Matrix4f; import org.joml.Vector3f; import org.joml.Vector4f; import net.seabears.game.entities.Entity; import net.seabears.game.entities.Light; import net.seabears.game.shadows.ShadowShader; import net.seabears.game.textures.ModelTexture; import net.seabears.game.util.TransformationMatrix; public class NormalMappingShader extends ShadowShader { public static final int TEXTURE_SHADOW = 2; private final int lights; private int locationClippingPlane; private int locationModelTexture; private int locationNormalMap; private int[] locationLightAttenuation; private int[] locationLightColor; private int[] locationLightPosition; private int locationProjectionMatrix; private int locationReflectivity; private int locationShineDamper; private int locationSkyColor; private int locationTextureRows; private int locationTextureOffset; private int locationTransformationMatrix; private int locationViewMatrix; public NormalMappingShader(int lights) throws IOException { super(SHADER_ROOT + "normalmap/", TEXTURE_SHADOW); this.lights = lights; } @Override protected void bindAttributes() { super.bindAttribute(ATTR_POSITION, "position"); super.bindAttribute(ATTR_TEXTURE, "textureCoords"); super.bindAttribute(ATTR_NORMAL, "normal"); super.bindAttribute(ATTR_TANGENT, "tangent"); } @Override protected void getAllUniformLocations() { super.getAllUniformLocations(); locationClippingPlane = super.getUniformLocation("clippingPlane"); locationModelTexture = super.getUniformLocation("modelTexture"); locationNormalMap = super.getUniformLocation("normalMap"); locationLightAttenuation = super.getUniformLocations("attenuation", lights); locationLightColor = super.getUniformLocations("lightColor", lights); locationLightPosition = super.getUniformLocations("lightPosition", lights); locationProjectionMatrix = super.getUniformLocation("projectionMatrix"); locationReflectivity = super.getUniformLocation("reflectivity"); locationShineDamper = super.getUniformLocation("shineDamper"); locationSkyColor = super.getUniformLocation("skyColor"); locationTextureRows = super.getUniformLocation("textureRows"); locationTextureOffset = super.getUniformLocation("textureOffset"); locationTransformationMatrix = super.getUniformLocation("transformationMatrix"); locationViewMatrix = super.getUniformLocation("viewMatrix"); } public void loadClippingPlane(Vector4f plane) { this.loadFloat(locationClippingPlane, plane); } public void loadLights(final List<Light> lights, Matrix4f viewMatrix) { range(0, this.lights) .forEach(i -> loadLight(i < lights.size() ? lights.get(i) : OFF_LIGHT, i, viewMatrix)); } private void loadLight(Light light, int index, Matrix4f viewMatrix) { super.loadFloat(locationLightAttenuation[index], light.getAttenuation()); super.loadFloat(locationLightColor[index], light.getColor()); super.loadFloat(locationLightPosition[index], getEyeSpacePosition(light.getPosition(), viewMatrix)); } public void loadProjectionMatrix(Matrix4f matrix) { super.loadMatrix(locationProjectionMatrix, matrix); } public void loadSky(Vector3f color) { super.loadFloat(locationSkyColor, color); } public void loadNormalMap() { // refers to texture units // TEXTURE_SHADOW occupies one unit super.loadInt(locationModelTexture, 0); super.loadInt(locationNormalMap, 1); } public void loadTexture(ModelTexture texture) { super.loadFloat(locationReflectivity, texture.getReflectivity()); super.loadFloat(locationShineDamper, texture.getShineDamper()); super.loadFloat(locationTextureRows, texture.getRows()); } public void loadEntity(Entity entity) { loadTransformationMatrix( new TransformationMatrix(entity.getPosition(), entity.getRotation(), entity.getScale()) .toMatrix()); super.loadFloat(locationTextureOffset, entity.getTextureOffset()); } public void loadTransformationMatrix(Matrix4f matrix) { super.loadMatrix(locationTransformationMatrix, matrix); } public void loadViewMatrix(Matrix4f matrix) { super.loadMatrix(locationViewMatrix, matrix); } private static Vector3f getEyeSpacePosition(Vector3f position, Matrix4f viewMatrix) { final Vector4f eyeSpacePos = new Vector4f(position.x, position.y, position.z, 1.0f); viewMatrix.transform(eyeSpacePos); return new Vector3f(eyeSpacePos.x, eyeSpacePos.y, eyeSpacePos.z); } }
cberes/game
engine/src/main/java/net/seabears/game/entities/normalmap/NormalMappingShader.java
Java
gpl-3.0
4,691
'use strict' // untuk status uploader const STATUS_INITIAL = 0 const STATUS_SAVING = 1 const STATUS_SUCCESS = 2 const STATUS_FAILED = 3 // base url api const BASE_URL = 'http://localhost:3000' const app = new Vue({ el: '#app', data: { message: 'Hello', currentStatus: null, uploadError: null, uploadFieldName: 'image', uploadedFiles: [], files:[] }, computed: { isInitial() { return this.currentStatus === STATUS_INITIAL; }, isSaving() { return this.currentStatus === STATUS_SAVING; }, isSuccess() { return this.currentStatus === STATUS_SUCCESS; }, isFailed() { return this.currentStatus === STATUS_FAILED; } }, // computed methods: { // reset form to initial state getAllFile () { let self = this axios.get(`${BASE_URL}/files`) .then(response => { self.files = response.data }) }, // getAllFile() deleteFile (id) { axios.delete(`${BASE_URL}/files/${id}`) .then(r => { this.files.splice(id, 1) }) }, reset() { this.currentStatus = STATUS_INITIAL; this.uploadedFiles = []; this.uploadError = null; }, // reset() // upload data to the server save(formData) { console.log('save') console.log('form data', formData) this.currentStatus = STATUS_SAVING; axios.post(`${BASE_URL}/files/add`, formData) .then(up => { // console.log('up', up) this.uploadedFiles = [].concat(up) this.currentStatus = STATUS_SUCCESS }) .catch(e => { console.log(e.response.data) this.currentStatus = STATUS_FAILED }) }, // save() filesChange(fieldName, fileList) { // handle file changes const formData = new FormData(); formData.append('image', fileList[0]) console.log(formData) this.save(formData); } // filesChange() }, // methods mounted () { this.reset() }, created () { this.getAllFile() } })
hariantara/rapid-share-clone
client/assets/lib/upload.js
JavaScript
gpl-3.0
2,046
Simpla CMS 2.3.8 = f8952829bab201835e255735de3774f0
gohdan/DFC
known_files/hashes/Smarty/libs/sysplugins/smarty_internal_compile_extends.php
PHP
gpl-3.0
52
<h3>Publicaciones relacionadas</h3> <p><b>Análisis Publicados</b></p> <ul> <li><a href="http://www.trcimplan.gob.mx/blog/cobertura-y-rezago-de-servicios-en-las-viviendas-de-torreon.html">Cobertura y rezago de servicios en las viviendas de Torre&oacute;n</a></li> <li><a href="http://www.trcimplan.gob.mx/blog/hacinamiento-en-torreon-marzo2020.html">La Situaci&oacute;n de Hacinamiento en Torre&oacute;n</a></li> <li><a href="http://www.trcimplan.gob.mx/blog/caracteristicas-de-un-buen-espacio-publico-ene2020.html">Caracter&iacute;sticas de un Buen Espacio P&uacute;blico</a></li> <li><a href="http://www.trcimplan.gob.mx/blog/nuevos-esquemas-para-acceder-a-la-vivienda-enero2020.html">Nuevos esquemas para acceder a la vivienda.</a></li> <li><a href="http://www.trcimplan.gob.mx/blog/la-transformacion-de-la-periferia-urbana-de-torreon-dic2019.html">La Transformaci&oacute;n de la Periferia Urbana de Torre&oacute;n</a></li> <li><a href="http://www.trcimplan.gob.mx/blog/credito-de-vivienda-en-colonias-tradicionales-dic2019.html">Cr&eacute;ditos de Vivienda en Colonias Tradicionales como Estrategia para la Consolidaci&oacute;n Urbana</a></li> <li><a href="http://www.trcimplan.gob.mx/blog/suelo-mixto-como-politica-de-desarrollo-sostenible-nov2019.html">El Suelo Mixto como Pol&iacute;tica de Desarrollo Sostenible.</a></li> <li><a href="http://www.trcimplan.gob.mx/blog/programa-parcial-desarrollo-urbano-torreon-zona-norte-marzo2020.html">Propuesta de Programa Parcial de Desarrollo Urbano de la Zona Norte de Torre&oacute;n</a></li> <li><a href="http://www.trcimplan.gob.mx/blog/planificacion-urbana-en-la-salud-publica-de-la-laguna.html">La planificaci&oacute;n urbana, fundamental en la salud p&uacute;blica de los laguneros.</a></li> <li><a href="http://www.trcimplan.gob.mx/blog/urbanismo-con-enfoque-de-genero-en-la-laguna.html">Urbanismo con enfoque de g&eacute;nero en La Laguna</a></li> </ul> <p><b>Sistema Metropolitano de Indicadores</b></p> <ul> <li><a href="http://www.trcimplan.gob.mx/indicadores-torreon/sociedad-viviendas-con-agua-entubada.html">Viviendas con Agua Entubada en Torre&oacute;n</a></li> <li><a href="http://www.trcimplan.gob.mx/indicadores-torreon/sociedad-viviendas-particulares-habitadas-que-disponen-de-energia-electrica.html">Viviendas Particulares Habitadas que Disponen de Energ&iacute;a El&eacute;ctrica en Torre&oacute;n</a></li> <li><a href="http://www.trcimplan.gob.mx/indicadores-torreon/sociedad-viviendas-particulares-habitadas-que-disponen-de-drenaje.html">Viviendas Particulares Habitadas que Disponen de Drenaje en Torre&oacute;n</a></li> <li><a href="http://www.trcimplan.gob.mx/indicadores-la-laguna/sociedad-viviendas-con-lineas-telefonicas-moviles.html">Viviendas con L&iacute;neas Telef&oacute;nicas M&oacute;viles en La Laguna</a></li> <li><a href="http://www.trcimplan.gob.mx/indicadores-la-laguna/economia-intensidad-energetica-en-la-economia.html">Intensidad energ&eacute;tica en la econom&iacute;a en La Laguna</a></li> <li><a href="http://www.trcimplan.gob.mx/indicadores-la-laguna/sociedad-viviendas-con-drenaje-solo-conexion-a-red-publica.html">Viviendas con Drenaje (s&oacute;lo conexi&oacute;n a red p&uacute;blica) en La Laguna</a></li> <li><a href="http://www.trcimplan.gob.mx/indicadores-la-laguna/sociedad-viviendas-totales.html">Viviendas Totales en La Laguna</a></li> <li><a href="http://www.trcimplan.gob.mx/indicadores-la-laguna/sociedad-viviendas-habitadas.html">Viviendas Habitadas en La Laguna</a></li> <li><a href="http://www.trcimplan.gob.mx/indicadores-la-laguna/sustentabilidad-consumo-electrico-residencial.html">Consumo el&eacute;ctrico residencial en La Laguna</a></li> <li><a href="http://www.trcimplan.gob.mx/indicadores-la-laguna/sustentabilidad-consumo-electrico-en-servicios-municipales.html">Consumo el&eacute;ctrico en servicios municipales en La Laguna</a></li> </ul> <p><b>Sistema de Información Geográfica</b></p> <ul> <li><a href="http://www.trcimplan.gob.mx/sig-mapas-torreon/inventario-viviendas.html">Inventario de Viviendas</a></li> <li><a href="http://www.trcimplan.gob.mx/sig-mapas-torreon/caracteristicas-viviendas.html">Caracter&iacute;sticas de las Viviendas</a></li> <li><a href="http://www.trcimplan.gob.mx/sig-mapas-torreon/centros-atencion-adultos-mayores.html">Centros de Atenci&oacute;n a Adultos Mayores</a></li> <li><a href="http://www.trcimplan.gob.mx/sig-mapas-torreon/valores-catastrales-por-vialidades.html">Valores Catastrales por Vialidades</a></li> <li><a href="http://www.trcimplan.gob.mx/sig-mapas-torreon/crecimiento-decrecimiento-poblacion.html">Crecimiento y Decrecimiento de Poblaci&oacute;n</a></li> <li><a href="http://www.trcimplan.gob.mx/sig-mapas-torreon/avance-reconversion-tecnologica-led-alumbrado-publico.html">Avance de Reconversi&oacute;n Tecnol&oacute;gica Led del Alumbrado P&uacute;blico</a></li> </ul> <p><b>Plan Estratégico Torreón</b></p> <ul> <li><a href="http://www.trcimplan.gob.mx/pet/cartera-proyectos-entorno-urbano.html">Cartera de Proyectos: Entorno Urbano</a></li> <li><a href="http://www.trcimplan.gob.mx/pet/diagnostico-estrategico-entorno-urbano.html">Diagn&oacute;stico Estrat&eacute;gico: Entorno Urbano</a></li> <li><a href="http://www.trcimplan.gob.mx/pet/vision-entorno-urbano.html">Visi&oacute;n de Entorno Urbano 2040</a></li> <li><a href="http://www.trcimplan.gob.mx/pet/cartera-proyectos-medio-ambiente-sustentabilidad.html">Cartera de Proyectos: Medio Ambiente y Sustentabilidad</a></li> <li><a href="http://www.trcimplan.gob.mx/pet/diagnostico-estrategico-medio-ambiente-sustentabilidad.html">Diagn&oacute;stico Estrat&eacute;gico: Medio Ambiente y Sustentabilidad</a></li> <li><a href="http://www.trcimplan.gob.mx/pet/vision-medio-ambiente-sustentabilidad.html">Visi&oacute;n de Medio Ambiente y Sustentabilidad 2040</a></li> <li><a href="http://www.trcimplan.gob.mx/pet/diagnostico-estrategico-buen-gobierno.html">Diagn&oacute;stico Estrat&eacute;gico: Buen Gobierno</a></li> <li><a href="http://www.trcimplan.gob.mx/pet/diagnostico-estrategico-desarrollo-economico-innovacion.html">Diagn&oacute;stico Estrat&eacute;gico: Desarrollo Econ&oacute;mico e Innovaci&oacute;n</a></li> <li><a href="http://www.trcimplan.gob.mx/pet/diagnostico-estrategico-desarrollo-social.html">Diagn&oacute;stico Estrat&eacute;gico: Desarrollo Social</a></li> <li><a href="http://www.trcimplan.gob.mx/pet/diagnostico-estrategico-movilidad-transporte.html">Diagn&oacute;stico Estrat&eacute;gico: Movilidad y Transporte</a></li> </ul> <p><b>Sala de Prensa</b></p> <ul> <li><a href="http://www.trcimplan.gob.mx/sala-prensa/2018-10-31-decima-sesion.html">Presentan &ldquo;Propuesta conceptual para el manejo sustentable del agua&rdquo; en Sesi&oacute;n del IMPLAN.</a></li> <li><a href="http://www.trcimplan.gob.mx/sala-prensa/2019-02-22-conferencia-urbanizaciones-cerradas.html">IMPLAN presenta conferencia &ldquo;Islas de seguridad y distinci&oacute;n. Las urbanizaciones cerradas en la frontera noroeste de M&eacute;xico&rdquo;.</a></li> <li><a href="http://www.trcimplan.gob.mx/sala-prensa/2020-04-15-comunicado-conferencias-virtuales.html">El IMPLAN Torre&oacute;n y su Consejo Juvenil: Visi&oacute;n Metr&oacute;poli, presentar&aacute;n Conferencias Virtuales</a></li> <li><a href="http://www.trcimplan.gob.mx/sala-prensa/2020-02-27-segunda-sesion-consejo-2020.html">Presentan en Segunda Sesi&oacute;n de Consejo el &ldquo;Programa Parcial de Desarrollo Urbano para la Zona Norte de Torre&oacute;n&rdquo;</a></li> <li><a href="http://www.trcimplan.gob.mx/sala-prensa/2020-02-17-comunicado-enoe.html">Disminuye la tasa de desempleo en la Zona Metropolitana de La Laguna (ZML), al cuarto trimestre de 2019</a></li> <li><a href="http://www.trcimplan.gob.mx/sala-prensa/2020-02-06-comunicado-conferencia-imeplan.html">Postura sobre la creaci&oacute;n de un Instituto Metropolitano de Planeaci&oacute;n.</a></li> <li><a href="http://www.trcimplan.gob.mx/sala-prensa/2020-01-30-primer-sesion-consejo-2020.html">Primer Sesi&oacute;n de Consejo 2020. Se renueva el Consejo Directivo del IMPLAN.</a></li> <li><a href="http://www.trcimplan.gob.mx/sala-prensa/2019-09-26-novena-sesion-consejo.html">Novena Sesi&oacute;n de Consejo Implan. Presentan Resultados del Conversatorio y del Concurso &ldquo;Manos a la Cebra&rdquo;.</a></li> <li><a href="http://www.trcimplan.gob.mx/sala-prensa/2019-09-26-seminario-identidad-lagunera.html">Consejo Visi&oacute;n Metr&oacute;poli presenta Seminario de Identidad Lagunera</a></li> <li><a href="http://www.trcimplan.gob.mx/sala-prensa/2019-09-24-manos-a-la-cebra-reporte.html">Manos a la Cebra</a></li> </ul>
TRCIMPLAN/trcimplan.github.io
include/extra/indicadores-la-laguna/sociedad-viviendas-con-agua-entubada.html
HTML
gpl-3.0
8,682
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>P5</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="robots" content="noindex, nofollow"> <style> html, body, #map { height: 100%; margin: 0; padding: 0; } </style> </head> <body> <div id="map"></div> <script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap"></script> <script> function initMap() { var mapNode = document.getElementById('map'); var mapOptions = { zoom: 4, center: {lat: -25.363882, lng: 131.044922 } }; var map = new google.maps.Map(mapNode, mapOptions); } </script> </body> </html>
samplesize/samplesize.github.io
index.A.html
HTML
gpl-3.0
795
#include "../header/Base.h" #include "../header/Decorator.h" Decorator::Decorator() { } Decorator::Decorator(Base* node) { } Decorator::~Decorator() { }
ksemelka/rshell
src/Decorator.cpp
C++
gpl-3.0
156
/* * Copyright (C) 2010-2021 JPEXS * * 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 com.jpexs.decompiler.flash.gui.timeline; import com.jpexs.decompiler.flash.configuration.Configuration; import com.jpexs.decompiler.flash.tags.base.CharacterTag; import com.jpexs.decompiler.flash.tags.base.MorphShapeTag; import com.jpexs.decompiler.flash.timeline.DepthState; import com.jpexs.decompiler.flash.timeline.Timeline; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.SystemColor; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.swing.JPanel; import org.pushingpixels.substance.api.ColorSchemeAssociationKind; import org.pushingpixels.substance.api.ComponentState; import org.pushingpixels.substance.api.DecorationAreaType; import org.pushingpixels.substance.api.SubstanceLookAndFeel; import org.pushingpixels.substance.internal.utils.SubstanceColorUtilities; /** * * @author JPEXS */ public class TimelineBodyPanel extends JPanel implements MouseListener, KeyListener { private final Timeline timeline; public static final Color shapeTweenColor = new Color(0x59, 0xfe, 0x7c); public static final Color motionTweenColor = new Color(0xd1, 0xac, 0xf1); //public static final Color frameColor = new Color(0xbd, 0xd8, 0xfc); public static final Color borderColor = Color.black; public static final Color emptyBorderColor = new Color(0xbd, 0xd8, 0xfc); public static final Color keyColor = Color.black; public static final Color aColor = Color.black; public static final Color stopColor = Color.white; public static final Color stopBorderColor = Color.black; public static final Color borderLinesColor = new Color(0xde, 0xde, 0xde); //public static final Color selectedColor = new Color(113, 174, 235); public static final int borderLinesLength = 2; public static final float fontSize = 10.0f; private final List<FrameSelectionListener> listeners = new ArrayList<>(); public Point cursor = null; private enum BlockType { EMPTY, NORMAL, MOTION_TWEEN, SHAPE_TWEEN } public static Color getEmptyFrameColor() { return SubstanceColorUtilities.getLighterColor(getControlColor(), 0.7); } public static Color getEmptyFrameSecondColor() { return SubstanceColorUtilities.getLighterColor(getControlColor(), 0.9); } public static Color getSelectedColor() { if (Configuration.useRibbonInterface.get()) { return SubstanceLookAndFeel.getCurrentSkin().getColorScheme(DecorationAreaType.GENERAL, ColorSchemeAssociationKind.FILL, ComponentState.ROLLOVER_SELECTED).getBackgroundFillColor(); } else { return SystemColor.textHighlight; } } private static Color getControlColor() { if (Configuration.useRibbonInterface.get()) { return SubstanceLookAndFeel.getCurrentSkin().getColorScheme(DecorationAreaType.GENERAL, ColorSchemeAssociationKind.FILL, ComponentState.ENABLED).getBackgroundFillColor(); } else { return SystemColor.control; } } public static Color getFrameColor() { return SubstanceColorUtilities.getDarkerColor(getControlColor(), 0.1); } public void addFrameSelectionListener(FrameSelectionListener l) { listeners.add(l); } public void removeFrameSelectionListener(FrameSelectionListener l) { listeners.remove(l); } public TimelineBodyPanel(Timeline timeline) { this.timeline = timeline; Dimension dim = new Dimension(TimelinePanel.FRAME_WIDTH * timeline.getFrameCount() + 1, TimelinePanel.FRAME_HEIGHT * timeline.getMaxDepth()); setSize(dim); setPreferredSize(dim); addMouseListener(this); addKeyListener(this); setFocusable(true); } @Override protected void paintComponent(Graphics g1) { Graphics2D g = (Graphics2D) g1; g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setColor(TimelinePanel.getBackgroundColor()); g.fillRect(0, 0, getWidth(), getHeight()); Rectangle clip = g.getClipBounds(); int frameWidth = TimelinePanel.FRAME_WIDTH; int frameHeight = TimelinePanel.FRAME_HEIGHT; int start_f = clip.x / frameWidth; int start_d = clip.y / frameHeight; int end_f = (clip.x + clip.width) / frameWidth; int end_d = (clip.y + clip.height) / frameHeight; int max_d = timeline.getMaxDepth(); if (max_d < end_d) { end_d = max_d; } int max_f = timeline.getFrameCount() - 1; if (max_f < end_f) { end_f = max_f; } if (end_d - start_d + 1 < 0) { return; } // draw background for (int f = start_f; f <= end_f; f++) { g.setColor((f + 1) % 5 == 0 ? getEmptyFrameSecondColor() : getEmptyFrameColor()); g.fillRect(f * frameWidth, start_d * frameHeight, frameWidth, (end_d - start_d + 1) * frameHeight); g.setColor(emptyBorderColor); for (int d = start_d; d <= end_d; d++) { g.drawRect(f * frameWidth, d * frameHeight, frameWidth, frameHeight); } } // draw selected cell if (cursor != null) { g.setColor(getSelectedColor()); g.fillRect(cursor.x * frameWidth + 1, cursor.y * frameHeight + 1, frameWidth - 1, frameHeight - 1); } g.setColor(aColor); g.setFont(getFont().deriveFont(fontSize)); int awidth = g.getFontMetrics().stringWidth("a"); for (int f = start_f; f <= end_f; f++) { if (!timeline.getFrame(f).actions.isEmpty()) { g.drawString("a", f * frameWidth + frameWidth / 2 - awidth / 2, frameHeight / 2 + fontSize / 2); } } Map<Integer, Integer> depthMaxFrames = timeline.getDepthMaxFrame(); for (int d = start_d; d <= end_d; d++) { int maxFrame = depthMaxFrames.containsKey(d) ? depthMaxFrames.get(d) : -1; if (maxFrame < 0) { continue; } int end_f2 = Math.min(end_f, maxFrame); int start_f2 = Math.min(start_f, end_f2); // find the start frame number of the current block DepthState dsStart = timeline.getFrame(start_f2).layers.get(d); for (; start_f2 >= 1; start_f2--) { DepthState ds = timeline.getFrame(start_f2 - 1).layers.get(d); if (((dsStart == null) != (ds == null)) || (ds != null && dsStart.characterId != ds.characterId)) { break; } } for (int f = start_f2; f <= end_f2; f++) { DepthState fl = timeline.getFrame(f).layers.get(d); boolean motionTween = fl == null ? false : fl.motionTween; DepthState flNext = f < max_f ? timeline.getFrame(f + 1).layers.get(d) : null; DepthState flPrev = f > 0 ? timeline.getFrame(f - 1).layers.get(d) : null; CharacterTag cht = fl == null ? null : timeline.swf.getCharacter(fl.characterId); boolean shapeTween = cht != null && (cht instanceof MorphShapeTag); boolean motionTweenStart = !motionTween && (flNext != null && flNext.motionTween); boolean motionTweenEnd = !motionTween && (flPrev != null && flPrev.motionTween); //boolean shapeTweenStart = shapeTween && (flPrev == null || flPrev.characterId != fl.characterId); //boolean shapeTweenEnd = shapeTween && (flNext == null || flNext.characterId != fl.characterId); /*if (motionTweenStart || motionTweenEnd) { motionTween = true; }*/ int draw_f = f; int num_frames = 1; Color backColor; BlockType blockType; if (fl == null) { for (; f + 1 < timeline.getFrameCount(); f++) { fl = timeline.getFrame(f + 1).layers.get(d); if (fl != null && fl.characterId != -1) { break; } num_frames++; } backColor = getEmptyFrameColor(); blockType = BlockType.EMPTY; } else { for (; f + 1 < timeline.getFrameCount(); f++) { fl = timeline.getFrame(f + 1).layers.get(d); if (fl == null || fl.key) { break; } num_frames++; } backColor = shapeTween ? shapeTweenColor : motionTween ? motionTweenColor : getFrameColor(); blockType = shapeTween ? BlockType.SHAPE_TWEEN : motionTween ? BlockType.MOTION_TWEEN : BlockType.NORMAL; } drawBlock(g, backColor, d, draw_f, num_frames, blockType); } } if (cursor != null && cursor.x >= start_f && cursor.x <= end_f) { g.setColor(TimelinePanel.selectedBorderColor); g.drawLine(cursor.x * frameWidth + frameWidth / 2, 0, cursor.x * frameWidth + frameWidth / 2, getHeight()); } } private void drawBlock(Graphics2D g, Color backColor, int depth, int frame, int num_frames, BlockType blockType) { int frameWidth = TimelinePanel.FRAME_WIDTH; int frameHeight = TimelinePanel.FRAME_HEIGHT; g.setColor(backColor); g.fillRect(frame * frameWidth, depth * frameHeight, num_frames * frameWidth, frameHeight); g.setColor(borderColor); g.drawRect(frame * frameWidth, depth * frameHeight, num_frames * frameWidth, frameHeight); boolean selected = false; if (cursor != null && frame <= cursor.x && (frame + num_frames) > cursor.x && depth == cursor.y) { selected = true; } if (selected) { g.setColor(getSelectedColor()); g.fillRect(cursor.x * frameWidth + 1, depth * frameHeight + 1, frameWidth - 1, frameHeight - 1); } boolean isTween = blockType == BlockType.MOTION_TWEEN || blockType == BlockType.SHAPE_TWEEN; g.setColor(keyColor); if (isTween) { g.drawLine(frame * frameWidth, depth * frameHeight + frameHeight * 3 / 4, frame * frameWidth + num_frames * frameWidth - frameWidth / 2, depth * frameHeight + frameHeight * 3 / 4 ); } if (blockType == BlockType.EMPTY) { g.drawOval(frame * frameWidth + frameWidth / 4, depth * frameHeight + frameHeight * 3 / 4 - frameWidth / 2 / 2, frameWidth / 2, frameWidth / 2); } else { g.fillOval(frame * frameWidth + frameWidth / 4, depth * frameHeight + frameHeight * 3 / 4 - frameWidth / 2 / 2, frameWidth / 2, frameWidth / 2); } if (num_frames > 1) { int endFrame = frame + num_frames - 1; if (isTween) { g.fillOval(endFrame * frameWidth + frameWidth / 4, depth * frameHeight + frameHeight * 3 / 4 - frameWidth / 2 / 2, frameWidth / 2, frameWidth / 2); } else { g.setColor(stopColor); g.fillRect(endFrame * frameWidth + frameWidth / 4, depth * frameHeight + frameHeight / 2 - 2, frameWidth / 2, frameHeight / 2); g.setColor(stopBorderColor); g.drawRect(endFrame * frameWidth + frameWidth / 4, depth * frameHeight + frameHeight / 2 - 2, frameWidth / 2, frameHeight / 2); } g.setColor(borderLinesColor); for (int n = frame + 1; n < frame + num_frames; n++) { g.drawLine(n * frameWidth, depth * frameHeight + 1, n * frameWidth, depth * frameHeight + borderLinesLength); g.drawLine(n * frameWidth, depth * frameHeight + frameHeight - 1, n * frameWidth, depth * frameHeight + frameHeight - borderLinesLength); } } } @Override public void mouseClicked(MouseEvent e) { } public void frameSelect(int frame, int depth) { if (cursor != null && cursor.x == frame && (cursor.y == depth || depth == -1)) { return; } if (depth == -1 && cursor != null) { depth = cursor.y; } cursor = new Point(frame, depth); for (FrameSelectionListener l : listeners) { l.frameSelected(frame, depth); } repaint(); } @Override public void mousePressed(MouseEvent e) { Point p = e.getPoint(); p.x = p.x / TimelinePanel.FRAME_WIDTH; p.y = p.y / TimelinePanel.FRAME_HEIGHT; if (p.x >= timeline.getFrameCount()) { p.x = timeline.getFrameCount() - 1; } int maxDepth = timeline.getMaxDepth(); if (p.y > maxDepth) { p.y = maxDepth; } frameSelect(p.x, p.y); } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } @Override public void keyTyped(KeyEvent e) { } @Override public void keyPressed(KeyEvent e) { switch (e.getKeyCode()) { case 37: //left if (cursor.x > 0) { frameSelect(cursor.x - 1, cursor.y); } break; case 39: //right if (cursor.x < timeline.getFrameCount() - 1) { frameSelect(cursor.x + 1, cursor.y); } break; case 38: //up if (cursor.y > 0) { frameSelect(cursor.x, cursor.y - 1); } break; case 40: //down if (cursor.y < timeline.getMaxDepth()) { frameSelect(cursor.x, cursor.y + 1); } break; } } @Override public void keyReleased(KeyEvent e) { } }
jindrapetrik/jpexs-decompiler
src/com/jpexs/decompiler/flash/gui/timeline/TimelineBodyPanel.java
Java
gpl-3.0
15,335
//===========================================================================// // File: memblock.hh // // Contents: Interface specification of the memory block class // //---------------------------------------------------------------------------// // Copyright (C) Microsoft Corporation. All rights reserved. // //===========================================================================// #pragma once #include"stuff.hpp" namespace Stuff { //~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MemoryBlockHeader ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ class MemoryBlockHeader { public: MemoryBlockHeader *nextBlock; size_t blockSize; void TestInstance() {} }; //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MemoryBlockBase ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ class MemoryBlockBase #if defined(_ARMOR) : public Stuff::Signature #endif { public: void TestInstance() {Verify(blockMemory != NULL);} static void UsageReport(); static void CollapseBlocks(); protected: const char *blockName; MemoryBlockHeader *blockMemory; // the first record block allocated size_t blockSize, // size in bytes of the current record block recordSize, // size in bytes of the individual record deltaSize; // size in bytes of the growth blocks BYTE *firstHeaderRecord, // the beginning of useful free space *freeRecord, // the next address to allocate from the block *deletedRecord; // the next record to reuse MemoryBlockBase( size_t rec_size, size_t start, size_t delta, const char* name, HGOSHEAP parent = ParentClientHeap ); ~MemoryBlockBase(); void* Grow(); HGOSHEAP blockHeap; private: static MemoryBlockBase *firstBlock; MemoryBlockBase *nextBlock, *previousBlock; void Collapse(); }; //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MemoryBlock ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ class MemoryBlock: public MemoryBlockBase { public: static bool TestClass(); MemoryBlock( size_t rec_size, size_t start, size_t delta, const char* name, HGOSHEAP parent = ParentClientHeap ): MemoryBlockBase(rec_size, start, delta, name, parent) {} void* New(); void Delete(void *Where); void* operator[](size_t Index); }; //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MemoryBlockOf ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ template <class T> class MemoryBlockOf: public MemoryBlock { public: MemoryBlockOf( size_t start, size_t delta, const char* name, HGOSHEAP parent = ParentClientHeap ): MemoryBlock(sizeof(T), start, delta, name, parent) {} T* New() {return Cast_Pointer(T*, MemoryBlock::New());} void Delete(void *where) {MemoryBlock::Delete(where);} T* operator[](size_t index) {return Cast_Pointer(T*, MemoryBlock::operator[](index));} }; //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MemoryStack ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ class MemoryStack: public MemoryBlockBase { public: static bool TestClass(); protected: BYTE *topOfStack; MemoryStack( size_t rec_size, size_t start, size_t delta, const char* name, HGOSHEAP parent = ParentClientHeap ): MemoryBlockBase(rec_size, start, delta, name, parent) {topOfStack = NULL;} void* Push(const void *What); void* Push(); void* Peek() {return topOfStack;} void Pop(); }; //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MemoryStackOf ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ template <class T> class MemoryStackOf: public MemoryStack { public: MemoryStackOf( size_t start, size_t delta, const char *name, HGOSHEAP parent = ParentClientHeap ): MemoryStack(sizeof(T), start, delta, name, parent) {} T* Push(const T *what) {return Cast_Pointer(T*, MemoryStack::Push(what));} T* Peek() {return static_cast<T*>(MemoryStack::Peek());} void Pop() {MemoryStack::Pop();} }; }
alariq/mc2
mclib/stuff/memoryblock.hpp
C++
gpl-3.0
4,175
#!/usr/bin/env python import turtle import random def bloom(radius): turtle.colormode(255) for rad in range(40, 10, -5): for looper in range(360//rad): turtle.up() turtle.circle(radius+rad, rad) turtle.begin_fill() turtle.fillcolor((200+random.randint(0, rad), 200+random.randint(0, rad), 200+random.randint(0, rad))) turtle.down() turtle.circle(-rad) turtle.end_fill() def main(): """Simple flower, using global turtle instance""" turtle.speed(0) turtle.colormode(1.0) bloom(5) turtle.exitonclick() ### if __name__ == "__main__": main()
mpclemens/python-explore
turtle/bloom.py
Python
gpl-3.0
728
/* * Orbit, a versatile image analysis software for biological image-based quantification. * Copyright (C) 2009 - 2017 Idorsia Pharmaceuticals Ltd., Hegenheimermattweg 91, CH-4123 Allschwil, 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/>. * */ package com.actelion.research.orbit.imageprovider.tree; import com.actelion.research.orbit.beans.RawData; import com.actelion.research.orbit.imageprovider.ImageProviderOmero; import com.actelion.research.orbit.utils.Logger; import java.util.ArrayList; import java.util.List; public class TreeNodeProject extends AbstractOrbitTreeNode { private static Logger logger = Logger.getLogger(TreeNodeProject.class); private RawData project = null; private ImageProviderOmero imageProviderOmero; public TreeNodeProject(ImageProviderOmero imageProviderOmero, RawData project) { this.imageProviderOmero = imageProviderOmero; this.project = project; } @Override public synchronized List<TreeNodeProject> getNodes(AbstractOrbitTreeNode parent) { List<TreeNodeProject> nodeList = new ArrayList<>(); int group = -1; if (parent!=null && parent instanceof TreeNodeGroup) { TreeNodeGroup groupNode = (TreeNodeGroup) parent; RawData rdGroup = (RawData) groupNode.getIdentifier(); group = rdGroup.getRawDataId(); } List<RawData> rdList = loadProjects(group); for (RawData rd : rdList) { nodeList.add(new TreeNodeProject(imageProviderOmero, rd)); } return nodeList; } @Override public boolean isChildOf(Object parent) { return parent instanceof TreeNodeGroup; } @Override public Object getIdentifier() { return project; } @Override public String toString() { return project != null ? project.getBioLabJournal() : ""; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TreeNodeProject that = (TreeNodeProject) o; return project != null ? project.equals(that.project) : that.project == null; } @Override public int hashCode() { return project != null ? project.hashCode() : 0; } private List<RawData> loadProjects(int group) { return imageProviderOmero.loadProjects(group); } }
mstritt/image-provider-omero
src/main/java/com/actelion/research/orbit/imageprovider/tree/TreeNodeProject.java
Java
gpl-3.0
3,070
/*======= Image Animation Controls =======*/ /*Image-1 timing*/ @-webkit-keyframes image-1-animation { 0% { opacity: 0; } 5% { opacity: 1; } 29% { opacity: 1; } 30% { opacity: 0; } 100% { opacity: 0; } } /*Image-1 Text timing*/ @-webkit-keyframes text-1-animation { 0% { opacity: 0; } 4% { opacity: 1; } 27% { opacity: 1; } 28% { opacity: 0; } 100% { opacity: 0; } } /*Image-2 timing*/ @-webkit-keyframes image-2-animation { 0% { opacity: 0; } 30% { opacity: 0; } 35% { opacity: 1; } 60% { opacity: 1; } 61% { opacity: 0; } 100% { opacity: 0; } } /*Image-2 Text timing*/ @-webkit-keyframes text-2-animation { 0% {opacity:0;} 30% {opacity:0;} 34% {opacity:1;} 58% {opacity:1;} 59% {opacity:0;} 100% {opacity:0;} } /*Image-3 timing*/ @-webkit-keyframes image-3-animation { 0% { opacity: 0; } 61% { opacity: 0; } 66% { opacity: 1; } 99% { opacity: 1; } 100% { opacity: 0; } } @keyframes image-3-animation { 0% { opacity: 0; } 61% { opacity: 0; } 66% { opacity: 1; } 99% { opacity: 1; } 100% { opacity: 0; } } /*Image-3 Text timing*/ @-webkit-keyframes text-3-animation { 0% { opacity: 0; } 61% { opacity: 0; } 64% { opacity: 1; } 97% { opacity: 1; } 98% { opacity: 0; } } /*Logo timing*/ @-webkit-keyframes logo-animation { 0% { opacity: 0; } 5% { opacity: 1; } 29% { opacity: 1; right: 4vh; bottom: 4vh; } 30% { opacity:0; right:4vh; bottom:4vh; } 31% { right:4vh; bottom:115vh; } 32% { opacity:0; } 33% { opacity:1; } 98% { opacity:1; } 99% { opacity:0; right:4vh; bottom:115vh; } 100% { opacity:0; right:4vh; bottom:4vh; } } /*oniste logo timing*/ @-webkit-keyframes onsite-animation { 0% { opacity: 0; } 34% { opacity: 0; } 35% { opacity: 1; } 60% { opacity: 1; } 61% { opacity: 0; } 100% { opacity:0; } } /*======= Content Styling =======*/ body { font-size: 20px; font-family: "Oswald", sans-serif; } .image-1 { width:100vw; height:100vh; position: absolute; top:0; left:0; background-image:url(images/background-1.jpg); background-size: 100% 100%; -webkit-animation:image-1-animation 30s ease-out infinite; animation:image-1-animation 30s ease-out infinite; } .image-2 { width:100vw; height:100vh; position: absolute; top:0; left:0; background-image:url(images/background-2.jpg); background-size: 100% 100%; -webkit-animation:image-2-animation 30s ease-out infinite; animation:image-2-animation 30s ease-out infinite; } .image-3 { width:100vw; height:100vh; position: absolute; top:0; left:0; background-image:url(images/background-3.jpg); background-size: 100% 100%; -webkit-animation:image-3-animation 30s ease-out infinite; animation:image-3-animation 30s ease-out infinite; } #content .slides{ color:red; position: absolute; left:5vw; top:10vh; z-index: 10; opacity: 0; } /*Styling text for first image*/ #content .slides:nth-of-type(1){ opacity:1; top: 15vh; -webkit-animation:text-1-animation 30s ease-out infinite; animation:text-1-animation 30s ease-out infinite; } #content .slides:nth-of-type(1) .headline-1{ color:#B5BD00; font-size: 70px; line-height: 1; margin: 0; margin-bottom: 2vh; padding: 0; } #content .slides:nth-of-type(1) .headline-2{ color:#C11545; font-size: 130px; line-height: 1.1; width:60%; margin: 0; margin-bottom: 2vh; padding: 0; } #content .slides:nth-of-type(1) .body-text { color:#636363; font-size: 60px; font-weight: 300; line-height: 1.1; color:#777; margin: 0; padding: 0; width:55%; } /*Styling text for second image*/ #content .slides:nth-of-type(2){ opacity:0; top: 55vh; left:2vw; -webkit-animation:text-2-animation 30s ease-out infinite; animation:text-2-animation 30s ease-out infinite; } #content .slides:nth-of-type(2) .headline-1{ color:#B5BD00; display: inline-block; font-size: 80px; font-weight: 400; line-height: 1; margin: 0; margin-bottom: 2vh; padding: 0; } #content .slides:nth-of-type(2) .headline-2{ display: inline-block; color:#C11545; font-size: 80px; font-weight: 400; line-height: 1; margin: 0; margin-left: 2vw; margin-bottom: 2vh; padding: 0; } #content .slides:nth-of-type(2) .body-text { font-size: 43px; font-weight: 300; line-height: 1.1; color:#636363; margin: 0; margin-top: 1vh; padding: 0; width:100%; } /*Styling text for third image*/ #content .slides:nth-of-type(3){ opacity:0; top: 20vh; -webkit-animation:text-3-animation 30s ease-out infinite; animation:text-3-animation 30s ease-out infinite; } #content .slides:nth-of-type(3) .headline-1{ color:#C11545; font-size: 80px; font-weight: 700; line-height: 1.1; margin: 0; padding: 0; } #content .slides:nth-of-type(3) .headline-2 { color:#B5BD00; font-size: 80px; font-weight: 700; width:60%; line-height: 1.1; margin: 0; padding: 0; } #content .slides:nth-of-type(3) .body-text { color:#C11545; font-size: 80px; font-weight: 700; line-height: 1.1; margin: 0; padding: 0; width:60%; } .logo { width:10vw; height:5vw; position: absolute; right:4vh; bottom:4vh; background-image:url(images/logo-onthego.png); background-size: 100% 100%; z-index: 10; -webkit-animation:logo-animation 30s ease-out infinite; animation:logo-animation 30s ease-out infinite; } .logo-onsite { width:10vw; height:10vw; position: absolute; right:10vw; top:52vh; background-image: url(images/logo-onsite.png); background-size: 100% 100%; z-index: 10; -webkit-animation:onsite-animation 30s ease-out infinite; animation:onsite-animation 30s ease-out infinite; } .rise-logo { background-image: url(images/rise-icon.png); background-size: 100% 100%; opacity:.5; width:5%; height:5%; left:5%; top:90%; z-index:5; margin-left:-1%; position:absolute; z-index:5; } /* footer icons */ .github { width:20%; height:4%; left:10%; top:90%; z-index:4; margin-left:1%; margin-top: 1%; position:absolute; z-index:4; } .gitbtn { color:white; font-family:"Helvetica Neue",Helvetica,Arial,sans-serif; text-decoration: none; font-size:25px; opacity:.5; z-index:4; } @media only screen and (min-width: 1280px) { #gitbtn { font-size:25px; } } /* 1360x768 */ @media only screen and (min-width: 1360px) { #gitbtn { font-size:24px; } } /* 1920x1080*/ @media only screen and (min-width: 1920px) { #gitbtn { font-size: 34px; } } /* 3840x2160 */ @media screen and (min-width: 2200px) { #gitbtn { font-size: 64px; } }
Rise-Vision/content-restaurant-promotion
style.css
CSS
gpl-3.0
6,992
/** * * Copyright 2014 Martijn Brekhof * * This file is part of Catch Da Stars. * * Catch Da Stars 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. * * Catch Da Stars 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 Catch Da Stars. If not, see <http://www.gnu.org/licenses/>. * */ package com.strategames.engine.gameobject.types; import java.util.ArrayList; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.ChainShape; import com.badlogic.gdx.physics.box2d.Contact; import com.badlogic.gdx.physics.box2d.ContactImpulse; import com.badlogic.gdx.physics.box2d.Fixture; import com.badlogic.gdx.utils.Json; import com.badlogic.gdx.utils.JsonValue; import com.strategames.engine.gameobject.GameObject; import com.strategames.engine.gameobject.StaticBody; import com.strategames.engine.utils.ConfigurationItem; import com.strategames.engine.utils.Textures; public class Door extends StaticBody { public final static float WIDTH = 0.35f; public final static float HEIGHT = 0.35f; private Wall wall; private boolean open; private int[] entryLevel = new int[2]; // level this door provides access too private int[] exitLevel = new int[2]; // level this door can be accessed from public Door() { super(new Vector2(WIDTH, HEIGHT)); } @Override protected TextureRegion createImage() { return Textures.getInstance().passageToNextLevel; } @Override protected void setupBody(Body body) { Vector2 leftBottom = new Vector2(0, 0); Vector2 rightBottom = new Vector2(WIDTH, 0); Vector2 rightTop = new Vector2(WIDTH, HEIGHT); Vector2 leftTop = new Vector2(0, HEIGHT); ChainShape chain = new ChainShape(); chain.createLoop(new Vector2[] {leftBottom, rightBottom, rightTop, leftTop}); Fixture fixture = body.createFixture(chain, 0.0f); fixture.setSensor(true); } @Override protected void writeValues(Json json) { json.writeArrayStart("nextLevelPosition"); json.writeValue(entryLevel[0]); json.writeValue(entryLevel[1]); json.writeArrayEnd(); } @Override protected void readValue(JsonValue jsonData) { String name = jsonData.name(); if( name.contentEquals("nextLevelPosition")) { this.entryLevel = jsonData.asIntArray(); } } @Override public GameObject copy() { Door door = (Door) newInstance(); door.setPosition(getX(), getY()); int[] pos = getAccessToPosition(); door.setAccessTo(pos[0], pos[1]); return door; } @Override protected GameObject newInstance() { return new Door(); } @Override protected ArrayList<ConfigurationItem> createConfigurationItems() { return null; } @Override public void increaseSize() { } @Override public void decreaseSize() { } @Override protected void destroyAction() { } @Override public void handleCollision(Contact contact, ContactImpulse impulse, GameObject gameObject) { } @Override public void loadSounds() { } public Wall getWall() { return wall; } public void setWall(Wall wall) { this.wall = wall; } public boolean isOpen() { return open; } /** * Sets the level position this door provides access too * @param x * @param y */ public void setAccessTo(int x, int y) { this.entryLevel[0] = x; this.entryLevel[1] = y; } /** * Returns the level position this door provides access too * @return */ public int[] getAccessToPosition() { return entryLevel; } /** * Sets the level position from which this door is accessible * @param exitLevel */ public void setExitLevel(int[] exitLevel) { this.exitLevel = exitLevel; } /** * Returns the level position this door is accessible from * @return */ public int[] getAccessFromPosition() { return exitLevel; } @Override public String toString() { return super.toString() + ", nextLevelPosition="+entryLevel[0]+","+entryLevel[1]; } @Override public boolean equals(Object obj) { Door door; if( obj instanceof Door ) { door = (Door) obj; } else { return false; } int[] pos = door.getAccessToPosition(); return pos[0] == entryLevel[0] && pos[1] == entryLevel[1] && super.equals(obj); } public void open() { Gdx.app.log("Door", "open"); this.open = true; } public void close(){ this.open = false; } }
poisdeux/catchdastars
core/src/com/strategames/engine/gameobject/types/Door.java
Java
gpl-3.0
4,823
/* Buffer.cpp - This file is part of Element Copyright (C) 2014 Kushview, LLC. All rights reserved. */ #if ELEMENT_BUFFER_FACTORY Buffer::Buffer (DataType dataType_, uint32 subType_) : factory (nullptr), refs (0), dataType (dataType_), subType (subType_), capacity (0), next (nullptr) { } Buffer::~Buffer() { } void Buffer::attach (BufferFactory* owner) { jassert (factory == nullptr && owner != nullptr); factory = owner; } void Buffer::recycle() { if (isManaged()) factory->recycle (this); } void intrusive_ptr_add_ref (Buffer* b) { if (b->isManaged()) ++b->refs; } void intrusive_ptr_release (Buffer* b) { if (b->isManaged()) if (--b->refs == 0) b->recycle(); } #endif
kushview/element
experimental/Buffer.cpp
C++
gpl-3.0
780
/* * Decompiled with CFR 0_115. * * Could not load the following classes: * android.content.BroadcastReceiver * android.content.Context * android.content.Intent * android.content.IntentFilter */ package com.buzzfeed.android.vcr.util; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.support.annotation.NonNull; import com.buzzfeed.android.vcr.VCRConfig; import com.buzzfeed.toolkit.util.EZUtil; public final class VCRBitrateLimitingReceiver { private final Context mContext; private final BroadcastReceiver mReceiver; public VCRBitrateLimitingReceiver(@NonNull Context context) { this.mContext = EZUtil.checkNotNull(context, "Context must not be null."); this.mReceiver = new ConnectivityReceiver(); } public void register() { this.mContext.registerReceiver(this.mReceiver, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE")); } public void unregister() { this.mContext.unregisterReceiver(this.mReceiver); } private final class ConnectivityReceiver extends BroadcastReceiver { private ConnectivityReceiver() { } public void onReceive(Context context, Intent intent) { VCRConfig.getInstance().setAdaptiveBitrateLimitForConnection(context); } } }
SPACEDAC7/TrabajoFinalGrado
uploads/34f7f021ecaf167f6e9669e45c4483ec/java_source/com/buzzfeed/android/vcr/util/VCRBitrateLimitingReceiver.java
Java
gpl-3.0
1,401
namespace SandbarWorkbench { partial class frmOptions { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmOptions)); this.cmdOK = new System.Windows.Forms.Button(); this.tabControl1 = new System.Windows.Forms.TabControl(); this.tabPage1 = new System.Windows.Forms.TabPage(); this.txtInstallationGuid = new System.Windows.Forms.TextBox(); this.label9 = new System.Windows.Forms.Label(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.rdo5Digits = new System.Windows.Forms.RadioButton(); this.rdo4Digits = new System.Windows.Forms.RadioButton(); this.cboStartupView = new System.Windows.Forms.ComboBox(); this.label1 = new System.Windows.Forms.Label(); this.chkLoadLastDatabase = new System.Windows.Forms.CheckBox(); this.tabPage2 = new System.Windows.Forms.TabPage(); this.txtMasterDatabase = new System.Windows.Forms.TextBox(); this.label5 = new System.Windows.Forms.Label(); this.txtMasterPassword = new System.Windows.Forms.TextBox(); this.label4 = new System.Windows.Forms.Label(); this.txtMasterUserName = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.txtMasterServer = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.tabPage3 = new System.Windows.Forms.TabPage(); this.grdFolderPaths = new System.Windows.Forms.DataGridView(); this.tabPage4 = new System.Windows.Forms.TabPage(); this.button1 = new System.Windows.Forms.Button(); this.txtMainPy = new System.Windows.Forms.TextBox(); this.label17 = new System.Windows.Forms.Label(); this.valBenchmark = new System.Windows.Forms.NumericUpDown(); this.label16 = new System.Windows.Forms.Label(); this.valIncrement = new System.Windows.Forms.NumericUpDown(); this.label15 = new System.Windows.Forms.Label(); this.cmdBrowseGDALWarp = new System.Windows.Forms.Button(); this.txtGDALWarp = new System.Windows.Forms.TextBox(); this.label14 = new System.Windows.Forms.Label(); this.cmdBrowseCompExtents = new System.Windows.Forms.Button(); this.txtCompExtents = new System.Windows.Forms.TextBox(); this.label13 = new System.Windows.Forms.Label(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.txtSpatialReference = new System.Windows.Forms.TextBox(); this.cboInterpolation = new System.Windows.Forms.ComboBox(); this.label8 = new System.Windows.Forms.Label(); this.valDefaultOutputCellSize = new System.Windows.Forms.NumericUpDown(); this.valDefaultInputCellSize = new System.Windows.Forms.NumericUpDown(); this.label7 = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.tabPage5 = new System.Windows.Forms.TabPage(); this.cmdTestAWS = new System.Windows.Forms.Button(); this.txtErrorLoggingKey = new System.Windows.Forms.TextBox(); this.lblStreamName = new System.Windows.Forms.Label(); this.chkAWSLoggingEnabled = new System.Windows.Forms.CheckBox(); this.tabPage6 = new System.Windows.Forms.TabPage(); this.cboAuditFieldDates = new System.Windows.Forms.ComboBox(); this.label12 = new System.Windows.Forms.Label(); this.cboSurveyDates = new System.Windows.Forms.ComboBox(); this.label11 = new System.Windows.Forms.Label(); this.cboTripDates = new System.Windows.Forms.ComboBox(); this.label10 = new System.Windows.Forms.Label(); this.tabPage7 = new System.Windows.Forms.TabPage(); this.txtPython = new System.Windows.Forms.TextBox(); this.cmdHelp = new System.Windows.Forms.Button(); this.tt = new System.Windows.Forms.ToolTip(this.components); this.tabControl1.SuspendLayout(); this.tabPage1.SuspendLayout(); this.groupBox1.SuspendLayout(); this.tabPage2.SuspendLayout(); this.tabPage3.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.grdFolderPaths)).BeginInit(); this.tabPage4.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.valBenchmark)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.valIncrement)).BeginInit(); this.groupBox2.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.valDefaultOutputCellSize)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.valDefaultInputCellSize)).BeginInit(); this.tabPage5.SuspendLayout(); this.tabPage6.SuspendLayout(); this.tabPage7.SuspendLayout(); this.SuspendLayout(); // // cmdOK // this.cmdOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.cmdOK.DialogResult = System.Windows.Forms.DialogResult.OK; this.cmdOK.Location = new System.Drawing.Point(491, 373); this.cmdOK.Name = "cmdOK"; this.cmdOK.Size = new System.Drawing.Size(75, 23); this.cmdOK.TabIndex = 0; this.cmdOK.Text = "Close"; this.cmdOK.UseVisualStyleBackColor = true; this.cmdOK.Click += new System.EventHandler(this.cmdOK_Click); // // tabControl1 // this.tabControl1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.tabControl1.Controls.Add(this.tabPage1); this.tabControl1.Controls.Add(this.tabPage2); this.tabControl1.Controls.Add(this.tabPage3); this.tabControl1.Controls.Add(this.tabPage4); this.tabControl1.Controls.Add(this.tabPage5); this.tabControl1.Controls.Add(this.tabPage6); this.tabControl1.Controls.Add(this.tabPage7); this.tabControl1.Location = new System.Drawing.Point(12, 12); this.tabControl1.Name = "tabControl1"; this.tabControl1.SelectedIndex = 0; this.tabControl1.Size = new System.Drawing.Size(554, 355); this.tabControl1.TabIndex = 0; // // tabPage1 // this.tabPage1.Controls.Add(this.txtInstallationGuid); this.tabPage1.Controls.Add(this.label9); this.tabPage1.Controls.Add(this.groupBox1); this.tabPage1.Controls.Add(this.cboStartupView); this.tabPage1.Controls.Add(this.label1); this.tabPage1.Controls.Add(this.chkLoadLastDatabase); this.tabPage1.Location = new System.Drawing.Point(4, 22); this.tabPage1.Name = "tabPage1"; this.tabPage1.Padding = new System.Windows.Forms.Padding(3); this.tabPage1.Size = new System.Drawing.Size(546, 329); this.tabPage1.TabIndex = 0; this.tabPage1.Text = "Start Up"; this.tabPage1.UseVisualStyleBackColor = true; // // txtInstallationGuid // this.txtInstallationGuid.Location = new System.Drawing.Point(122, 171); this.txtInstallationGuid.MaxLength = 256; this.txtInstallationGuid.Name = "txtInstallationGuid"; this.txtInstallationGuid.ReadOnly = true; this.txtInstallationGuid.Size = new System.Drawing.Size(292, 20); this.txtInstallationGuid.TabIndex = 5; // // label9 // this.label9.AutoSize = true; this.label9.Location = new System.Drawing.Point(29, 175); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(87, 13); this.label9.TabIndex = 4; this.label9.Text = "Installation GUID"; // // groupBox1 // this.groupBox1.Controls.Add(this.rdo5Digits); this.groupBox1.Controls.Add(this.rdo4Digits); this.groupBox1.Location = new System.Drawing.Point(29, 80); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(385, 79); this.groupBox1.TabIndex = 3; this.groupBox1.TabStop = false; this.groupBox1.Text = "Sandbar Folder Identification"; // // rdo5Digits // this.rdo5Digits.AutoSize = true; this.rdo5Digits.Location = new System.Drawing.Point(27, 49); this.rdo5Digits.Name = "rdo5Digits"; this.rdo5Digits.Size = new System.Drawing.Size(145, 17); this.rdo5Digits.TabIndex = 1; this.rdo5Digits.Text = "5 digit codes (e.g. 0003L)"; this.rdo5Digits.UseVisualStyleBackColor = true; // // rdo4Digits // this.rdo4Digits.AutoSize = true; this.rdo4Digits.Checked = true; this.rdo4Digits.Location = new System.Drawing.Point(27, 25); this.rdo4Digits.Name = "rdo4Digits"; this.rdo4Digits.Size = new System.Drawing.Size(139, 17); this.rdo4Digits.TabIndex = 0; this.rdo4Digits.TabStop = true; this.rdo4Digits.Text = "4 digit codes (e.g. 003L)"; this.rdo4Digits.UseVisualStyleBackColor = true; // // cboStartupView // this.cboStartupView.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cboStartupView.FormattingEnabled = true; this.cboStartupView.Location = new System.Drawing.Point(149, 44); this.cboStartupView.Name = "cboStartupView"; this.cboStartupView.Size = new System.Drawing.Size(265, 21); this.cboStartupView.TabIndex = 2; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(26, 47); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(108, 13); this.label1.TabIndex = 1; this.label1.Text = "Open view at start up"; // // chkLoadLastDatabase // this.chkLoadLastDatabase.AutoSize = true; this.chkLoadLastDatabase.Location = new System.Drawing.Point(25, 16); this.chkLoadLastDatabase.Name = "chkLoadLastDatabase"; this.chkLoadLastDatabase.Size = new System.Drawing.Size(116, 17); this.chkLoadLastDatabase.TabIndex = 0; this.chkLoadLastDatabase.Text = "Load last database"; this.chkLoadLastDatabase.UseVisualStyleBackColor = true; // // tabPage2 // this.tabPage2.Controls.Add(this.txtMasterDatabase); this.tabPage2.Controls.Add(this.label5); this.tabPage2.Controls.Add(this.txtMasterPassword); this.tabPage2.Controls.Add(this.label4); this.tabPage2.Controls.Add(this.txtMasterUserName); this.tabPage2.Controls.Add(this.label3); this.tabPage2.Controls.Add(this.txtMasterServer); this.tabPage2.Controls.Add(this.label2); this.tabPage2.Location = new System.Drawing.Point(4, 22); this.tabPage2.Name = "tabPage2"; this.tabPage2.Padding = new System.Windows.Forms.Padding(3); this.tabPage2.Size = new System.Drawing.Size(546, 329); this.tabPage2.TabIndex = 1; this.tabPage2.Text = "Master Database"; this.tabPage2.UseVisualStyleBackColor = true; // // txtMasterDatabase // this.txtMasterDatabase.Location = new System.Drawing.Point(98, 50); this.txtMasterDatabase.Name = "txtMasterDatabase"; this.txtMasterDatabase.Size = new System.Drawing.Size(433, 20); this.txtMasterDatabase.TabIndex = 3; // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(37, 54); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(53, 13); this.label5.TabIndex = 2; this.label5.Text = "Database"; // // txtMasterPassword // this.txtMasterPassword.Location = new System.Drawing.Point(98, 114); this.txtMasterPassword.Name = "txtMasterPassword"; this.txtMasterPassword.PasswordChar = '*'; this.txtMasterPassword.Size = new System.Drawing.Size(433, 20); this.txtMasterPassword.TabIndex = 7; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(37, 118); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(53, 13); this.label4.TabIndex = 6; this.label4.Text = "Password"; // // txtMasterUserName // this.txtMasterUserName.Location = new System.Drawing.Point(98, 82); this.txtMasterUserName.Name = "txtMasterUserName"; this.txtMasterUserName.Size = new System.Drawing.Size(433, 20); this.txtMasterUserName.TabIndex = 5; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(32, 86); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(58, 13); this.label3.TabIndex = 4; this.label3.Text = "User name"; // // txtMasterServer // this.txtMasterServer.Location = new System.Drawing.Point(98, 18); this.txtMasterServer.Name = "txtMasterServer"; this.txtMasterServer.Size = new System.Drawing.Size(433, 20); this.txtMasterServer.TabIndex = 1; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(52, 22); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(38, 13); this.label2.TabIndex = 0; this.label2.Text = "Server"; // // tabPage3 // this.tabPage3.Controls.Add(this.grdFolderPaths); this.tabPage3.Location = new System.Drawing.Point(4, 22); this.tabPage3.Name = "tabPage3"; this.tabPage3.Padding = new System.Windows.Forms.Padding(3); this.tabPage3.Size = new System.Drawing.Size(546, 329); this.tabPage3.TabIndex = 2; this.tabPage3.Text = "Folders"; this.tabPage3.UseVisualStyleBackColor = true; // // grdFolderPaths // this.grdFolderPaths.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.grdFolderPaths.Location = new System.Drawing.Point(125, 112); this.grdFolderPaths.Name = "grdFolderPaths"; this.grdFolderPaths.Size = new System.Drawing.Size(240, 150); this.grdFolderPaths.TabIndex = 0; this.grdFolderPaths.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.grdFolderPaths_CellClick); // // tabPage4 // this.tabPage4.Controls.Add(this.button1); this.tabPage4.Controls.Add(this.txtMainPy); this.tabPage4.Controls.Add(this.label17); this.tabPage4.Controls.Add(this.valBenchmark); this.tabPage4.Controls.Add(this.label16); this.tabPage4.Controls.Add(this.valIncrement); this.tabPage4.Controls.Add(this.label15); this.tabPage4.Controls.Add(this.cmdBrowseGDALWarp); this.tabPage4.Controls.Add(this.txtGDALWarp); this.tabPage4.Controls.Add(this.label14); this.tabPage4.Controls.Add(this.cmdBrowseCompExtents); this.tabPage4.Controls.Add(this.txtCompExtents); this.tabPage4.Controls.Add(this.label13); this.tabPage4.Controls.Add(this.groupBox2); this.tabPage4.Controls.Add(this.cboInterpolation); this.tabPage4.Controls.Add(this.label8); this.tabPage4.Controls.Add(this.valDefaultOutputCellSize); this.tabPage4.Controls.Add(this.valDefaultInputCellSize); this.tabPage4.Controls.Add(this.label7); this.tabPage4.Controls.Add(this.label6); this.tabPage4.Location = new System.Drawing.Point(4, 22); this.tabPage4.Name = "tabPage4"; this.tabPage4.Padding = new System.Windows.Forms.Padding(3); this.tabPage4.Size = new System.Drawing.Size(546, 329); this.tabPage4.TabIndex = 3; this.tabPage4.Text = "Sandbar Analysis"; this.tabPage4.UseVisualStyleBackColor = true; // // button1 // this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.button1.Image = global::SandbarWorkbench.Properties.Resources.explorer; this.button1.Location = new System.Drawing.Point(517, 171); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(23, 23); this.button1.TabIndex = 18; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // txtMainPy // this.txtMainPy.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtMainPy.Location = new System.Drawing.Point(176, 172); this.txtMainPy.Name = "txtMainPy"; this.txtMainPy.ReadOnly = true; this.txtMainPy.Size = new System.Drawing.Size(335, 20); this.txtMainPy.TabIndex = 17; // // label17 // this.label17.AutoSize = true; this.label17.Location = new System.Drawing.Point(39, 176); this.label17.Name = "label17"; this.label17.Size = new System.Drawing.Size(128, 13); this.label17.TabIndex = 16; this.label17.Text = "Sandbar Analysis Main.py"; // // valBenchmark // this.valBenchmark.Increment = new decimal(new int[] { 1000, 0, 0, 0}); this.valBenchmark.Location = new System.Drawing.Point(420, 49); this.valBenchmark.Maximum = new decimal(new int[] { 40000, 0, 0, 0}); this.valBenchmark.Name = "valBenchmark"; this.valBenchmark.Size = new System.Drawing.Size(120, 20); this.valBenchmark.TabIndex = 9; this.valBenchmark.Value = new decimal(new int[] { 8000, 0, 0, 0}); // // label16 // this.label16.AutoSize = true; this.label16.Location = new System.Drawing.Point(304, 53); this.label16.Name = "label16"; this.label16.Size = new System.Drawing.Size(113, 13); this.label16.TabIndex = 8; this.label16.Text = "Benchmark stage (cfs)"; // // valIncrement // this.valIncrement.DecimalPlaces = 1; this.valIncrement.Location = new System.Drawing.Point(420, 18); this.valIncrement.Maximum = new decimal(new int[] { 5, 0, 0, 0}); this.valIncrement.Name = "valIncrement"; this.valIncrement.Size = new System.Drawing.Size(120, 20); this.valIncrement.TabIndex = 7; this.valIncrement.Value = new decimal(new int[] { 1, 0, 0, 65536}); // // label15 // this.label15.AutoSize = true; this.label15.Location = new System.Drawing.Point(300, 22); this.label15.Name = "label15"; this.label15.Size = new System.Drawing.Size(117, 13); this.label15.TabIndex = 6; this.label15.Text = "Elevation increment (m)"; // // cmdBrowseGDALWarp // this.cmdBrowseGDALWarp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.cmdBrowseGDALWarp.Image = global::SandbarWorkbench.Properties.Resources.explorer; this.cmdBrowseGDALWarp.Location = new System.Drawing.Point(517, 142); this.cmdBrowseGDALWarp.Name = "cmdBrowseGDALWarp"; this.cmdBrowseGDALWarp.Size = new System.Drawing.Size(23, 23); this.cmdBrowseGDALWarp.TabIndex = 15; this.cmdBrowseGDALWarp.UseVisualStyleBackColor = true; this.cmdBrowseGDALWarp.Click += new System.EventHandler(this.cmdBrowseGDALWarp_Click); // // txtGDALWarp // this.txtGDALWarp.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtGDALWarp.Location = new System.Drawing.Point(176, 143); this.txtGDALWarp.Name = "txtGDALWarp"; this.txtGDALWarp.ReadOnly = true; this.txtGDALWarp.Size = new System.Drawing.Size(335, 20); this.txtGDALWarp.TabIndex = 14; // // label14 // this.label14.AutoSize = true; this.label14.Location = new System.Drawing.Point(55, 147); this.label14.Name = "label14"; this.label14.Size = new System.Drawing.Size(117, 13); this.label14.TabIndex = 13; this.label14.Text = "GDAL warp executable"; // // cmdBrowseCompExtents // this.cmdBrowseCompExtents.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.cmdBrowseCompExtents.Image = global::SandbarWorkbench.Properties.Resources.explorer; this.cmdBrowseCompExtents.Location = new System.Drawing.Point(517, 111); this.cmdBrowseCompExtents.Name = "cmdBrowseCompExtents"; this.cmdBrowseCompExtents.Size = new System.Drawing.Size(23, 23); this.cmdBrowseCompExtents.TabIndex = 12; this.cmdBrowseCompExtents.UseVisualStyleBackColor = true; this.cmdBrowseCompExtents.Click += new System.EventHandler(this.cmdBrowseCompExtents_Click); // // txtCompExtents // this.txtCompExtents.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtCompExtents.Location = new System.Drawing.Point(176, 112); this.txtCompExtents.Name = "txtCompExtents"; this.txtCompExtents.ReadOnly = true; this.txtCompExtents.Size = new System.Drawing.Size(335, 20); this.txtCompExtents.TabIndex = 11; // // label13 // this.label13.AutoSize = true; this.label13.Location = new System.Drawing.Point(16, 116); this.label13.Name = "label13"; this.label13.Size = new System.Drawing.Size(156, 13); this.label13.TabIndex = 10; this.label13.Text = "Computational extents shapefile"; // // groupBox2 // this.groupBox2.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.groupBox2.Controls.Add(this.txtSpatialReference); this.groupBox2.Location = new System.Drawing.Point(6, 202); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(534, 121); this.groupBox2.TabIndex = 19; this.groupBox2.TabStop = false; this.groupBox2.Text = "Spatial Reference"; // // txtSpatialReference // this.txtSpatialReference.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtSpatialReference.Location = new System.Drawing.Point(6, 19); this.txtSpatialReference.Multiline = true; this.txtSpatialReference.Name = "txtSpatialReference"; this.txtSpatialReference.Size = new System.Drawing.Size(522, 96); this.txtSpatialReference.TabIndex = 0; // // cboInterpolation // this.cboInterpolation.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cboInterpolation.FormattingEnabled = true; this.cboInterpolation.Location = new System.Drawing.Point(176, 80); this.cboInterpolation.Name = "cboInterpolation"; this.cboInterpolation.Size = new System.Drawing.Size(121, 21); this.cboInterpolation.TabIndex = 5; // // label8 // this.label8.AutoSize = true; this.label8.Location = new System.Drawing.Point(33, 84); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(139, 13); this.label8.TabIndex = 4; this.label8.Text = "Default interpolation method"; // // valDefaultOutputCellSize // this.valDefaultOutputCellSize.DecimalPlaces = 2; this.valDefaultOutputCellSize.Location = new System.Drawing.Point(176, 49); this.valDefaultOutputCellSize.Name = "valDefaultOutputCellSize"; this.valDefaultOutputCellSize.Size = new System.Drawing.Size(120, 20); this.valDefaultOutputCellSize.TabIndex = 3; // // valDefaultInputCellSize // this.valDefaultInputCellSize.DecimalPlaces = 2; this.valDefaultInputCellSize.Location = new System.Drawing.Point(176, 18); this.valDefaultInputCellSize.Name = "valDefaultInputCellSize"; this.valDefaultInputCellSize.Size = new System.Drawing.Size(120, 20); this.valDefaultInputCellSize.TabIndex = 1; // // label7 // this.label7.AutoSize = true; this.label7.Location = new System.Drawing.Point(12, 53); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(160, 13); this.label7.TabIndex = 2; this.label7.Text = "Default raster output cell size (m)"; // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(12, 22); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(160, 13); this.label6.TabIndex = 0; this.label6.Text = "Default input text file cell size (m)"; // // tabPage5 // this.tabPage5.Controls.Add(this.cmdTestAWS); this.tabPage5.Controls.Add(this.txtErrorLoggingKey); this.tabPage5.Controls.Add(this.lblStreamName); this.tabPage5.Controls.Add(this.chkAWSLoggingEnabled); this.tabPage5.Location = new System.Drawing.Point(4, 22); this.tabPage5.Name = "tabPage5"; this.tabPage5.Padding = new System.Windows.Forms.Padding(3); this.tabPage5.Size = new System.Drawing.Size(546, 329); this.tabPage5.TabIndex = 4; this.tabPage5.Text = "Error Logging"; this.tabPage5.UseVisualStyleBackColor = true; // // cmdTestAWS // this.cmdTestAWS.Location = new System.Drawing.Point(11, 84); this.cmdTestAWS.Name = "cmdTestAWS"; this.cmdTestAWS.Size = new System.Drawing.Size(156, 23); this.cmdTestAWS.TabIndex = 8; this.cmdTestAWS.Text = "Test AWS Message Log"; this.cmdTestAWS.UseVisualStyleBackColor = true; this.cmdTestAWS.Visible = false; // // txtErrorLoggingKey // this.txtErrorLoggingKey.Location = new System.Drawing.Point(119, 36); this.txtErrorLoggingKey.Name = "txtErrorLoggingKey"; this.txtErrorLoggingKey.ReadOnly = true; this.txtErrorLoggingKey.Size = new System.Drawing.Size(407, 20); this.txtErrorLoggingKey.TabIndex = 7; // // lblStreamName // this.lblStreamName.AutoSize = true; this.lblStreamName.Location = new System.Drawing.Point(29, 40); this.lblStreamName.Name = "lblStreamName"; this.lblStreamName.Size = new System.Drawing.Size(86, 13); this.lblStreamName.TabIndex = 6; this.lblStreamName.Text = "Error logging key"; // // chkAWSLoggingEnabled // this.chkAWSLoggingEnabled.AutoSize = true; this.chkAWSLoggingEnabled.Location = new System.Drawing.Point(11, 12); this.chkAWSLoggingEnabled.Name = "chkAWSLoggingEnabled"; this.chkAWSLoggingEnabled.Size = new System.Drawing.Size(261, 17); this.chkAWSLoggingEnabled.TabIndex = 5; this.chkAWSLoggingEnabled.Text = "Share status and error information with developers"; this.chkAWSLoggingEnabled.UseVisualStyleBackColor = true; // // tabPage6 // this.tabPage6.Controls.Add(this.cboAuditFieldDates); this.tabPage6.Controls.Add(this.label12); this.tabPage6.Controls.Add(this.cboSurveyDates); this.tabPage6.Controls.Add(this.label11); this.tabPage6.Controls.Add(this.cboTripDates); this.tabPage6.Controls.Add(this.label10); this.tabPage6.Location = new System.Drawing.Point(4, 22); this.tabPage6.Name = "tabPage6"; this.tabPage6.Padding = new System.Windows.Forms.Padding(3); this.tabPage6.Size = new System.Drawing.Size(546, 329); this.tabPage6.TabIndex = 5; this.tabPage6.Text = "Dates"; this.tabPage6.UseVisualStyleBackColor = true; // // cboAuditFieldDates // this.cboAuditFieldDates.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.cboAuditFieldDates.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cboAuditFieldDates.FormattingEnabled = true; this.cboAuditFieldDates.Location = new System.Drawing.Point(101, 71); this.cboAuditFieldDates.Name = "cboAuditFieldDates"; this.cboAuditFieldDates.Size = new System.Drawing.Size(430, 21); this.cboAuditFieldDates.TabIndex = 5; // // label12 // this.label12.AutoSize = true; this.label12.Location = new System.Drawing.Point(36, 75); this.label12.Name = "label12"; this.label12.Size = new System.Drawing.Size(58, 13); this.label12.TabIndex = 4; this.label12.Text = "Audit fields"; // // cboSurveyDates // this.cboSurveyDates.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.cboSurveyDates.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cboSurveyDates.FormattingEnabled = true; this.cboSurveyDates.Location = new System.Drawing.Point(101, 44); this.cboSurveyDates.Name = "cboSurveyDates"; this.cboSurveyDates.Size = new System.Drawing.Size(430, 21); this.cboSurveyDates.TabIndex = 3; // // label11 // this.label11.AutoSize = true; this.label11.Location = new System.Drawing.Point(25, 48); this.label11.Name = "label11"; this.label11.Size = new System.Drawing.Size(69, 13); this.label11.TabIndex = 2; this.label11.Text = "Survey dates"; // // cboTripDates // this.cboTripDates.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.cboTripDates.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cboTripDates.FormattingEnabled = true; this.cboTripDates.Location = new System.Drawing.Point(101, 17); this.cboTripDates.Name = "cboTripDates"; this.cboTripDates.Size = new System.Drawing.Size(430, 21); this.cboTripDates.TabIndex = 1; // // label10 // this.label10.AutoSize = true; this.label10.Location = new System.Drawing.Point(40, 21); this.label10.Name = "label10"; this.label10.Size = new System.Drawing.Size(54, 13); this.label10.TabIndex = 0; this.label10.Text = "Trip dates"; // // tabPage7 // this.tabPage7.Controls.Add(this.txtPython); this.tabPage7.Location = new System.Drawing.Point(4, 22); this.tabPage7.Name = "tabPage7"; this.tabPage7.Padding = new System.Windows.Forms.Padding(3); this.tabPage7.Size = new System.Drawing.Size(546, 329); this.tabPage7.TabIndex = 6; this.tabPage7.Text = "Python"; this.tabPage7.UseVisualStyleBackColor = true; // // txtPython // this.txtPython.AcceptsReturn = true; this.txtPython.Dock = System.Windows.Forms.DockStyle.Fill; this.txtPython.Location = new System.Drawing.Point(3, 3); this.txtPython.Multiline = true; this.txtPython.Name = "txtPython"; this.txtPython.Size = new System.Drawing.Size(540, 323); this.txtPython.TabIndex = 0; // // cmdHelp // this.cmdHelp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.cmdHelp.Location = new System.Drawing.Point(16, 373); this.cmdHelp.Name = "cmdHelp"; this.cmdHelp.Size = new System.Drawing.Size(75, 23); this.cmdHelp.TabIndex = 2; this.cmdHelp.Text = "Help"; this.cmdHelp.UseVisualStyleBackColor = true; this.cmdHelp.Click += new System.EventHandler(this.cmdHelp_Click); // // frmOptions // this.AcceptButton = this.cmdOK; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(578, 408); this.Controls.Add(this.cmdHelp); this.Controls.Add(this.tabControl1); this.Controls.Add(this.cmdOK); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "frmOptions"; this.Text = "frmOptions"; this.Load += new System.EventHandler(this.frmOptions_Load); this.HelpRequested += new System.Windows.Forms.HelpEventHandler(this.frmOptions_HelpRequested); this.tabControl1.ResumeLayout(false); this.tabPage1.ResumeLayout(false); this.tabPage1.PerformLayout(); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.tabPage2.ResumeLayout(false); this.tabPage2.PerformLayout(); this.tabPage3.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.grdFolderPaths)).EndInit(); this.tabPage4.ResumeLayout(false); this.tabPage4.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.valBenchmark)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.valIncrement)).EndInit(); this.groupBox2.ResumeLayout(false); this.groupBox2.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.valDefaultOutputCellSize)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.valDefaultInputCellSize)).EndInit(); this.tabPage5.ResumeLayout(false); this.tabPage5.PerformLayout(); this.tabPage6.ResumeLayout(false); this.tabPage6.PerformLayout(); this.tabPage7.ResumeLayout(false); this.tabPage7.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Button cmdOK; private System.Windows.Forms.TabControl tabControl1; private System.Windows.Forms.TabPage tabPage1; private System.Windows.Forms.TabPage tabPage2; private System.Windows.Forms.ComboBox cboStartupView; private System.Windows.Forms.Label label1; private System.Windows.Forms.CheckBox chkLoadLastDatabase; private System.Windows.Forms.TextBox txtMasterDatabase; private System.Windows.Forms.Label label5; private System.Windows.Forms.TextBox txtMasterPassword; private System.Windows.Forms.Label label4; private System.Windows.Forms.TextBox txtMasterUserName; private System.Windows.Forms.Label label3; private System.Windows.Forms.TextBox txtMasterServer; private System.Windows.Forms.Label label2; private System.Windows.Forms.TabPage tabPage3; private System.Windows.Forms.DataGridView grdFolderPaths; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.RadioButton rdo5Digits; private System.Windows.Forms.RadioButton rdo4Digits; private System.Windows.Forms.TabPage tabPage4; private System.Windows.Forms.NumericUpDown valDefaultOutputCellSize; private System.Windows.Forms.NumericUpDown valDefaultInputCellSize; private System.Windows.Forms.Label label7; private System.Windows.Forms.Label label6; private System.Windows.Forms.ComboBox cboInterpolation; private System.Windows.Forms.Label label8; private System.Windows.Forms.TabPage tabPage5; private System.Windows.Forms.Button cmdTestAWS; private System.Windows.Forms.TextBox txtErrorLoggingKey; private System.Windows.Forms.Label lblStreamName; private System.Windows.Forms.CheckBox chkAWSLoggingEnabled; private System.Windows.Forms.TextBox txtInstallationGuid; private System.Windows.Forms.Label label9; private System.Windows.Forms.TabPage tabPage6; private System.Windows.Forms.ComboBox cboAuditFieldDates; private System.Windows.Forms.Label label12; private System.Windows.Forms.ComboBox cboSurveyDates; private System.Windows.Forms.Label label11; private System.Windows.Forms.ComboBox cboTripDates; private System.Windows.Forms.Label label10; private System.Windows.Forms.Button cmdHelp; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.TextBox txtSpatialReference; private System.Windows.Forms.Button cmdBrowseCompExtents; private System.Windows.Forms.TextBox txtCompExtents; private System.Windows.Forms.Label label13; private System.Windows.Forms.Button cmdBrowseGDALWarp; private System.Windows.Forms.TextBox txtGDALWarp; private System.Windows.Forms.Label label14; private System.Windows.Forms.NumericUpDown valBenchmark; private System.Windows.Forms.Label label16; private System.Windows.Forms.NumericUpDown valIncrement; private System.Windows.Forms.Label label15; private System.Windows.Forms.TabPage tabPage7; private System.Windows.Forms.TextBox txtPython; private System.Windows.Forms.Button button1; private System.Windows.Forms.TextBox txtMainPy; private System.Windows.Forms.Label label17; private System.Windows.Forms.ToolTip tt; } }
NorthArrowResearch/sandbar-analysis-workbench
SandbarWorkbench/frmOptions.Designer.cs
C#
gpl-3.0
43,463
sap.ui.jsview(ui5nameSpace, { // define the (default) controller type for this View getControllerName: function() { return "my.own.controller"; }, // defines the UI of this View createContent: function(oController) { // button text is bound to Model, "press" action is bound to Controller's event handler return; } });
Ryan-Boyd/ui5-artisan
lib/stubs/views/PlainView.js
JavaScript
gpl-3.0
368
/* * 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. */ /** * * @author dh2744 */ import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.LineNumberReader; import java.util.Vector; /* * 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. */ /** * * @author dh2744 */ public class CheckField { //check that spike list and exp log exists, are correct and match public static int checkSpkListExpLog(javax.swing.JTextField spikeListField, javax.swing.JTextField expLogFileField, javax.swing.JButton runButton, javax.swing.JTextArea outputTextArea) { int exitValue = 0; runButton.setEnabled(false); Boolean errorLog = false; //Vector<String> logResult = new Vector<>(); // to do java 1.6 compatibility Vector<String> logResult = new Vector<String>(); //experimental log try { //read in Experimental log String csvFile = expLogFileField.getText(); String[] csvCheck1 = csvFile.split("\\."); String csvText1 = "csv"; System.out.println("end of Exp log"+ csvCheck1[csvCheck1.length - 1] + " equals csv:" ); System.out.println(csvCheck1[csvCheck1.length - 1].equals("csv")); //two ifs for whether string ends in "]" or not if ( !csvCheck1[csvCheck1.length - 1].equals("csv") ){ if (!(csvCheck1[csvCheck1.length].equals("csv"))) { logResult.add( "Exp log file chosen is not a csv file" ); ErrorHandler.errorPanel("Exp log file chosen " + '\n' + csvFile + '\n' + "Is not a csv file."); exitValue = -1; errorLog = true; } } // This will reference one line at a time String line = null; Boolean expLogGood = true; try { // FileReader reads text files in the default encoding. FileReader fileReader = new FileReader(csvFile); // Always wrap FileReader in BufferedReader. BufferedReader bufferedReader = new BufferedReader(fileReader); line = bufferedReader.readLine(); String[] expLogParts = line.split(","); if (!expLogParts[0].toUpperCase().equals("PROJECT")) { logResult.add( "Error reading in expLog File" ); logResult.add("Exp log file lacks Project column." ); ErrorHandler.errorPanel("Exp log file lacks Project column " + '\n' + "Please re-enter exp log file"); errorLog = true; expLogGood = false; exitValue = -1; } else if (!expLogParts[1].toUpperCase().equals("EXPERIMENT DATE")) { logResult.add( "Error reading in expLog File" ); logResult.add("Exp log file lacks Experiment column." ); ErrorHandler.errorPanel("Exp log file lacks Experiment column " + '\n' + "Please re-enter exp log file"); errorLog = true; expLogGood = false; exitValue = -1; } else { LineNumberReader lnr = null; line = bufferedReader.readLine(); Integer i = 1; line = bufferedReader.readLine(); String[] country = line.split(","); System.out.println("Start while loop"); while (line != null) { System.out.println(line); System.out.println(country[0]); System.out.println("Current line num " + i); i++; line = bufferedReader.readLine(); System.out.println(line); System.out.println("line = null? " + (line == null)); //System.out.println("line.isEmpty ? " + (line.isEmpty()) ); if (line != null) { System.out.println("line : " + line); System.out.println("country : " + country[0]); country = line.split(","); } } System.out.println("Current line num " + i); System.out.println("done with while loop"); // Always close files. bufferedReader.close(); } //end of if-else } catch (FileNotFoundException ex) { logResult.add( "ExpLog File not found" ); System.out.println( "Unable to open file '" + csvFile + "'"); errorLog = true; exitValue = -1; expLogGood = false; } catch (IOException ex) { logResult.add( "Error reading in expLog File" ); logResult.add("IOException." ); System.out.println( "Error reading file '" + csvFile + "'"); errorLog = true; expLogGood = false; exitValue = -1; } System.out.println("expLogGood : " + expLogGood); //++++++++++++++++++++++++++++++++++++read in Spk list file String check = spikeListField.getText(); String[] temp = check.split(","); System.out.println("spk list chooser: " + temp[0]); String[] spkCsvFile = temp; if (temp.length > 1) { System.out.println("spkCsvFile.length = " + temp.length); for (int ind = 0; ind < temp.length; ind++) { if (0 == ind) { spkCsvFile[ind] = temp[ind].substring(1, temp[ind].length()).trim(); System.out.println("spkCsvFile[ind] " + spkCsvFile[ind]); File fileCheck = new File(spkCsvFile[ind]); System.out.println("exists? spkCsvFile[" + ind + "] " + fileCheck.exists()); } else if (ind == (temp.length - 1)) { spkCsvFile[ind] = temp[ind].substring(0, temp[ind].length() - 1).trim(); System.out.println("spkCsvFile[ind] " + spkCsvFile[ind]); File fileCheck = new File(spkCsvFile[ind]); System.out.println("exists? spkCsvFile[" + ind + "] " + fileCheck.exists()); } else { spkCsvFile[ind] = temp[ind]; System.out.println("spkCsvFile[ind] " + spkCsvFile[ind].trim()); System.out.println("MMMMM" + spkCsvFile[ind].trim() + "MMMMMMM"); File fileCheck = new File(spkCsvFile[ind].trim()); System.out.println("exists? spkCsvFile[" + ind + "] " + fileCheck.exists()); } } } else if (temp.length == 1) { System.out.println("temp.length = " + temp.length); System.out.println("temp[0].length = " + temp.length); System.out.println("temp[0].toString().endsWith(]) = " + temp.toString().endsWith("]") ); System.out.println("temp[0].toString().length() "+temp[0].toString().length()); System.out.println("temp[0].substring(temp[0].toString().length()-1 ) = " + temp[0].substring(temp[0].toString().length()-1 ).toString() ); System.out.println("temp[0].substring(temp[0].toString().length()-1 ).equals(]) "+ temp[0].substring(temp[0].toString().length()-1 ).equals("]") ); if ( temp[0].substring(temp[0].toString().length()-1 ).equals("]") ){ int len = temp[0].length(); len--; System.out.println("temp[0].toString().substring(2,3 ) = "+ temp[0].substring(2,3) ); System.out.println("temp[0].toString().substring(1,2 ) = "+ temp[0].toString().substring(1,2 ) ); System.out.println("temp[0].toString().substring(0,1 ) = "+ temp[0].substring(0,1 ) ); if (temp[0].substring(2,3 ).equals("[")){ spkCsvFile[0] = temp[0].substring(3, len).trim(); } else if (temp[0].toString().substring(1,2 ).equals("[")){ spkCsvFile[0] = temp[0].toString().substring(2, len).trim(); } else if (temp[0].toString().substring(0,1 ).equals("[")){ spkCsvFile[0] = temp[0].toString().substring(1, len).trim(); } System.out.println("spkCsvFile[ind] " + spkCsvFile[0]); } File fileCheck = new File(spkCsvFile[0]); System.out.println("exists? spkCsvFile[" + 0 + "] " + fileCheck.exists()); } System.out.println("Done with reading in spike-list file names "); // check that it's csv for (int j = 0; j < spkCsvFile.length; j++) { String[] csvCheck = spkCsvFile[j].split("\\."); String csvText = "csv"; System.out.println(csvCheck[csvCheck.length - 1]); System.out.println(csvCheck[csvCheck.length - 1].equals("csv")); if (!(csvCheck[csvCheck.length - 1].equals("csv")|| csvCheck[csvCheck.length].equals("csv")) ) { logResult.add( "Spike-list csv file chosen " + spkCsvFile[j] ); logResult.add("Is not a csv file." ); ErrorHandler.errorPanel("Spike-list csv file chosen " + spkCsvFile[j] + '\n' + "Is not a csv file."); errorLog = true; exitValue = -1; } // spike list file try { // FileReader reads text files in the default encoding. FileReader fileReader = new FileReader(spkCsvFile[j].trim()); System.out.println("file reader " + spkCsvFile[j]); // Always wrap FileReader in BufferedReader. BufferedReader bufferedReader = new BufferedReader(fileReader); line = bufferedReader.readLine(); System.out.println(line); String[] spkListHeader = line.split(","); String third = "Time (s)"; System.out.println(spkListHeader[2]); // check for spike list file System.out.println(spkListHeader[2]); if (!(spkListHeader[2].equals("Time (s)") || spkListHeader[2].equals("Time (s) ") || spkListHeader[2].equals("\"Time (s)\"") || spkListHeader[2].equals("\"Time (s) \""))) { logResult.add( "Spike-list csv file chosen " + spkCsvFile[j] ); logResult.add("Is not a proper spike-list file" ); logResult.add( "'Time (s)' should be third column header " ); logResult.add("Instead 3rd column is "+ spkListHeader[2].toString() ); ErrorHandler.errorPanel("Spike-list csv file chosen '" + spkCsvFile[j]+"'" + '\n' + "Is not a proper spike-list file" + '\n' + "'Time (s)' should be third column header"); exitValue = -1; errorLog=true; } for (int counter2 = 1; counter2 < 5; counter2++) { // content check line = bufferedReader.readLine(); if (counter2 == 2) { System.out.println(line); String[] spkListContents = line.split(","); //Project,Experiment Date,Plate SN,DIV,Well,Treatment,Size,Dose,Units System.out.println("Time(s) " + spkListContents[2] + " , Electrode =" + spkListContents[3]); } } // Always close files. bufferedReader.close(); } catch (FileNotFoundException ex) { logResult.add( " Unable to open file " + spkCsvFile[j] ); logResult.add(" Please select another spike list file " ); ErrorHandler.errorPanel("Unable to open file " + j + " " + spkCsvFile[j] + '\n' + "Please select another spike list file"); exitValue = -1; errorLog = true; } catch (IOException ex) { logResult.add( "Error reading file " + spkCsvFile[j] ); logResult.add(" IOException " ); ErrorHandler.errorPanel( "Error reading file '" + j + " " + spkCsvFile[j] + "'" + '\n' + "Please select another spike list file"); errorLog = true; exitValue = -1; } } //end of loop through spike List Files // +++++++++need to compare files System.out.println("Starting match"); for (int j = 0; j < spkCsvFile.length; j++) { if (expLogGood && !errorLog) { try { // FileReader reads text files in the default encoding. FileReader fileReader = new FileReader(csvFile); // Always wrap FileReader in BufferedReader. BufferedReader bufferedReader = new BufferedReader(fileReader); line = bufferedReader.readLine(); line = bufferedReader.readLine(); System.out.println(line); String[] country = line.split(","); //Project,Experiment Date,Plate SN,DIV,Well,Treatment,Size,Dose,Units if (country.length>5 ){ System.out.println("Project " + country[0] + " , Exp Date=" + country[1] + " , Plate SN=" + country[2] + " , DIV= " + country[3] + " , Well=" + country[4] + " , trt=" + country[5]); } else{ System.out.println("Project " + country[0] + " , Exp Date=" + country[1] + " , Plate SN=" + country[2] + " , DIV= " + country[3] + " , Well=" + country[4] ); } // now compare to name of spk-list file File spkListFile = new File(spkCsvFile[j]); System.out.println("spkCsvFile "+spkCsvFile[j]); System.out.println( "File.separator" + File.separator ); String name1 = spkListFile.getName().toString(); String[] partsName1 = name1.split("_"); System.out.println(partsName1[0]); System.out.println(partsName1[1]); System.out.println(partsName1[2]); if (!(partsName1[0].equals(country[0].trim() ))) { System.out.println("spkListFileNameParts " + partsName1[0].toString()); System.out.println("country " + country[0]); logResult.add( "project in spk-list file name: " + partsName1[0] ); logResult.add("& experimental log file project: " + country[0]); logResult.add("Do not match"); ErrorHandler.errorPanel( "project in spk-list file name: " + partsName1[0] + '\n' + "& experimental log file project: " + country[0] + '\n' + "Do not match"); exitValue = -1; errorLog = true; } else if (!(partsName1[1].equals(country[1].trim() ))) { logResult.add( "Experiment date does not match between" + '\n' + spkCsvFile[j] ); logResult.add("and experimental log file. "); logResult.add("Please re-enter file"); ErrorHandler.errorPanel( "Experiment date does not match between" + '\n' + spkCsvFile[j] + " name and experimental log file. '"); exitValue = -1; errorLog = true; } else if (!(partsName1[2].equals(country[2].trim() ))) { logResult.add("No match between spk list" + spkCsvFile[j]); logResult.add("and experimental log file. "); ErrorHandler.errorPanel( "No match between spk list" + spkCsvFile[j] + '\n' + "and experimental log file. '" + '\n' + "Project name do not match"); exitValue = -1; errorLog = true; } // Always close files. bufferedReader.close(); } catch (FileNotFoundException ex) { System.out.println( "Unable to open file '" + csvFile + "'"); logResult.add(" Unable to open file "); logResult.add("'" + csvFile + "'"); ErrorHandler.errorPanel( "Unable to open file " + '\n' + "'" + csvFile + "'" + '\n' ); exitValue = -1; errorLog = true; } catch (IOException ex) { System.out.println( "Error reading file '" + csvFile + "'"); ErrorHandler.errorPanel( "Error reading file " + "'" + csvFile + "'" + '\n' ); logResult.add("Error reading file "); logResult.add("'" + csvFile + "'"); errorLog = true; exitValue = -1; } System.out.println("expLogGood : " + expLogGood); System.out.println(" "); } System.out.println("done with match "); System.out.println("NUMER OF TIMES THROUGH LOOP : " + j + 1); } //end of loop through spike list files if (!errorLog) { runButton.setEnabled(true); logResult.add("Files chosen are without errors"); logResult.add("They match one another"); logResult.add("proceeeding to Analysis"); } PrintToTextArea.printToTextArea(logResult , outputTextArea); } catch (Exception e) { logResult.add("Try at reading the csv file failed"); logResult.add(" "); logResult.add(" "); e.printStackTrace(); exitValue = -1; PrintToTextArea.printToTextArea(logResult , outputTextArea); } return(exitValue); } public static int checkRObject(javax.swing.JTextField rasterFileChooserField, javax.swing.JButton makeRasterButton, javax.swing.JTextArea toolsTextArea) { int exitValue = 0; makeRasterButton.setEnabled(false); Boolean errorLog = false; //Vector<String> logResult = new Vector<>(); // to do java 1.6 compatibility Vector<String> logResult = new Vector<String>(); //check Robject try { //check extension String rObject = rasterFileChooserField.getText(); String[] rObjectCheck1 = rObject.split("\\."); String rObjectText1 = "RData"; System.out.println( rObject + " (-1) end in .RData? : " ); System.out.println(rObjectCheck1[rObjectCheck1.length-1 ].equals("RData")); System.out.println( rObject + " end in .RData? : " ); //System.out.println(rObjectCheck1[rObjectCheck1.length ].equals("RData")); //two ifs for whether string ends in "]" or not if ( !rObjectCheck1[rObjectCheck1.length-1 ].equals("RData") ) { System.out.println("in if statement"); ErrorHandler.errorPanel("Robject file chosen " + '\n' + rObject + '\n' + "Is not a Robject of .RData extension"); exitValue = -1; errorLog = true; return exitValue; } // This will reference one line at a time String line = null; Boolean expLogGood = true; try { // Query R for what's in the Robject System.out.println(" right before SystemCall.systemCall(cmd0, outputTextArea) " ); Vector<String> envVars = new Vector<String>(); File fileWD = new File(System.getProperty("java.class.path")); File dashDir = fileWD.getAbsoluteFile().getParentFile(); System.out.println("Dash dir " + dashDir.toString()); File systemPaths = new File( dashDir.toString() +File.separator+"Code" + File.separator+"systemPaths.txt"); File javaClassPath = new File(System.getProperty("java.class.path")); File rootPath1 = javaClassPath.getAbsoluteFile().getParentFile(); String rootPath2Slash = rootPath1.toString(); rootPath2Slash = rootPath2Slash.replace("\\", "\\\\"); envVars=GetEnvVars.getEnvVars( systemPaths, toolsTextArea ); String cmd0 = envVars.get(0).toString() + " " + rootPath2Slash + File.separator +"Code"+ File.separator + "RobjectInfoScript.R "+ "RobjectPath="+rObject.toString(); System.out.println( "cmd0 " + cmd0 ); SystemCall.systemCall(cmd0, toolsTextArea ); System.out.println("After SystemCall in Raster " ); /// here we need code to populate raster parameter object } catch (Exception i){ logResult.add("Try at running RobjectInfoScript.R"); logResult.add(" "); logResult.add(" "); i.printStackTrace(); exitValue = -1; PrintToTextArea.printToTextArea(logResult , toolsTextArea); } } catch (Exception e) { logResult.add("Try at reading the Robject file failed"); logResult.add(" "); logResult.add(" "); e.printStackTrace(); exitValue = -1; PrintToTextArea.printToTextArea(logResult , toolsTextArea); } return(exitValue); } public static int checkDistFile( javax.swing.JTextField distPlotFileField, javax.swing.JButton plotDistrButton, javax.swing.JTextArea distPlotTextArea) { int exitValue = 0; plotDistrButton.setEnabled(false); Boolean errorLog = false; //Vector<String> logResult = new Vector<>(); // to do java 1.6 compatibility Vector<String> logResult = new Vector<String>(); //check Robject try { //check extension String[] distPlotFile1=RemoveSqBrackets.removeSqBrackets( distPlotFileField ); String[] distPlotFileCheck1 = distPlotFile1[0].split("\\."); String distPlotFileText1 = "csv"; System.out.println( distPlotFile1[0] + " (-1) end in .csv? : " ); System.out.println(distPlotFileCheck1[distPlotFileCheck1.length-1 ].equals("csv")); System.out.println(distPlotFileCheck1[distPlotFileCheck1.length-1 ] + " =distPlotFileCheck1[distPlotFileCheck1.length-1 ]" ); //System.out.println(rObjectCheck1[rObjectCheck1.length ].equals("RData")); //two ifs for whether string ends in "]" or not if ( !distPlotFileCheck1[distPlotFileCheck1.length-1 ].equals("csv") ) { System.out.println("in if statement"); ErrorHandler.errorPanel("Distribution file chosen " + '\n' + distPlotFile1[0] + '\n' + "Is not a distribution file of .csv extension"); exitValue = -1; errorLog = true; return exitValue; } // This will reference one line at a time String line = null; Boolean expLogGood = true; try { // Query R for what's in the Robject System.out.println(" right before SystemCall.systemCall(cmd0, distPlotTextArea) " ); Vector<String> envVars = new Vector<String>(); File fileWD = new File(System.getProperty("java.class.path")); File dashDir = fileWD.getAbsoluteFile().getParentFile(); System.out.println("Dash dir " + dashDir.toString()); File systemPaths = new File( dashDir.toString() +File.separator+"Code" + File.separator+"systemPaths.txt"); File javaClassPath = new File(System.getProperty("java.class.path")); File rootPath1 = javaClassPath.getAbsoluteFile().getParentFile(); String rootPath2Slash = rootPath1.toString(); rootPath2Slash = rootPath2Slash.replace("\\", "\\\\"); envVars=GetEnvVars.getEnvVars( systemPaths, distPlotTextArea ); String cmd0 = envVars.get(0).toString() + " " + rootPath2Slash + File.separator +"Code"+ File.separator + "distFileInfoScript.R "+ "distFilePath="+distPlotFile1[0].toString(); System.out.println( "cmd0 " + cmd0 ); SystemCall.systemCall(cmd0, distPlotTextArea ); System.out.println("After SystemCall in distPlot " ); /// here we need code to populate raster parameter object } catch (Exception i){ logResult.add("Try at running distFileInfoScript.R"); logResult.add(" "); logResult.add(" "); i.printStackTrace(); exitValue = -1; PrintToTextArea.printToTextArea(logResult , distPlotTextArea); } } catch (Exception e) { logResult.add("Try at reading the Robject file failed"); logResult.add(" "); logResult.add(" "); e.printStackTrace(); exitValue = -1; PrintToTextArea.printToTextArea(logResult ,distPlotTextArea); } return(exitValue); } }
igm-team/meaRtools
Java_IGMDash-master/src/CheckField.java
Java
gpl-3.0
29,621
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('characters', '0011_auto_20160212_1144'), ] operations = [ migrations.CreateModel( name='CharacterSpells', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('character', models.ForeignKey(verbose_name='Karakt\xe4r', to='characters.Character')), ], options={ 'verbose_name': 'Karakt\xe4rers magi', 'verbose_name_plural': 'Karakt\xe4rers magi', }, ), migrations.AlterModelOptions( name='spellextras', options={'verbose_name': 'Magi extra', 'verbose_name_plural': 'Magi extra'}, ), migrations.AlterModelOptions( name='spellinfo', options={'verbose_name': 'Magi information', 'verbose_name_plural': 'Magi information'}, ), migrations.AddField( model_name='spellinfo', name='name', field=models.CharField(default='Magins namn', max_length=256, verbose_name='Namn'), ), migrations.AlterField( model_name='spellinfo', name='parent', field=models.ForeignKey(verbose_name='Tillh\xf6righet', to='characters.SpellParent'), ), migrations.AddField( model_name='characterspells', name='spells', field=models.ManyToManyField(to='characters.SpellInfo', verbose_name='Magier och besv\xe4rjelser'), ), ]
svamp/rp_management
characters/migrations/0012_auto_20160212_1210.py
Python
gpl-3.0
1,712
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Copyright (C) 2011-2021 OpenFOAM Foundation \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of OpenFOAM. OpenFOAM 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. OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>. \*---------------------------------------------------------------------------*/ #include "localEulerDdtScheme.H" #include "surfaceInterpolate.H" #include "fvMatrices.H" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace Foam { // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace fv { // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // template<class Type> const volScalarField& localEulerDdtScheme<Type>::localRDeltaT() const { return localEulerDdt::localRDeltaT(mesh()); } template<class Type> const surfaceScalarField& localEulerDdtScheme<Type>::localRDeltaTf() const { return localEulerDdt::localRDeltaTf(mesh()); } template<class Type> tmp<GeometricField<Type, fvPatchField, volMesh>> localEulerDdtScheme<Type>::fvcDdt ( const dimensioned<Type>& dt ) { const word ddtName("ddt(" + dt.name() + ')'); return tmp<GeometricField<Type, fvPatchField, volMesh>> ( GeometricField<Type, fvPatchField, volMesh>::New ( ddtName, mesh(), dimensioned<Type> ( "0", dt.dimensions()/dimTime, Zero ), calculatedFvPatchField<Type>::typeName ) ); } template<class Type> tmp<GeometricField<Type, fvPatchField, volMesh>> localEulerDdtScheme<Type>::fvcDdt ( const GeometricField<Type, fvPatchField, volMesh>& vf ) { const volScalarField& rDeltaT = localRDeltaT(); const word ddtName("ddt(" + vf.name() + ')'); return tmp<GeometricField<Type, fvPatchField, volMesh>> ( GeometricField<Type, fvPatchField, volMesh>::New ( ddtName, rDeltaT*(vf - vf.oldTime()) ) ); } template<class Type> tmp<GeometricField<Type, fvPatchField, volMesh>> localEulerDdtScheme<Type>::fvcDdt ( const dimensionedScalar& rho, const GeometricField<Type, fvPatchField, volMesh>& vf ) { const volScalarField& rDeltaT = localRDeltaT(); const word ddtName("ddt(" + rho.name() + ',' + vf.name() + ')'); return tmp<GeometricField<Type, fvPatchField, volMesh>> ( GeometricField<Type, fvPatchField, volMesh>::New ( ddtName, rDeltaT*rho*(vf - vf.oldTime()) ) ); } template<class Type> tmp<GeometricField<Type, fvPatchField, volMesh>> localEulerDdtScheme<Type>::fvcDdt ( const volScalarField& rho, const GeometricField<Type, fvPatchField, volMesh>& vf ) { const volScalarField& rDeltaT = localRDeltaT(); const word ddtName("ddt(" + rho.name() + ',' + vf.name() + ')'); return tmp<GeometricField<Type, fvPatchField, volMesh>> ( GeometricField<Type, fvPatchField, volMesh>::New ( ddtName, rDeltaT*(rho*vf - rho.oldTime()*vf.oldTime()) ) ); } template<class Type> tmp<GeometricField<Type, fvPatchField, volMesh>> localEulerDdtScheme<Type>::fvcDdt ( const volScalarField& alpha, const volScalarField& rho, const GeometricField<Type, fvPatchField, volMesh>& vf ) { const volScalarField& rDeltaT = localRDeltaT(); const word ddtName("ddt("+alpha.name()+','+rho.name()+','+vf.name()+')'); return tmp<GeometricField<Type, fvPatchField, volMesh>> ( GeometricField<Type, fvPatchField, volMesh>::New ( ddtName, rDeltaT *( alpha*rho*vf - alpha.oldTime()*rho.oldTime()*vf.oldTime() ) ) ); } template<class Type> tmp<GeometricField<Type, fvsPatchField, surfaceMesh>> localEulerDdtScheme<Type>::fvcDdt ( const GeometricField<Type, fvsPatchField, surfaceMesh>& sf ) { const surfaceScalarField& rDeltaT = localRDeltaTf(); const word ddtName("ddt("+sf.name()+')'); return GeometricField<Type, fvsPatchField, surfaceMesh>::New ( ddtName, rDeltaT*(sf - sf.oldTime()) ); } template<class Type> tmp<fvMatrix<Type>> localEulerDdtScheme<Type>::fvmDdt ( const GeometricField<Type, fvPatchField, volMesh>& vf ) { tmp<fvMatrix<Type>> tfvm ( new fvMatrix<Type> ( vf, vf.dimensions()*dimVol/dimTime ) ); fvMatrix<Type>& fvm = tfvm.ref(); const scalarField& rDeltaT = localRDeltaT(); fvm.diag() = rDeltaT*mesh().Vsc(); fvm.source() = rDeltaT*vf.oldTime().primitiveField()*mesh().Vsc(); return tfvm; } template<class Type> tmp<fvMatrix<Type>> localEulerDdtScheme<Type>::fvmDdt ( const dimensionedScalar& rho, const GeometricField<Type, fvPatchField, volMesh>& vf ) { tmp<fvMatrix<Type>> tfvm ( new fvMatrix<Type> ( vf, rho.dimensions()*vf.dimensions()*dimVol/dimTime ) ); fvMatrix<Type>& fvm = tfvm.ref(); const scalarField& rDeltaT = localRDeltaT(); fvm.diag() = rDeltaT*rho.value()*mesh().Vsc(); fvm.source() = rDeltaT*rho.value()*vf.oldTime().primitiveField()*mesh().Vsc(); return tfvm; } template<class Type> tmp<fvMatrix<Type>> localEulerDdtScheme<Type>::fvmDdt ( const volScalarField& rho, const GeometricField<Type, fvPatchField, volMesh>& vf ) { tmp<fvMatrix<Type>> tfvm ( new fvMatrix<Type> ( vf, rho.dimensions()*vf.dimensions()*dimVol/dimTime ) ); fvMatrix<Type>& fvm = tfvm.ref(); const scalarField& rDeltaT = localRDeltaT(); fvm.diag() = rDeltaT*rho.primitiveField()*mesh().Vsc(); fvm.source() = rDeltaT *rho.oldTime().primitiveField() *vf.oldTime().primitiveField()*mesh().Vsc(); return tfvm; } template<class Type> tmp<fvMatrix<Type>> localEulerDdtScheme<Type>::fvmDdt ( const volScalarField& alpha, const volScalarField& rho, const GeometricField<Type, fvPatchField, volMesh>& vf ) { tmp<fvMatrix<Type>> tfvm ( new fvMatrix<Type> ( vf, alpha.dimensions()*rho.dimensions()*vf.dimensions()*dimVol/dimTime ) ); fvMatrix<Type>& fvm = tfvm.ref(); const scalarField& rDeltaT = localRDeltaT(); fvm.diag() = rDeltaT*alpha.primitiveField()*rho.primitiveField()*mesh().Vsc(); fvm.source() = rDeltaT *alpha.oldTime().primitiveField() *rho.oldTime().primitiveField() *vf.oldTime().primitiveField()*mesh().Vsc(); return tfvm; } /* // Courant number limited formulation template<class Type> tmp<surfaceScalarField> localEulerDdtScheme<Type>::fvcDdtPhiCoeff ( const GeometricField<Type, fvPatchField, volMesh>& U, const fluxFieldType& phi, const fluxFieldType& phiCorr ) { // Courant number limited formulation tmp<surfaceScalarField> tddtCouplingCoeff = scalar(1) - min ( mag(phiCorr)*mesh().deltaCoeffs() /(fvc::interpolate(localRDeltaT())*mesh().magSf()), scalar(1) ); surfaceScalarField& ddtCouplingCoeff = tddtCouplingCoeff.ref(); surfaceScalarField::Boundary& ccbf = ddtCouplingCoeff.boundaryFieldRef(); forAll(U.boundaryField(), patchi) { if ( U.boundaryField()[patchi].fixesValue() || isA<cyclicAMIFvPatch>(mesh().boundary()[patchi]) ) { ccbf[patchi] = 0.0; } } if (debug > 1) { InfoInFunction << "ddtCouplingCoeff mean max min = " << gAverage(ddtCouplingCoeff.primitiveField()) << " " << gMax(ddtCouplingCoeff.primitiveField()) << " " << gMin(ddtCouplingCoeff.primitiveField()) << endl; } return tddtCouplingCoeff; } */ template<class Type> tmp<typename localEulerDdtScheme<Type>::fluxFieldType> localEulerDdtScheme<Type>::fvcDdtUfCorr ( const GeometricField<Type, fvPatchField, volMesh>& U, const GeometricField<Type, fvsPatchField, surfaceMesh>& Uf ) { const surfaceScalarField rDeltaT(fvc::interpolate(localRDeltaT())); fluxFieldType phiUf0(mesh().Sf() & Uf.oldTime()); fluxFieldType phiCorr ( phiUf0 - fvc::dotInterpolate(mesh().Sf(), U.oldTime()) ); return tmp<fluxFieldType> ( new fluxFieldType ( IOobject ( "ddtCorr(" + U.name() + ',' + Uf.name() + ')', mesh().time().timeName(), mesh() ), this->fvcDdtPhiCoeff(U.oldTime(), phiUf0, phiCorr) *rDeltaT*phiCorr ) ); } template<class Type> tmp<typename localEulerDdtScheme<Type>::fluxFieldType> localEulerDdtScheme<Type>::fvcDdtPhiCorr ( const GeometricField<Type, fvPatchField, volMesh>& U, const fluxFieldType& phi ) { const surfaceScalarField rDeltaT(fvc::interpolate(localRDeltaT())); fluxFieldType phiCorr ( phi.oldTime() - fvc::dotInterpolate(mesh().Sf(), U.oldTime()) ); return tmp<fluxFieldType> ( new fluxFieldType ( IOobject ( "ddtCorr(" + U.name() + ',' + phi.name() + ')', mesh().time().timeName(), mesh() ), this->fvcDdtPhiCoeff(U.oldTime(), phi.oldTime(), phiCorr) *rDeltaT*phiCorr ) ); } template<class Type> tmp<typename localEulerDdtScheme<Type>::fluxFieldType> localEulerDdtScheme<Type>::fvcDdtUfCorr ( const volScalarField& rho, const GeometricField<Type, fvPatchField, volMesh>& U, const GeometricField<Type, fvsPatchField, surfaceMesh>& Uf ) { const surfaceScalarField rDeltaT(fvc::interpolate(localRDeltaT())); if ( U.dimensions() == dimVelocity && Uf.dimensions() == dimDensity*dimVelocity ) { GeometricField<Type, fvPatchField, volMesh> rhoU0 ( rho.oldTime()*U.oldTime() ); fluxFieldType phiUf0(mesh().Sf() & Uf.oldTime()); fluxFieldType phiCorr(phiUf0 - fvc::dotInterpolate(mesh().Sf(), rhoU0)); return tmp<fluxFieldType> ( new fluxFieldType ( IOobject ( "ddtCorr(" + rho.name() + ',' + U.name() + ',' + Uf.name() + ')', mesh().time().timeName(), mesh() ), this->fvcDdtPhiCoeff(rhoU0, phiUf0, phiCorr, rho.oldTime()) *rDeltaT*phiCorr ) ); } else if ( U.dimensions() == dimDensity*dimVelocity && Uf.dimensions() == dimDensity*dimVelocity ) { fluxFieldType phiUf0(mesh().Sf() & Uf.oldTime()); fluxFieldType phiCorr ( phiUf0 - fvc::dotInterpolate(mesh().Sf(), U.oldTime()) ); return tmp<fluxFieldType> ( new fluxFieldType ( IOobject ( "ddtCorr(" + rho.name() + ',' + U.name() + ',' + Uf.name() + ')', mesh().time().timeName(), mesh() ), this->fvcDdtPhiCoeff ( U.oldTime(), phiUf0, phiCorr, rho.oldTime() )*rDeltaT*phiCorr ) ); } else { FatalErrorInFunction << "dimensions of Uf are not correct" << abort(FatalError); return fluxFieldType::null(); } } template<class Type> tmp<typename localEulerDdtScheme<Type>::fluxFieldType> localEulerDdtScheme<Type>::fvcDdtPhiCorr ( const volScalarField& rho, const GeometricField<Type, fvPatchField, volMesh>& U, const fluxFieldType& phi ) { const surfaceScalarField rDeltaT(fvc::interpolate(localRDeltaT())); if ( U.dimensions() == dimVelocity && phi.dimensions() == rho.dimensions()*dimFlux ) { GeometricField<Type, fvPatchField, volMesh> rhoU0 ( rho.oldTime()*U.oldTime() ); fluxFieldType phiCorr ( phi.oldTime() - fvc::dotInterpolate(mesh().Sf(), rhoU0) ); return tmp<fluxFieldType> ( new fluxFieldType ( IOobject ( "ddtCorr(" + rho.name() + ',' + U.name() + ',' + phi.name() + ')', mesh().time().timeName(), mesh() ), this->fvcDdtPhiCoeff ( rhoU0, phi.oldTime(), phiCorr, rho.oldTime() )*rDeltaT*phiCorr ) ); } else if ( U.dimensions() == rho.dimensions()*dimVelocity && phi.dimensions() == rho.dimensions()*dimFlux ) { fluxFieldType phiCorr ( phi.oldTime() - fvc::dotInterpolate(mesh().Sf(), U.oldTime()) ); return tmp<fluxFieldType> ( new fluxFieldType ( IOobject ( "ddtCorr(" + rho.name() + ',' + U.name() + ',' + phi.name() + ')', mesh().time().timeName(), mesh() ), this->fvcDdtPhiCoeff ( U.oldTime(), phi.oldTime(), phiCorr, rho.oldTime() )*rDeltaT*phiCorr ) ); } else { FatalErrorInFunction << "dimensions of phi are not correct" << abort(FatalError); return fluxFieldType::null(); } } template<class Type> tmp<surfaceScalarField> localEulerDdtScheme<Type>::meshPhi ( const GeometricField<Type, fvPatchField, volMesh>& ) { return surfaceScalarField::New ( "meshPhi", mesh(), dimensionedScalar(dimVolume/dimTime, 0) ); } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace fv // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace Foam // ************************************************************************* //
OpenFOAM/OpenFOAM-dev
src/finiteVolume/finiteVolume/ddtSchemes/localEulerDdtScheme/localEulerDdtScheme.C
C++
gpl-3.0
15,508
package org.emdev.ui.uimanager; import android.annotation.TargetApi; import android.app.Activity; import android.app.ActivityManager; import android.app.ActivityManager.RunningServiceInfo; import android.content.ComponentName; import android.content.Context; import android.view.View; import android.view.Window; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.StringWriter; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import org.emdev.BaseDroidApp; @TargetApi(11) public class UIManager3x implements IUIManager { private static final String SYS_UI_CLS = "com.android.systemui.SystemUIService"; private static final String SYS_UI_PKG = "com.android.systemui"; private static final ComponentName SYS_UI = new ComponentName(SYS_UI_PKG, SYS_UI_CLS); private static final String SU_PATH1 = "/system/bin/su"; private static final String SU_PATH2 = "/system/xbin/su"; private static final String AM_PATH = "/system/bin/am"; private static final Map<ComponentName, Data> data = new HashMap<ComponentName, Data>() { /** * */ private static final long serialVersionUID = -6627308913610357179L; @Override public Data get(final Object key) { Data existing = super.get(key); if (existing == null) { existing = new Data(); put((ComponentName) key, existing); } return existing; } }; @Override public void setTitleVisible(final Activity activity, final boolean visible, final boolean firstTime) { if (firstTime) { try { final Window window = activity.getWindow(); window.requestFeature(Window.FEATURE_ACTION_BAR); window.requestFeature(Window.FEATURE_INDETERMINATE_PROGRESS); activity.setProgressBarIndeterminate(true); activity.setProgressBarIndeterminateVisibility(true); window.setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS, 1); } catch (final Throwable th) { LCTX.e("Error on requestFeature call: " + th.getMessage()); } } try { if (visible) { activity.getActionBar().show(); } else { activity.getActionBar().hide(); } data.get(activity.getComponentName()).titleVisible = visible; } catch (final Throwable th) { LCTX.e("Error on requestFeature call: " + th.getMessage()); } } @Override public boolean isTitleVisible(final Activity activity) { return data.get(activity.getComponentName()).titleVisible; } @Override public void setProgressSpinnerVisible(Activity activity, boolean visible) { activity.setProgressBarIndeterminateVisibility(visible); activity.getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS, visible ? 1 : 0); } @Override public void setFullScreenMode(final Activity activity, final View view, final boolean fullScreen) { data.get(activity.getComponentName()).fullScreen = fullScreen; if (fullScreen) { stopSystemUI(activity); } else { startSystemUI(activity); } } @Override public void openOptionsMenu(final Activity activity, final View view) { activity.openOptionsMenu(); } @Override public void invalidateOptionsMenu(final Activity activity) { activity.invalidateOptionsMenu(); } @Override public void onMenuOpened(final Activity activity) { if (data.get(activity.getComponentName()).fullScreen && data.get(activity.getComponentName()).fullScreenState.get()) { startSystemUI(activity); } } @Override public void onMenuClosed(final Activity activity) { if (data.get(activity.getComponentName()).fullScreen && !data.get(activity.getComponentName()).fullScreenState.get()) { stopSystemUI(activity); } } @Override public void onPause(final Activity activity) { if (data.get(activity.getComponentName()).fullScreen && data.get(activity.getComponentName()).fullScreenState.get()) { startSystemUI(activity); } } @Override public void onResume(final Activity activity) { if (data.get(activity.getComponentName()).fullScreen && !data.get(activity.getComponentName()).fullScreenState.get()) { stopSystemUI(activity); } } @Override public void onDestroy(final Activity activity) { if (data.get(activity.getComponentName()).fullScreen && data.get(activity.getComponentName()).fullScreenState.get()) { startSystemUI(activity); } } @Override public boolean isTabletUi(final Activity activity) { return true; } protected void startSystemUI(final Activity activity) { if (isSystemUIRunning()) { data.get(activity.getComponentName()).fullScreenState.set(false); return; } exec(false, activity, AM_PATH, "startservice", "-n", SYS_UI.flattenToString()); } protected void stopSystemUI(final Activity activity) { if (!isSystemUIRunning()) { data.get(activity.getComponentName()).fullScreenState.set(true); return; } final String su = getSuPath(); if (su == null) { data.get(activity.getComponentName()).fullScreenState.set(false); return; } exec(true, activity, su, "-c", "service call activity 79 s16 " + SYS_UI_PKG); } protected boolean isSystemUIRunning() { final Context ctx = BaseDroidApp.context; final ActivityManager am = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE); final List<RunningServiceInfo> rsiList = am.getRunningServices(1000); for (final RunningServiceInfo rsi : rsiList) { LCTX.d("Service: " + rsi.service); if (SYS_UI.equals(rsi.service)) { LCTX.e("System UI service found"); return true; } } return false; } protected void exec(final boolean expected, final Activity activity, final String... as) { (new Thread(new Runnable() { @Override public void run() { try { final boolean result = execImpl(as); data.get(activity.getComponentName()).fullScreenState.set(result ? expected : !expected); } catch (final Throwable th) { LCTX.e("Changing full screen mode failed: " + th.getCause()); data.get(activity.getComponentName()).fullScreenState.set(!expected); } } })).start(); } private boolean execImpl(final String... as) { try { LCTX.d("Execute: " + Arrays.toString(as)); final Process process = Runtime.getRuntime().exec(as); final InputStreamReader r = new InputStreamReader(process.getInputStream()); final StringWriter w = new StringWriter(); final char ac[] = new char[8192]; int i = 0; do { i = r.read(ac); if (i > 0) { w.write(ac, 0, i); } } while (i != -1); r.close(); process.waitFor(); final int exitValue = process.exitValue(); final String text = w.toString(); LCTX.d("Result code: " + exitValue); LCTX.d("Output:\n" + text); return 0 == exitValue; } catch (final IOException e) { throw new IllegalStateException(e); } catch (final InterruptedException e) { throw new IllegalStateException(e); } } private static String getSuPath() { final File su1 = new File(SU_PATH1); if (su1.exists() && su1.isFile() && su1.canExecute()) { return SU_PATH1; } final File su2 = new File(SU_PATH2); if (su2.exists() && su2.isFile() && su2.canExecute()) { return SU_PATH2; } return null; } private static class Data { boolean fullScreen = false; boolean titleVisible = true; final AtomicBoolean fullScreenState = new AtomicBoolean(); } }
bonisamber/bookreader
Application/src/main/java/org/emdev/ui/uimanager/UIManager3x.java
Java
gpl-3.0
8,692
/** Copyright 2012 John Cummens (aka Shadowmage, Shadowmage4513) This software is distributed under the terms of the GNU General Public License. Please see COPYING for precise license information. This file is part of Ancient Warfare. Ancient Warfare 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. Ancient Warfare 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 Ancient Warfare. If not, see <http://www.gnu.org/licenses/>. */ package shadowmage.ancient_warfare.common.vehicles.types; import net.minecraft.block.Block; import net.minecraft.item.Item; import shadowmage.ancient_warfare.common.config.Config; import shadowmage.ancient_warfare.common.item.ItemLoader; import shadowmage.ancient_warfare.common.registry.ArmorRegistry; import shadowmage.ancient_warfare.common.registry.VehicleUpgradeRegistry; import shadowmage.ancient_warfare.common.research.ResearchGoal; import shadowmage.ancient_warfare.common.utils.ItemStackWrapperCrafting; import shadowmage.ancient_warfare.common.vehicles.VehicleBase; import shadowmage.ancient_warfare.common.vehicles.VehicleMovementType; import shadowmage.ancient_warfare.common.vehicles.VehicleVarHelpers.BallistaVarHelper; import shadowmage.ancient_warfare.common.vehicles.helpers.VehicleFiringVarsHelper; import shadowmage.ancient_warfare.common.vehicles.materials.VehicleMaterial; import shadowmage.ancient_warfare.common.vehicles.missiles.Ammo; public class VehicleTypeBoatBallista extends VehicleType { /** * @param typeNum */ public VehicleTypeBoatBallista(int typeNum) { super(typeNum); this.configName = "boat_ballista"; this.vehicleMaterial = VehicleMaterial.materialWood; this.materialCount = 5; this.movementType = VehicleMovementType.WATER; this.maxMissileWeight = 2.f; this.validAmmoTypes.add(Ammo.ammoBallistaBolt); this.validAmmoTypes.add(Ammo.ammoBallistaBoltFlame); this.validAmmoTypes.add(Ammo.ammoBallistaBoltExplosive); this.validAmmoTypes.add(Ammo.ammoBallistaBoltIron); this.ammoBySoldierRank.put(0, Ammo.ammoBallistaBolt); this.ammoBySoldierRank.put(1, Ammo.ammoBallistaBolt); this.ammoBySoldierRank.put(2, Ammo.ammoBallistaBoltFlame); this.validUpgrades.add(VehicleUpgradeRegistry.speedUpgrade); this.validUpgrades.add(VehicleUpgradeRegistry.pitchDownUpgrade); this.validUpgrades.add(VehicleUpgradeRegistry.pitchUpUpgrade); this.validUpgrades.add(VehicleUpgradeRegistry.pitchExtUpgrade); this.validUpgrades.add(VehicleUpgradeRegistry.powerUpgrade); this.validUpgrades.add(VehicleUpgradeRegistry.reloadUpgrade); this.validUpgrades.add(VehicleUpgradeRegistry.aimUpgrade); this.validArmors.add(ArmorRegistry.armorStone); this.validArmors.add(ArmorRegistry.armorObsidian); this.validArmors.add(ArmorRegistry.armorIron); this.armorBaySize = 3; this.upgradeBaySize = 3; this.ammoBaySize = 6; this.storageBaySize = 0; this.addNeededResearchForMaterials(); this.addNeededResearch(0, ResearchGoal.vehicleTorsion1); this.addNeededResearch(1, ResearchGoal.vehicleTorsion2); this.addNeededResearch(2, ResearchGoal.vehicleTorsion3); this.addNeededResearch(3, ResearchGoal.vehicleTorsion4); this.addNeededResearch(4, ResearchGoal.vehicleTorsion5); this.addNeededResearch(0, ResearchGoal.vehicleMobility1); this.addNeededResearch(1, ResearchGoal.vehicleMobility2); this.addNeededResearch(2, ResearchGoal.vehicleMobility3); this.addNeededResearch(3, ResearchGoal.vehicleMobility4); this.addNeededResearch(4, ResearchGoal.vehicleMobility5); this.addNeededResearch(0, ResearchGoal.upgradeMechanics1); this.addNeededResearch(1, ResearchGoal.upgradeMechanics2); this.addNeededResearch(2, ResearchGoal.upgradeMechanics3); this.addNeededResearch(3, ResearchGoal.upgradeMechanics4); this.addNeededResearch(4, ResearchGoal.upgradeMechanics5); this.additionalMaterials.add(new ItemStackWrapperCrafting(Item.silk, 8, false, false)); this.additionalMaterials.add(new ItemStackWrapperCrafting(ItemLoader.torsionUnit, 2, false, false)); this.additionalMaterials.add(new ItemStackWrapperCrafting(ItemLoader.equipmentBay, 1, false, false)); this.additionalMaterials.add(new ItemStackWrapperCrafting(ItemLoader.mobilityUnit, 1, false, false)); this.additionalMaterials.add(new ItemStackWrapperCrafting(Block.cactus, 2, false, false)); this.width = 2.7f; this.height = 1.4f; this.baseStrafeSpeed = 2.f; this.baseForwardSpeed = 6.2f*0.05f; this.turretForwardsOffset = 23*0.0625f; this.turretVerticalOffset = 1.325f; this.accuracy = 0.98f; this.basePitchMax = 15; this.basePitchMin = -15; this.baseMissileVelocityMax = 42.f;//stand versions should have higher velocity, as should fixed version--i.e. mobile turret should have the worst of all versions this.riderForwardsOffset = -1.0f ; this.riderVerticalOffset = 0.7f; this.shouldRiderSit = true; this.isMountable = true; this.isDrivable = true;//adjust based on isMobile or not this.isCombatEngine = true; this.canAdjustPitch = true; this.canAdjustPower = false; this.canAdjustYaw = true; this.turretRotationMax=360.f;//adjust based on mobile/stand fixed (0), stand fixed(90'), or mobile or stand turret (360) this.displayName = "item.vehicleSpawner.18"; this.displayTooltip.add("item.vehicleSpawner.tooltip.torsion"); this.displayTooltip.add("item.vehicleSpawner.tooltip.boat"); this.displayTooltip.add("item.vehicleSpawner.tooltip.fullturret"); } @Override public String getTextureForMaterialLevel(int level) { switch(level) { case 0: return Config.texturePath + "models/boatBallista1.png"; case 1: return Config.texturePath + "models/boatBallista2.png"; case 2: return Config.texturePath + "models/boatBallista3.png"; case 3: return Config.texturePath + "models/boatBallista4.png"; case 4: return Config.texturePath + "models/boatBallista5.png"; default: return Config.texturePath + "models/boatBallista1.png"; } } @Override public VehicleFiringVarsHelper getFiringVarsHelper(VehicleBase veh) { return new BallistaVarHelper(veh); } }
shadowmage45/AncientWarfare
AncientWarfare/src/shadowmage/ancient_warfare/common/vehicles/types/VehicleTypeBoatBallista.java
Java
gpl-3.0
6,768
/** * @file udp_socket.c * @author Ricardo Tubío (rtpardavila[at]gmail.com) * @version 0.1 * * @section LICENSE * * This file is part of udpip-broadcaster. * udpip-broadcaster 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. * * udpip-broadcaster 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 udpip-broadcaster. If not, see <http://www.gnu.org/licenses/>. */ #include "udp_socket.h" /* new_ifreq */ ifreq_t *new_ifreq() { ifreq_t *s = NULL; if ( ( s = (ifreq_t *)malloc(LEN__IFREQ) ) == NULL ) { handle_sys_error("new_ifreq: <malloc> returns NULL.\n"); } if ( memset(s, 0, LEN__IFREQ) == NULL ) { handle_sys_error("new_ifreq: <memset> returns NULL.\n"); } return(s); } /* init_ifreq */ ifreq_t *init_ifreq(const char *if_name) { ifreq_t *s = new_ifreq(); int if_name_len = 0; int ifr_name_len = sizeof(s->ifr_name); if ( ( if_name_len = strlen(if_name) ) < 0 ) { handle_sys_error("init_ifreq: <strlen> returns < 0.\n"); } if ( if_name_len > ifr_name_len ) { handle_app_error("init_ifreq: if_name's length bigger than ifr's " \ "buffer.\n"); } if ( strncpy(s->ifr_name, if_name, if_name_len) == NULL ) { handle_sys_error("init_ifreq: <strncpy> returns NULL.\n"); } return(s); } /* new_sockaddr */ sockaddr_t *new_sockaddr() { sockaddr_t *s = NULL; if ( ( s = (sockaddr_t *)malloc(LEN__SOCKADDR) ) == NULL ) { handle_sys_error("new_sockaddr: <malloc> returns NULL.\n"); } if ( memset(s, 0, LEN__SOCKADDR) == NULL ) { handle_sys_error("new_sockaddr: <memset> returns NULL.\n"); } return(s); } /* new_sockaddr_in */ sockaddr_in_t *new_sockaddr_in() { sockaddr_in_t *s = NULL; if ( ( s = (sockaddr_in_t *)malloc(LEN__SOCKADDR_IN) ) == NULL ) { handle_sys_error("new_sockaddr_in: <malloc> returns NULL.\n"); } if ( memset(s, 0, LEN__SOCKADDR) == NULL ) { handle_sys_error("new_sockaddr_in: <memset> returns NULL.\n"); } return(s); } /* new_iovec */ iovec_t *new_iovec() { iovec_t *s = NULL; if ( ( s = (iovec_t *)malloc(LEN__IOVEC) ) == NULL ) { handle_sys_error("new_iovec: <malloc> returns NULL.\n"); } if ( memset(s, 0, LEN__IOVEC) == NULL ) { handle_sys_error("new_iovec: <memset> returns NULL.\n"); } return(s); } /* new_msg_header */ msg_header_t *new_msg_header() { msg_header_t *s = NULL; if ( ( s = (msg_header_t *)malloc(LEN__MSG_HEADER) ) == NULL ) { handle_sys_error("new_msg_header: <malloc> returns NULL.\n"); } if ( memset(s, 0, LEN__MSG_HEADER) == NULL ) { handle_sys_error("new_msg_header: <memset> returns NULL.\n"); } if ( ( s->msg_control = malloc(CONTROL_BUFFER_LEN) ) == NULL ) { handle_sys_error("init_msg_header: <malloc> returns NULL.\n"); } if ( memset(s->msg_control, 0, CONTROL_BUFFER_LEN) == NULL ) { handle_sys_error("init_msg_header: <memset> returns NULL.\n"); } s->msg_controllen = CONTROL_BUFFER_LEN; s->msg_flags = 0; s->msg_name = new_sockaddr_in(); s->msg_namelen = LEN__SOCKADDR_IN; s->msg_iov = new_iovec(); s->msg_iovlen = 0; return(s); } /* init_msg_header */ msg_header_t *init_msg_header(void* buffer, const int buffer_len) { msg_header_t *s = new_msg_header(); s->msg_iovlen = 1; s->msg_iov->iov_base = buffer; s->msg_iov->iov_len = buffer_len; return(s); } /* init_broadcast_sockaddr_in */ sockaddr_in_t *init_broadcast_sockaddr_in(const int port) { sockaddr_in_t *s = new_sockaddr_in(); s->sin_family = AF_INET; s->sin_port = (in_port_t)htons(port); s->sin_addr.s_addr = htonl(INADDR_BROADCAST); return(s); } /* init_any_sockaddr_in */ sockaddr_in_t *init_any_sockaddr_in(const int port) { sockaddr_in_t *s = new_sockaddr_in(); s->sin_family = AF_INET; s->sin_port = (in_port_t)htons(port); s->sin_addr.s_addr = htonl(INADDR_ANY); return(s); } /* init_sockaddr_in */ sockaddr_in_t *init_sockaddr_in(const char *address, const int port) { sockaddr_in_t *s = new_sockaddr_in(); s->sin_family = AF_INET; s->sin_port = (in_port_t)htons(port); printf("8\n"); // if ( ( s->sin_addr.s_addr = inet_addr(address) ) < 0 ) // { // // printf("entro no erro\n"); // perror("init_sockaddr_in: " \ // "<inet_addr> returns error.\n"); } printf("9\n"); return(s); } /* init_if_sockaddr_in */ sockaddr_in_t *init_if_sockaddr_in(const char *if_name, const int port) { sockaddr_in_t *s = NULL; struct ifaddrs *ifaddr, *ifa; int i; char host[NI_MAXHOST]; bool if_found = false; if ( getifaddrs(&ifaddr) < 0 ) { handle_sys_error("init_if_sockaddr_in: " \ "<getifaddrs> returned error. Error: "); } for ( ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next ) { if ( ifa->ifa_addr == NULL ) { continue; } i = getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in) , host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST); if ( ( strcmp(ifa->ifa_name,if_name) == 0 ) && ( ifa->ifa_addr->sa_family == AF_INET ) ) { if ( i != 0 ) { handle_app_error("init_if_sockaddr_in: " \ "<getnameinfo> failed: %s\n" , gai_strerror(i)); } s = init_sockaddr_in(host, port); if_found = true; } } freeifaddrs(ifaddr); if ( if_found == false ) { handle_app_error("Could not get local interface, if_name = %s.\n" , if_name); } return(s); } /* open_receiver_udp_socket */ int open_receiver_udp_socket(const int port) { int fd = -1; // 1) socket creation if ( ( fd = socket(AF_INET, SOCK_DGRAM, 0) ) < 0 ) { handle_sys_error("open_receiver_udp_socket: " \ "<socket> returns error. Description"); } // 2) local address for binding sockaddr_in_t* addr = init_any_sockaddr_in(port); if ( bind(fd, (sockaddr_t *)addr, LEN__SOCKADDR_IN) < 0 ) { handle_sys_error("open_receiver_udp_socket: " \ "<bind> returns error. Description"); } // 3) for analyzing received message's headers if ( set_msghdrs_socket(fd) < 0 ) { handle_app_error("open_receiver_udp_socket: " \ "<set_msghdrs_socket> returns error.\n"); } return(fd); } /* open_transmitter_udp_socket */ int open_transmitter_udp_socket(const int port) { int fd = -1; // 1) socket creation if ( ( fd = socket(AF_INET, SOCK_DGRAM, 0) ) < 0 ) { handle_sys_error("open_udp_socket: <socket> returns error.\n"); } return(fd); } /* open_broadcast_udp_socket */ int open_broadcast_udp_socket(const char *iface, const int port) { int fd = -1; // 1) socket creation if ( ( fd = socket(AF_INET, SOCK_DGRAM, 0) ) < 0 ) { handle_sys_error("open_udp_socket: <socket> returns error.\n"); } // 2) set broadcast socket options if ( set_broadcast_socket(fd) < 0 ) { handle_app_error("open_broadcast_udp_socket: " \ "<set_broadcast_socket> returns error.\n"); } // 3) broadcast socket must be bound to a specific network interface if ( set_bindtodevice_socket(iface, fd) < 0 ) { handle_app_error("open_broadcast_udp_socket: " \ "<set_bindtodevice_socket> returns error.\n"); } printf("saio do open_broadcast_udp_socket\n"); return(fd); } /* set_broadcast_socket */ int set_broadcast_socket(const int socket_fd) { int bcast = 1; if ( setsockopt(socket_fd, SOL_SOCKET, SO_BROADCAST, &bcast, sizeof(int)) < 0 ) { handle_sys_error("set_broadcast_socket: " \ "<setsockopt> returns error."); } return(EX_OK); } /* set_bindtodevice_socket */ int set_bindtodevice_socket(const char *if_name, const int socket_fd) { ifreq_t *ifr = init_ifreq(if_name); if ( setsockopt(socket_fd, SOL_SOCKET, SO_BINDTODEVICE, ifr, LEN__IFREQ) < 0 ) { handle_sys_error("set_bindtodevice_socket: " \ "<setsockopt> returns error"); } return(EX_OK); } /* set_msghdrs_socket */ int set_msghdrs_socket(const int socket_fd) { ifreq_t *ifr = new_ifreq(); if ( setsockopt(socket_fd, IPPROTO_IP, IP_PKTINFO, &ifr, LEN__IFREQ) < 0 ) { handle_sys_error("set_generate_headers: " \ "<setsockopt> returns error"); } return(EX_OK); } /* send_message */ int send_message( const sockaddr_t* dest_addr, const int socket_fd, const void *buffer, const int len ) { int sent_bytes = 0; if ( ( sent_bytes = sendto(socket_fd, buffer, len , 0, dest_addr, LEN__SOCKADDR_IN) ) < 0 ) { log_sys_error("cb_broadcast_sendto (fd=%d): <sendto> ERROR.\n" , socket_fd); getchar(); return(EX_ERR); } if ( sent_bytes < len ) { log_app_msg("send_message: sent %d bytes, requested %d.\n" , sent_bytes, len); return(EX_ERR); } return(sent_bytes); } /* recv_message */ int recv_message(const int socket_fd, void *data) { int rx_bytes = 0; if ( ( rx_bytes = recvfrom(socket_fd, data, UDP_BUFFER_LEN , 0, NULL, NULL) ) < 0 ) { log_sys_error("recv_message: wrong <recvfrom> call. "); return(EX_ERR); } return(rx_bytes); } /* recv_msg */ int recv_msg( const int socket_fd, msg_header_t *msg, const in_addr_t block_ip, bool *blocked ) { int rx_bytes = 0; // 1) read UDP message from network level if ( ( rx_bytes = recvmsg(socket_fd, msg, 0) ) < 0 ) { log_sys_error("recv_msg: wrong <recvmsg> call. "); return(EX_ERR); } in_addr_t src_addr = get_source_address(msg); if ( block_ip == src_addr ) { *blocked = true; } else { *blocked = false; } return(rx_bytes); } /* get_source_address */ in_addr_t get_source_address(msg_header_t *msg) { sockaddr_in_t *src = NULL; // iterate through all the control headers for ( struct cmsghdr *cmsg = CMSG_FIRSTHDR(msg); cmsg != NULL; cmsg = CMSG_NXTHDR(msg, cmsg) ) { // ignore the control headers that don't match what we want if ( ( cmsg->cmsg_level != IPPROTO_IP ) || ( cmsg->cmsg_type != IP_PKTINFO ) ) { continue; } //struct in_pktinfo *pi = CMSG_DATA(cmsg); src = (sockaddr_in_t *)msg->msg_name; break; } return(src->sin_addr.s_addr); } /* print_hex_data */ int print_hex_data(const char *buffer, const int len) { int last_byte = len - 1; if ( len < 0 ) { return(EX_WRONG_PARAM); } for ( int i = 0; i < len; i++ ) { if ( ( i != 0 ) && ( ( i % BYTES_PER_LINE ) == 0 ) ) { log_app_msg("\n\t\t\t"); } log_app_msg("%02X", 0xFF & (unsigned int)buffer[i]); if ( i < last_byte ) { log_app_msg(":"); } } return(EX_OK); } /* print_eth_address */ void print_eth_address(const unsigned char *eth_address) { printf("%02X:%02X:%02X:%02X:%02X:%02X", (unsigned char) eth_address[0], (unsigned char) eth_address[1], (unsigned char) eth_address[2], (unsigned char) eth_address[3], (unsigned char) eth_address[4], (unsigned char) eth_address[5]); }
vieites4/udpip_broadcaster
src/udpev/udp_socket.c
C
gpl-3.0
11,081
<?php $element = $variables['element']; // Special handling for form elements. if (isset($element['#array_parents'])) { // Assign an html ID. if (!isset($element['#attributes']['id'])) { $element['#attributes']['id'] = $element['#id']; } // Add the 'form-wrapper' class. $element['#attributes']['class'][] = 'form-wrapper'; } print '<div' . drupal_attributes($element['#attributes']) . '>' . $element['#children'] . '</div>'; ?>
sistemi-territoriali/StatPortalOpenData
sp-odata/sites/all/modules/spodata/metadata/theme/metadata_tree_filter.tpl.php
PHP
gpl-3.0
462
#pragma strict var playerFinalScore: int; var Users: List.< GameObject >; var userData: GameObject[]; var maxPlayers: int; var gameManager: GameObject; var currentPlayer: int; var currentName: String; function Awake () { //var users :GameObject = GameObject.Find("_UserControllerFB"); userData = GameObject.FindGameObjectsWithTag("Player"); } function Start() { gameManager = GameObject.Find("__GameManager"); NotificationCenter.DefaultCenter().AddObserver(this, "PlayerChanger"); } function Update () { if(Users.Count>0) playerFinalScore = Users[0].GetComponent(_GameManager).playerFinalScore; } function PlayerChanger() { currentPlayer++; for(var i: int; i<Users.Count; i++) { if(i!=currentPlayer)Users[i].SetActive(false); else Users[i].SetActive(true); } print("Change Player"); if(currentPlayer>maxPlayers) currentPlayer=0; } function OnLevelWasLoaded(level: int) { maxPlayers = userData.Length; gameManager = GameObject.Find("__GameManager"); for(var i: int; i< userData.Length; i++) { if(i!=0)Users[i].SetActive(false); Users[i].name = userData[i].name; currentName = Users[0].name; Users[i].transform.parent = gameManager.transform; } }
RomanKorchmenko/BowlingFX
BowlingFX/Assets/ScoreTransfer.js
JavaScript
gpl-3.0
1,210
<fieldset class="animated fadeIn" ng-form="employeeAuthorizationsForm"> <legend class="pull-left width-full">Authorizations</legend> <div class="form-group"> <label class="control-label col-sm-4"> Role&nbsp; <a href="#" tooltip-html="'<b>Employee:</b> An employee has basic viewing access to the schedule. They can facilitate requests on their own shifts, respond to available shifts. <br/> <b>Supervisor:</b> Has same...'"> <i class="fa fa-question-circle"></i> </a> </label> <div class="col-sm-5"> <select name="role" class="form-control" ng-model="vm.employee.role" ng-change="vm.deleteSupervisorLocations()" ng-options="role as role for role in vm.roles"></select> </div> </div> <div class="form-group"> <label class="control-label col-sm-offset-2 col-sm-8 pb5 text-left">Where can this employee work?</label> <div class="col-sm-offset-2 col-sm-8"> <div class="checkbox"> <input id="locationCheckboxes" type="checkbox" ng-model="vm.selectedAllLocations" ng-click="vm.selectAll(vm.selectedAllLocations, 'locations')"/> <label for="locationCheckboxes"><i>select/unselect all</i></label> </div> <hr class="mt5 mb5"/> <ul class="pl0 mb0"> <li ng-repeat="location in vm.locations track by location.id" class="checkbox min-height-0" ng-class="{'pt0': $index !== 0, 'pt5': $index === 0}"> <input id="location_{{$index}}" type="checkbox" ng-checked="vm.employee.locations.indexOf(location.id) > -1" ng-click="vm.toggleSelection(location.id, vm.selectedAllLocations, 'locations')" /> <label for="location_{{$index}}">{{location.name}}</label> </li> </ul> </div> </div> <div class="form-group" ng-show="vm.employee.role === vm.roles[1]"> <label class="control-label col-sm-offset-2 col-sm-8 pb5 text-left">Which locations can this supervisor manage?</label> <div class="col-sm-offset-2 col-sm-8"> <div class="checkbox"> <input id="supervisorLocationCheckboxes" type="checkbox" ng-model="vm.selectedAllSupervisorLocations" ng-click="vm.selectAll(vm.selectedAllSupervisorLocations, 'supervisorLocations')"/> <label for="supervisorLocationCheckboxes"><i>select/unselect all</i></label> </div> <hr class="mt5 mb5"/> <ul class="pl0 mb0"> <li ng-repeat="location in vm.locations track by location.id" class="checkbox min-height-0" ng-class="{'pt0': $index !== 0, 'pt5': $index === 0}"> <input id="supervisor_location_{{$index}}" type="checkbox" ng-checked="vm.employee.supervisorLocations.indexOf(location.id) > -1" ng-click="vm.toggleSelection(location.id, vm.selectedAllSupervisorLocations, 'supervisorLocations')" /> <label for="supervisor_location_{{$index}}">{{location.name}}</label> </li> </ul> </div> </div> </fieldset>
martinmicunda/employee-scheduling-ui
src/app/components/employee-authorizations/employee-authorizations.html
HTML
gpl-3.0
3,285
package com.andyadc.concurrency.latch; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.concurrent.*; /** * @author andaicheng * @version 2017/3/10 */ public class LatchDemo_1 { public static void main(String[] args) throws Exception { int num = 10; //发令枪只只响一次 CountDownLatch begin = new CountDownLatch(1); //参与跑步人数 CountDownLatch end = new CountDownLatch(num); ExecutorService es = Executors.newFixedThreadPool(num); //记录跑步成绩 List<Future<Integer>> futures = new ArrayList<>(); for (int i = 0; i < num; i++) { futures.add(es.submit(new Runner(begin, end))); } //预备 TimeUnit.SECONDS.sleep(10); //发令枪响 begin.countDown(); //等待跑者跑完 end.await(); int sum = 0; for (Future<Integer> f : futures) { sum += f.get(); } System.out.println("平均分数: " + (float) (sum / num)); } } class Runner implements Callable<Integer> { //开始信号 private CountDownLatch begin; //结束信号 private CountDownLatch end; public Runner(CountDownLatch begin, CountDownLatch end) { this.begin = begin; this.end = end; } @Override public Integer call() throws Exception { //跑步成绩 int score = new Random().nextInt(10); //等待发令枪响 begin.await(); TimeUnit.SECONDS.sleep(score); //跑步结束 end.countDown(); System.out.println("score:" + score); return score; } }
andyadc/java-study
concurrency-study/src/main/java/com/andyadc/concurrency/latch/LatchDemo_1.java
Java
gpl-3.0
1,769
# TimeBombs A plugin that allows players to drop item bombs that blow up in a configurable time and strength! [Spigot page](https://www.spigotmc.org/resources/timebombs.19012) **|** [Plugin jar download](http://shortninja.net/files/TimeBombs.jar)
Shortninja66/TimeBombs
README.md
Markdown
gpl-3.0
248
package com.infamous.performance.activities; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Bundle; import android.os.SystemClock; import android.preference.PreferenceManager; import android.view.View; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import com.infamous.performance.R; import com.infamous.performance.util.ActivityThemeChangeInterface; import com.infamous.performance.util.Constants; import com.infamous.performance.util.Helpers; /** * Created by h0rn3t on 09.02.2014. * http://forum.xda-developers.com/member.php?u=4674443 */ public class checkSU extends Activity implements Constants, ActivityThemeChangeInterface { private boolean mIsLightTheme; private ProgressBar wait; private TextView info; private ImageView attn; SharedPreferences mPreferences; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mPreferences = PreferenceManager.getDefaultSharedPreferences(this); setTheme(); setContentView(R.layout.check_su); wait=(ProgressBar) findViewById(R.id.wait); info=(TextView) findViewById(R.id.info); attn=(ImageView) findViewById(R.id.attn); if(mPreferences.getBoolean("booting",false)) { info.setText(getString(R.string.boot_wait)); wait.setVisibility(View.GONE); attn.setVisibility(View.VISIBLE); } else { new TestSU().execute(); } } private class TestSU extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... params) { SystemClock.sleep(1000); final Boolean canSu = Helpers.checkSu(); final Boolean canBb = Helpers.binExist("busybox")!=null; if (canSu && canBb) return "ok"; else return "nok"; } @Override protected void onPostExecute(String result) { if(result.equals("nok")){ //mPreferences.edit().putBoolean("firstrun", true).commit(); info.setText(getString(R.string.su_failed_su_or_busybox)); wait.setVisibility(View.GONE); attn.setVisibility(View.VISIBLE); } else{ //mPreferences.edit().putBoolean("firstrun", false).commit(); Intent returnIntent = new Intent(); returnIntent.putExtra("r",result); setResult(RESULT_OK,returnIntent); finish(); } } @Override protected void onPreExecute() { } @Override protected void onProgressUpdate(Void... values) { } } @Override public boolean isThemeChanged() { final boolean is_light_theme = mPreferences.getBoolean(PREF_USE_LIGHT_THEME, false); return is_light_theme != mIsLightTheme; } @Override public void setTheme() { final boolean is_light_theme = mPreferences.getBoolean(PREF_USE_LIGHT_THEME, false); mIsLightTheme = is_light_theme; setTheme(is_light_theme ? R.style.Theme_Light : R.style.Theme_Dark); } @Override public void onResume() { super.onResume(); } }
InfamousProductions/Infamous_Performance
src/com/infamous/performance/activities/checkSU.java
Java
gpl-3.0
3,396
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define LOG_TAG "Posix" #include "AsynchronousCloseMonitor.h" #include "cutils/log.h" #include "ExecStrings.h" #include "JNIHelp.h" #include "JniConstants.h" #include "JniException.h" #include "NetworkUtilities.h" #include "Portability.h" #include "readlink.h" #include "../../bionic/libc/dns/include/resolv_netid.h" // For android_getaddrinfofornet. #include "ScopedBytes.h" #include "ScopedLocalRef.h" #include "ScopedPrimitiveArray.h" #include "ScopedUtfChars.h" #include "toStringArray.h" #include "UniquePtr.h" #include <arpa/inet.h> #include <errno.h> #include <fcntl.h> #include <net/if.h> #include <netdb.h> #include <netinet/in.h> #include <poll.h> #include <pwd.h> #include <signal.h> #include <stdlib.h> #include <sys/ioctl.h> #include <sys/mman.h> #ifndef __APPLE__ #include <sys/prctl.h> #endif #include <sys/socket.h> #include <sys/stat.h> #ifdef __APPLE__ #include <sys/statvfs.h> #endif #include <sys/syscall.h> #include <sys/time.h> #include <sys/types.h> #include <sys/uio.h> #include <sys/utsname.h> #include <sys/wait.h> #include <termios.h> #include <unistd.h> #ifndef __unused #define __unused __attribute__((__unused__)) #endif #define TO_JAVA_STRING(NAME, EXP) \ jstring NAME = env->NewStringUTF(EXP); \ if (NAME == NULL) return NULL; struct addrinfo_deleter { void operator()(addrinfo* p) const { if (p != NULL) { // bionic's freeaddrinfo(3) crashes when passed NULL. freeaddrinfo(p); } } }; /** * Used to retry networking system calls that can be interrupted with a signal. Unlike * TEMP_FAILURE_RETRY, this also handles the case where * AsynchronousCloseMonitor::signalBlockedThreads(fd) is used to signal a close() or * Thread.interrupt(). Other signals that result in an EINTR result are ignored and the system call * is retried. * * Returns the result of the system call though a Java exception will be pending if the result is * -1: a SocketException if signaled via AsynchronousCloseMonitor, or ErrnoException for other * failures. */ #define NET_FAILURE_RETRY(jni_env, return_type, syscall_name, java_fd, ...) ({ \ return_type _rc = -1; \ do { \ bool _wasSignaled; \ int _syscallErrno; \ { \ int _fd = jniGetFDFromFileDescriptor(jni_env, java_fd); \ AsynchronousCloseMonitor _monitor(_fd); \ _rc = syscall_name(_fd, __VA_ARGS__); \ _syscallErrno = errno; \ _wasSignaled = _monitor.wasSignaled(); \ } \ if (_wasSignaled) { \ jniThrowException(jni_env, "java/net/SocketException", "Socket closed"); \ _rc = -1; \ break; \ } \ if (_rc == -1 && _syscallErrno != EINTR) { \ /* TODO: with a format string we could show the arguments too, like strace(1). */ \ throwErrnoException(jni_env, # syscall_name); \ break; \ } \ } while (_rc == -1); /* _syscallErrno == EINTR && !_wasSignaled */ \ _rc; }) /** * Used to retry system calls that can be interrupted with a signal. Unlike TEMP_FAILURE_RETRY, this * also handles the case where AsynchronousCloseMonitor::signalBlockedThreads(fd) is used to signal * a close() or Thread.interrupt(). Other signals that result in an EINTR result are ignored and the * system call is retried. * * Returns the result of the system call though a Java exception will be pending if the result is * -1: an IOException if the file descriptor is already closed, a InterruptedIOException if signaled * via AsynchronousCloseMonitor, or ErrnoException for other failures. */ #define IO_FAILURE_RETRY(jni_env, return_type, syscall_name, java_fd, ...) ({ \ return_type _rc = -1; \ do { \ bool _wasSignaled; \ int _syscallErrno; \ { \ int _fd = jniGetFDFromFileDescriptor(jni_env, java_fd); \ AsynchronousCloseMonitor _monitor(_fd); \ _rc = syscall_name(_fd, __VA_ARGS__); \ _syscallErrno = errno; \ _wasSignaled = _monitor.wasSignaled(); \ } \ if (_wasSignaled) { \ jniThrowException(jni_env, "java/io/InterruptedIOException", # syscall_name " interrupted"); \ _rc = -1; \ break; \ } \ if (_rc == -1 && _syscallErrno != EINTR) { \ /* TODO: with a format string we could show the arguments too, like strace(1). */ \ throwErrnoException(jni_env, # syscall_name); \ break; \ } \ } while (_rc == -1); /* && _syscallErrno == EINTR && !_wasSignaled */ \ _rc; }) static void throwException(JNIEnv* env, jclass exceptionClass, jmethodID ctor3, jmethodID ctor2, const char* functionName, int error) { jthrowable cause = NULL; if (env->ExceptionCheck()) { cause = env->ExceptionOccurred(); env->ExceptionClear(); } ScopedLocalRef<jstring> detailMessage(env, env->NewStringUTF(functionName)); if (detailMessage.get() == NULL) { // Not really much we can do here. We're probably dead in the water, // but let's try to stumble on... env->ExceptionClear(); } jobject exception; if (cause != NULL) { exception = env->NewObject(exceptionClass, ctor3, detailMessage.get(), error, cause); } else { exception = env->NewObject(exceptionClass, ctor2, detailMessage.get(), error); } env->Throw(reinterpret_cast<jthrowable>(exception)); } static void throwErrnoException(JNIEnv* env, const char* functionName) { int error = errno; static jmethodID ctor3 = env->GetMethodID(JniConstants::errnoExceptionClass, "<init>", "(Ljava/lang/String;ILjava/lang/Throwable;)V"); static jmethodID ctor2 = env->GetMethodID(JniConstants::errnoExceptionClass, "<init>", "(Ljava/lang/String;I)V"); throwException(env, JniConstants::errnoExceptionClass, ctor3, ctor2, functionName, error); } static void throwGaiException(JNIEnv* env, const char* functionName, int error) { // Cache the methods ids before we throw, so we don't call GetMethodID with a pending exception. static jmethodID ctor3 = env->GetMethodID(JniConstants::gaiExceptionClass, "<init>", "(Ljava/lang/String;ILjava/lang/Throwable;)V"); static jmethodID ctor2 = env->GetMethodID(JniConstants::gaiExceptionClass, "<init>", "(Ljava/lang/String;I)V"); if (errno != 0) { // EAI_SYSTEM should mean "look at errno instead", but both glibc and bionic seem to // mess this up. In particular, if you don't have INTERNET permission, errno will be EACCES // but you'll get EAI_NONAME or EAI_NODATA. So we want our GaiException to have a // potentially-relevant ErrnoException as its cause even if error != EAI_SYSTEM. // http://code.google.com/p/android/issues/detail?id=15722 throwErrnoException(env, functionName); // Deliberately fall through to throw another exception... } throwException(env, JniConstants::gaiExceptionClass, ctor3, ctor2, functionName, error); } template <typename rc_t> static rc_t throwIfMinusOne(JNIEnv* env, const char* name, rc_t rc) { if (rc == rc_t(-1)) { throwErrnoException(env, name); } return rc; } template <typename ScopedT> class IoVec { public: IoVec(JNIEnv* env, size_t bufferCount) : mEnv(env), mBufferCount(bufferCount) { } bool init(jobjectArray javaBuffers, jintArray javaOffsets, jintArray javaByteCounts) { // We can't delete our local references until after the I/O, so make sure we have room. if (mEnv->PushLocalFrame(mBufferCount + 16) < 0) { return false; } ScopedIntArrayRO offsets(mEnv, javaOffsets); if (offsets.get() == NULL) { return false; } ScopedIntArrayRO byteCounts(mEnv, javaByteCounts); if (byteCounts.get() == NULL) { return false; } // TODO: Linux actually has a 1024 buffer limit. glibc works around this, and we should too. // TODO: you can query the limit at runtime with sysconf(_SC_IOV_MAX). for (size_t i = 0; i < mBufferCount; ++i) { jobject buffer = mEnv->GetObjectArrayElement(javaBuffers, i); // We keep this local ref. mScopedBuffers.push_back(new ScopedT(mEnv, buffer)); jbyte* ptr = const_cast<jbyte*>(mScopedBuffers.back()->get()); if (ptr == NULL) { return false; } struct iovec iov; iov.iov_base = reinterpret_cast<void*>(ptr + offsets[i]); iov.iov_len = byteCounts[i]; mIoVec.push_back(iov); } return true; } ~IoVec() { for (size_t i = 0; i < mScopedBuffers.size(); ++i) { delete mScopedBuffers[i]; } mEnv->PopLocalFrame(NULL); } iovec* get() { return &mIoVec[0]; } size_t size() { return mBufferCount; } private: JNIEnv* mEnv; size_t mBufferCount; std::vector<iovec> mIoVec; std::vector<ScopedT*> mScopedBuffers; }; static jobject makeSocketAddress(JNIEnv* env, const sockaddr_storage& ss) { jint port; jobject inetAddress = sockaddrToInetAddress(env, ss, &port); if (inetAddress == NULL) { return NULL; } static jmethodID ctor = env->GetMethodID(JniConstants::inetSocketAddressClass, "<init>", "(Ljava/net/InetAddress;I)V"); return env->NewObject(JniConstants::inetSocketAddressClass, ctor, inetAddress, port); } static jobject makeStructPasswd(JNIEnv* env, const struct passwd& pw) { TO_JAVA_STRING(pw_name, pw.pw_name); TO_JAVA_STRING(pw_dir, pw.pw_dir); TO_JAVA_STRING(pw_shell, pw.pw_shell); static jmethodID ctor = env->GetMethodID(JniConstants::structPasswdClass, "<init>", "(Ljava/lang/String;IILjava/lang/String;Ljava/lang/String;)V"); return env->NewObject(JniConstants::structPasswdClass, ctor, pw_name, static_cast<jint>(pw.pw_uid), static_cast<jint>(pw.pw_gid), pw_dir, pw_shell); } static jobject makeStructStat(JNIEnv* env, const struct stat& sb) { static jmethodID ctor = env->GetMethodID(JniConstants::structStatClass, "<init>", "(JJIJIIJJJJJJJ)V"); return env->NewObject(JniConstants::structStatClass, ctor, static_cast<jlong>(sb.st_dev), static_cast<jlong>(sb.st_ino), static_cast<jint>(sb.st_mode), static_cast<jlong>(sb.st_nlink), static_cast<jint>(sb.st_uid), static_cast<jint>(sb.st_gid), static_cast<jlong>(sb.st_rdev), static_cast<jlong>(sb.st_size), static_cast<jlong>(sb.st_atime), static_cast<jlong>(sb.st_mtime), static_cast<jlong>(sb.st_ctime), static_cast<jlong>(sb.st_blksize), static_cast<jlong>(sb.st_blocks)); } static jobject makeStructStatVfs(JNIEnv* env, const struct statvfs& sb) { #if defined(__APPLE__) // Mac OS has no f_namelen field in struct statfs. jlong max_name_length = 255; // __DARWIN_MAXNAMLEN #else jlong max_name_length = static_cast<jlong>(sb.f_namemax); #endif static jmethodID ctor = env->GetMethodID(JniConstants::structStatVfsClass, "<init>", "(JJJJJJJJJJJ)V"); return env->NewObject(JniConstants::structStatVfsClass, ctor, static_cast<jlong>(sb.f_bsize), static_cast<jlong>(sb.f_frsize), static_cast<jlong>(sb.f_blocks), static_cast<jlong>(sb.f_bfree), static_cast<jlong>(sb.f_bavail), static_cast<jlong>(sb.f_files), static_cast<jlong>(sb.f_ffree), static_cast<jlong>(sb.f_favail), static_cast<jlong>(sb.f_fsid), static_cast<jlong>(sb.f_flag), max_name_length); } static jobject makeStructLinger(JNIEnv* env, const struct linger& l) { static jmethodID ctor = env->GetMethodID(JniConstants::structLingerClass, "<init>", "(II)V"); return env->NewObject(JniConstants::structLingerClass, ctor, l.l_onoff, l.l_linger); } static jobject makeStructTimeval(JNIEnv* env, const struct timeval& tv) { static jmethodID ctor = env->GetMethodID(JniConstants::structTimevalClass, "<init>", "(JJ)V"); return env->NewObject(JniConstants::structTimevalClass, ctor, static_cast<jlong>(tv.tv_sec), static_cast<jlong>(tv.tv_usec)); } static jobject makeStructUcred(JNIEnv* env, const struct ucred& u __unused) { #ifdef __APPLE__ jniThrowException(env, "java/lang/UnsupportedOperationException", "unimplemented support for ucred on a Mac"); return NULL; #else static jmethodID ctor = env->GetMethodID(JniConstants::structUcredClass, "<init>", "(III)V"); return env->NewObject(JniConstants::structUcredClass, ctor, u.pid, u.uid, u.gid); #endif } static jobject makeStructUtsname(JNIEnv* env, const struct utsname& buf) { TO_JAVA_STRING(sysname, buf.sysname); TO_JAVA_STRING(nodename, buf.nodename); TO_JAVA_STRING(release, buf.release); TO_JAVA_STRING(version, buf.version); TO_JAVA_STRING(machine, buf.machine); static jmethodID ctor = env->GetMethodID(JniConstants::structUtsnameClass, "<init>", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V"); return env->NewObject(JniConstants::structUtsnameClass, ctor, sysname, nodename, release, version, machine); }; static bool fillIfreq(JNIEnv* env, jstring javaInterfaceName, struct ifreq& req) { ScopedUtfChars interfaceName(env, javaInterfaceName); if (interfaceName.c_str() == NULL) { return false; } memset(&req, 0, sizeof(req)); strncpy(req.ifr_name, interfaceName.c_str(), sizeof(req.ifr_name)); req.ifr_name[sizeof(req.ifr_name) - 1] = '\0'; return true; } static bool fillInetSocketAddress(JNIEnv* env, jint rc, jobject javaInetSocketAddress, const sockaddr_storage& ss) { if (rc == -1 || javaInetSocketAddress == NULL) { return true; } // Fill out the passed-in InetSocketAddress with the sender's IP address and port number. jint port; jobject sender = sockaddrToInetAddress(env, ss, &port); if (sender == NULL) { return false; } static jfieldID addressFid = env->GetFieldID(JniConstants::inetSocketAddressClass, "addr", "Ljava/net/InetAddress;"); static jfieldID portFid = env->GetFieldID(JniConstants::inetSocketAddressClass, "port", "I"); env->SetObjectField(javaInetSocketAddress, addressFid, sender); env->SetIntField(javaInetSocketAddress, portFid, port); return true; } static jobject doStat(JNIEnv* env, jstring javaPath, bool isLstat) { ScopedUtfChars path(env, javaPath); if (path.c_str() == NULL) { return NULL; } struct stat sb; int rc = isLstat ? TEMP_FAILURE_RETRY(lstat(path.c_str(), &sb)) : TEMP_FAILURE_RETRY(stat(path.c_str(), &sb)); if (rc == -1) { throwErrnoException(env, isLstat ? "lstat" : "stat"); return NULL; } return makeStructStat(env, sb); } static jobject doGetSockName(JNIEnv* env, jobject javaFd, bool is_sockname) { int fd = jniGetFDFromFileDescriptor(env, javaFd); sockaddr_storage ss; sockaddr* sa = reinterpret_cast<sockaddr*>(&ss); socklen_t byteCount = sizeof(ss); memset(&ss, 0, byteCount); int rc = is_sockname ? TEMP_FAILURE_RETRY(getsockname(fd, sa, &byteCount)) : TEMP_FAILURE_RETRY(getpeername(fd, sa, &byteCount)); if (rc == -1) { throwErrnoException(env, is_sockname ? "getsockname" : "getpeername"); return NULL; } return makeSocketAddress(env, ss); } class Passwd { public: Passwd(JNIEnv* env) : mEnv(env), mResult(NULL) { mBufferSize = sysconf(_SC_GETPW_R_SIZE_MAX); mBuffer.reset(new char[mBufferSize]); } jobject getpwnam(const char* name) { return process("getpwnam_r", getpwnam_r(name, &mPwd, mBuffer.get(), mBufferSize, &mResult)); } jobject getpwuid(uid_t uid) { return process("getpwuid_r", getpwuid_r(uid, &mPwd, mBuffer.get(), mBufferSize, &mResult)); } struct passwd* get() { return mResult; } private: jobject process(const char* syscall, int error) { if (mResult == NULL) { errno = error; throwErrnoException(mEnv, syscall); return NULL; } return makeStructPasswd(mEnv, *mResult); } JNIEnv* mEnv; UniquePtr<char[]> mBuffer; size_t mBufferSize; struct passwd mPwd; struct passwd* mResult; }; static jobject Posix_accept(JNIEnv* env, jobject, jobject javaFd, jobject javaInetSocketAddress) { sockaddr_storage ss; socklen_t sl = sizeof(ss); memset(&ss, 0, sizeof(ss)); sockaddr* peer = (javaInetSocketAddress != NULL) ? reinterpret_cast<sockaddr*>(&ss) : NULL; socklen_t* peerLength = (javaInetSocketAddress != NULL) ? &sl : 0; jint clientFd = NET_FAILURE_RETRY(env, int, accept, javaFd, peer, peerLength); if (clientFd == -1 || !fillInetSocketAddress(env, clientFd, javaInetSocketAddress, ss)) { close(clientFd); return NULL; } return (clientFd != -1) ? jniCreateFileDescriptor(env, clientFd) : NULL; } static jboolean Posix_access(JNIEnv* env, jobject, jstring javaPath, jint mode) { ScopedUtfChars path(env, javaPath); if (path.c_str() == NULL) { return JNI_FALSE; } int rc = TEMP_FAILURE_RETRY(access(path.c_str(), mode)); if (rc == -1) { throwErrnoException(env, "access"); } return (rc == 0); } static void Posix_bind(JNIEnv* env, jobject, jobject javaFd, jobject javaAddress, jint port) { sockaddr_storage ss; socklen_t sa_len; if (!inetAddressToSockaddr(env, javaAddress, port, ss, sa_len)) { return; } const sockaddr* sa = reinterpret_cast<const sockaddr*>(&ss); // We don't need the return value because we'll already have thrown. (void) NET_FAILURE_RETRY(env, int, bind, javaFd, sa, sa_len); } static void Posix_chmod(JNIEnv* env, jobject, jstring javaPath, jint mode) { ScopedUtfChars path(env, javaPath); if (path.c_str() == NULL) { return; } throwIfMinusOne(env, "chmod", TEMP_FAILURE_RETRY(chmod(path.c_str(), mode))); } static void Posix_chown(JNIEnv* env, jobject, jstring javaPath, jint uid, jint gid) { ScopedUtfChars path(env, javaPath); if (path.c_str() == NULL) { return; } throwIfMinusOne(env, "chown", TEMP_FAILURE_RETRY(chown(path.c_str(), uid, gid))); } static void Posix_close(JNIEnv* env, jobject, jobject javaFd) { // Get the FileDescriptor's 'fd' field and clear it. // We need to do this before we can throw an IOException (http://b/3222087). int fd = jniGetFDFromFileDescriptor(env, javaFd); jniSetFileDescriptorOfFD(env, javaFd, -1); // Even if close(2) fails with EINTR, the fd will have been closed. // Using TEMP_FAILURE_RETRY will either lead to EBADF or closing someone else's fd. // http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html throwIfMinusOne(env, "close", close(fd)); } static void Posix_connect(JNIEnv* env, jobject, jobject javaFd, jobject javaAddress, jint port) { sockaddr_storage ss; socklen_t sa_len; if (!inetAddressToSockaddr(env, javaAddress, port, ss, sa_len)) { return; } const sockaddr* sa = reinterpret_cast<const sockaddr*>(&ss); // We don't need the return value because we'll already have thrown. (void) NET_FAILURE_RETRY(env, int, connect, javaFd, sa, sa_len); } static jobject Posix_dup(JNIEnv* env, jobject, jobject javaOldFd) { int oldFd = jniGetFDFromFileDescriptor(env, javaOldFd); int newFd = throwIfMinusOne(env, "dup", TEMP_FAILURE_RETRY(dup(oldFd))); return (newFd != -1) ? jniCreateFileDescriptor(env, newFd) : NULL; } static jobject Posix_dup2(JNIEnv* env, jobject, jobject javaOldFd, jint newFd) { int oldFd = jniGetFDFromFileDescriptor(env, javaOldFd); int fd = throwIfMinusOne(env, "dup2", TEMP_FAILURE_RETRY(dup2(oldFd, newFd))); return (fd != -1) ? jniCreateFileDescriptor(env, fd) : NULL; } static jobjectArray Posix_environ(JNIEnv* env, jobject) { extern char** environ; // Standard, but not in any header file. return toStringArray(env, environ); } static void Posix_execve(JNIEnv* env, jobject, jstring javaFilename, jobjectArray javaArgv, jobjectArray javaEnvp) { ScopedUtfChars path(env, javaFilename); if (path.c_str() == NULL) { return; } ExecStrings argv(env, javaArgv); ExecStrings envp(env, javaEnvp); execve(path.c_str(), argv.get(), envp.get()); throwErrnoException(env, "execve"); } static void Posix_execv(JNIEnv* env, jobject, jstring javaFilename, jobjectArray javaArgv) { ScopedUtfChars path(env, javaFilename); if (path.c_str() == NULL) { return; } ExecStrings argv(env, javaArgv); execv(path.c_str(), argv.get()); throwErrnoException(env, "execv"); } static void Posix_fchmod(JNIEnv* env, jobject, jobject javaFd, jint mode) { int fd = jniGetFDFromFileDescriptor(env, javaFd); throwIfMinusOne(env, "fchmod", TEMP_FAILURE_RETRY(fchmod(fd, mode))); } static void Posix_fchown(JNIEnv* env, jobject, jobject javaFd, jint uid, jint gid) { int fd = jniGetFDFromFileDescriptor(env, javaFd); throwIfMinusOne(env, "fchown", TEMP_FAILURE_RETRY(fchown(fd, uid, gid))); } static jint Posix_fcntlVoid(JNIEnv* env, jobject, jobject javaFd, jint cmd) { int fd = jniGetFDFromFileDescriptor(env, javaFd); return throwIfMinusOne(env, "fcntl", TEMP_FAILURE_RETRY(fcntl(fd, cmd))); } static jint Posix_fcntlLong(JNIEnv* env, jobject, jobject javaFd, jint cmd, jlong arg) { int fd = jniGetFDFromFileDescriptor(env, javaFd); return throwIfMinusOne(env, "fcntl", TEMP_FAILURE_RETRY(fcntl(fd, cmd, arg))); } static jint Posix_fcntlFlock(JNIEnv* env, jobject, jobject javaFd, jint cmd, jobject javaFlock) { static jfieldID typeFid = env->GetFieldID(JniConstants::structFlockClass, "l_type", "S"); static jfieldID whenceFid = env->GetFieldID(JniConstants::structFlockClass, "l_whence", "S"); static jfieldID startFid = env->GetFieldID(JniConstants::structFlockClass, "l_start", "J"); static jfieldID lenFid = env->GetFieldID(JniConstants::structFlockClass, "l_len", "J"); static jfieldID pidFid = env->GetFieldID(JniConstants::structFlockClass, "l_pid", "I"); struct flock64 lock; memset(&lock, 0, sizeof(lock)); lock.l_type = env->GetShortField(javaFlock, typeFid); lock.l_whence = env->GetShortField(javaFlock, whenceFid); lock.l_start = env->GetLongField(javaFlock, startFid); lock.l_len = env->GetLongField(javaFlock, lenFid); lock.l_pid = env->GetIntField(javaFlock, pidFid); int rc = IO_FAILURE_RETRY(env, int, fcntl, javaFd, cmd, &lock); if (rc != -1) { env->SetShortField(javaFlock, typeFid, lock.l_type); env->SetShortField(javaFlock, whenceFid, lock.l_whence); env->SetLongField(javaFlock, startFid, lock.l_start); env->SetLongField(javaFlock, lenFid, lock.l_len); env->SetIntField(javaFlock, pidFid, lock.l_pid); } return rc; } static void Posix_fdatasync(JNIEnv* env, jobject, jobject javaFd) { int fd = jniGetFDFromFileDescriptor(env, javaFd); throwIfMinusOne(env, "fdatasync", TEMP_FAILURE_RETRY(fdatasync(fd))); } static jobject Posix_fstat(JNIEnv* env, jobject, jobject javaFd) { int fd = jniGetFDFromFileDescriptor(env, javaFd); struct stat sb; int rc = TEMP_FAILURE_RETRY(fstat(fd, &sb)); if (rc == -1) { throwErrnoException(env, "fstat"); return NULL; } return makeStructStat(env, sb); } static jobject Posix_fstatvfs(JNIEnv* env, jobject, jobject javaFd) { int fd = jniGetFDFromFileDescriptor(env, javaFd); struct statvfs sb; int rc = TEMP_FAILURE_RETRY(fstatvfs(fd, &sb)); if (rc == -1) { throwErrnoException(env, "fstatvfs"); return NULL; } return makeStructStatVfs(env, sb); } static void Posix_fsync(JNIEnv* env, jobject, jobject javaFd) { int fd = jniGetFDFromFileDescriptor(env, javaFd); throwIfMinusOne(env, "fsync", TEMP_FAILURE_RETRY(fsync(fd))); } static void Posix_ftruncate(JNIEnv* env, jobject, jobject javaFd, jlong length) { int fd = jniGetFDFromFileDescriptor(env, javaFd); throwIfMinusOne(env, "ftruncate", TEMP_FAILURE_RETRY(ftruncate64(fd, length))); } static jstring Posix_gai_strerror(JNIEnv* env, jobject, jint error) { return env->NewStringUTF(gai_strerror(error)); } static jobjectArray Posix_android_getaddrinfo(JNIEnv* env, jobject, jstring javaNode, jobject javaHints, jint netId) { ScopedUtfChars node(env, javaNode); if (node.c_str() == NULL) { return NULL; } static jfieldID flagsFid = env->GetFieldID(JniConstants::structAddrinfoClass, "ai_flags", "I"); static jfieldID familyFid = env->GetFieldID(JniConstants::structAddrinfoClass, "ai_family", "I"); static jfieldID socktypeFid = env->GetFieldID(JniConstants::structAddrinfoClass, "ai_socktype", "I"); static jfieldID protocolFid = env->GetFieldID(JniConstants::structAddrinfoClass, "ai_protocol", "I"); addrinfo hints; memset(&hints, 0, sizeof(hints)); hints.ai_flags = env->GetIntField(javaHints, flagsFid); hints.ai_family = env->GetIntField(javaHints, familyFid); hints.ai_socktype = env->GetIntField(javaHints, socktypeFid); hints.ai_protocol = env->GetIntField(javaHints, protocolFid); addrinfo* addressList = NULL; errno = 0; int rc = android_getaddrinfofornet(node.c_str(), NULL, &hints, netId, 0, &addressList); UniquePtr<addrinfo, addrinfo_deleter> addressListDeleter(addressList); if (rc != 0) { throwGaiException(env, "android_getaddrinfo", rc); return NULL; } // Count results so we know how to size the output array. int addressCount = 0; for (addrinfo* ai = addressList; ai != NULL; ai = ai->ai_next) { if (ai->ai_family == AF_INET || ai->ai_family == AF_INET6) { ++addressCount; } else { ALOGE("android_getaddrinfo unexpected ai_family %i", ai->ai_family); } } if (addressCount == 0) { return NULL; } // Prepare output array. jobjectArray result = env->NewObjectArray(addressCount, JniConstants::inetAddressClass, NULL); if (result == NULL) { return NULL; } // Examine returned addresses one by one, save them in the output array. int index = 0; for (addrinfo* ai = addressList; ai != NULL; ai = ai->ai_next) { if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6) { // Unknown address family. Skip this address. ALOGE("android_getaddrinfo unexpected ai_family %i", ai->ai_family); continue; } // Convert each IP address into a Java byte array. sockaddr_storage& address = *reinterpret_cast<sockaddr_storage*>(ai->ai_addr); ScopedLocalRef<jobject> inetAddress(env, sockaddrToInetAddress(env, address, NULL)); if (inetAddress.get() == NULL) { return NULL; } env->SetObjectArrayElement(result, index, inetAddress.get()); ++index; } return result; } static jint Posix_getegid(JNIEnv*, jobject) { return getegid(); } static jint Posix_geteuid(JNIEnv*, jobject) { return geteuid(); } static jint Posix_getgid(JNIEnv*, jobject) { return getgid(); } static jstring Posix_getenv(JNIEnv* env, jobject, jstring javaName) { ScopedUtfChars name(env, javaName); if (name.c_str() == NULL) { return NULL; } return env->NewStringUTF(getenv(name.c_str())); } static jstring Posix_getnameinfo(JNIEnv* env, jobject, jobject javaAddress, jint flags) { sockaddr_storage ss; socklen_t sa_len; if (!inetAddressToSockaddrVerbatim(env, javaAddress, 0, ss, sa_len)) { return NULL; } char buf[NI_MAXHOST]; // NI_MAXHOST is longer than INET6_ADDRSTRLEN. errno = 0; int rc = getnameinfo(reinterpret_cast<sockaddr*>(&ss), sa_len, buf, sizeof(buf), NULL, 0, flags); if (rc != 0) { throwGaiException(env, "getnameinfo", rc); return NULL; } return env->NewStringUTF(buf); } static jobject Posix_getpeername(JNIEnv* env, jobject, jobject javaFd) { return doGetSockName(env, javaFd, false); } static jint Posix_getpid(JNIEnv*, jobject) { return getpid(); } static jint Posix_getppid(JNIEnv*, jobject) { return getppid(); } static jobject Posix_getpwnam(JNIEnv* env, jobject, jstring javaName) { ScopedUtfChars name(env, javaName); if (name.c_str() == NULL) { return NULL; } return Passwd(env).getpwnam(name.c_str()); } static jobject Posix_getpwuid(JNIEnv* env, jobject, jint uid) { return Passwd(env).getpwuid(uid); } static jobject Posix_getsockname(JNIEnv* env, jobject, jobject javaFd) { return doGetSockName(env, javaFd, true); } static jint Posix_getsockoptByte(JNIEnv* env, jobject, jobject javaFd, jint level, jint option) { int fd = jniGetFDFromFileDescriptor(env, javaFd); u_char result = 0; socklen_t size = sizeof(result); throwIfMinusOne(env, "getsockopt", TEMP_FAILURE_RETRY(getsockopt(fd, level, option, &result, &size))); return result; } static jobject Posix_getsockoptInAddr(JNIEnv* env, jobject, jobject javaFd, jint level, jint option) { int fd = jniGetFDFromFileDescriptor(env, javaFd); sockaddr_storage ss; memset(&ss, 0, sizeof(ss)); ss.ss_family = AF_INET; // This is only for the IPv4-only IP_MULTICAST_IF. sockaddr_in* sa = reinterpret_cast<sockaddr_in*>(&ss); socklen_t size = sizeof(sa->sin_addr); int rc = TEMP_FAILURE_RETRY(getsockopt(fd, level, option, &sa->sin_addr, &size)); if (rc == -1) { throwErrnoException(env, "getsockopt"); return NULL; } return sockaddrToInetAddress(env, ss, NULL); } static jint Posix_getsockoptInt(JNIEnv* env, jobject, jobject javaFd, jint level, jint option) { int fd = jniGetFDFromFileDescriptor(env, javaFd); jint result = 0; socklen_t size = sizeof(result); throwIfMinusOne(env, "getsockopt", TEMP_FAILURE_RETRY(getsockopt(fd, level, option, &result, &size))); return result; } static jobject Posix_getsockoptLinger(JNIEnv* env, jobject, jobject javaFd, jint level, jint option) { int fd = jniGetFDFromFileDescriptor(env, javaFd); struct linger l; socklen_t size = sizeof(l); memset(&l, 0, size); int rc = TEMP_FAILURE_RETRY(getsockopt(fd, level, option, &l, &size)); if (rc == -1) { throwErrnoException(env, "getsockopt"); return NULL; } return makeStructLinger(env, l); } static jobject Posix_getsockoptTimeval(JNIEnv* env, jobject, jobject javaFd, jint level, jint option) { int fd = jniGetFDFromFileDescriptor(env, javaFd); struct timeval tv; socklen_t size = sizeof(tv); memset(&tv, 0, size); int rc = TEMP_FAILURE_RETRY(getsockopt(fd, level, option, &tv, &size)); if (rc == -1) { throwErrnoException(env, "getsockopt"); return NULL; } return makeStructTimeval(env, tv); } static jobject Posix_getsockoptUcred(JNIEnv* env, jobject, jobject javaFd, jint level, jint option) { int fd = jniGetFDFromFileDescriptor(env, javaFd); struct ucred u; socklen_t size = sizeof(u); memset(&u, 0, size); int rc = TEMP_FAILURE_RETRY(getsockopt(fd, level, option, &u, &size)); if (rc == -1) { throwErrnoException(env, "getsockopt"); return NULL; } return makeStructUcred(env, u); } static jint Posix_gettid(JNIEnv* env __unused, jobject) { #if defined(__APPLE__) uint64_t owner; int rc = pthread_threadid_np(NULL, &owner); // Requires Mac OS 10.6 if (rc != 0) { throwErrnoException(env, "gettid"); return 0; } return static_cast<jint>(owner); #else // Neither bionic nor glibc exposes gettid(2). return syscall(__NR_gettid); #endif } static jint Posix_getuid(JNIEnv*, jobject) { return getuid(); } static jstring Posix_if_indextoname(JNIEnv* env, jobject, jint index) { char buf[IF_NAMESIZE]; char* name = if_indextoname(index, buf); // if_indextoname(3) returns NULL on failure, which will come out of NewStringUTF unscathed. // There's no useful information in errno, so we don't bother throwing. Callers can null-check. return env->NewStringUTF(name); } static jobject Posix_inet_pton(JNIEnv* env, jobject, jint family, jstring javaName) { ScopedUtfChars name(env, javaName); if (name.c_str() == NULL) { return NULL; } sockaddr_storage ss; memset(&ss, 0, sizeof(ss)); // sockaddr_in and sockaddr_in6 are at the same address, so we can use either here. void* dst = &reinterpret_cast<sockaddr_in*>(&ss)->sin_addr; if (inet_pton(family, name.c_str(), dst) != 1) { return NULL; } ss.ss_family = family; return sockaddrToInetAddress(env, ss, NULL); } static jobject Posix_ioctlInetAddress(JNIEnv* env, jobject, jobject javaFd, jint cmd, jstring javaInterfaceName) { struct ifreq req; if (!fillIfreq(env, javaInterfaceName, req)) { return NULL; } int fd = jniGetFDFromFileDescriptor(env, javaFd); int rc = throwIfMinusOne(env, "ioctl", TEMP_FAILURE_RETRY(ioctl(fd, cmd, &req))); if (rc == -1) { return NULL; } return sockaddrToInetAddress(env, reinterpret_cast<sockaddr_storage&>(req.ifr_addr), NULL); } static jint Posix_ioctlInt(JNIEnv* env, jobject, jobject javaFd, jint cmd, jobject javaArg) { // This is complicated because ioctls may return their result by updating their argument // or via their return value, so we need to support both. int fd = jniGetFDFromFileDescriptor(env, javaFd); static jfieldID valueFid = env->GetFieldID(JniConstants::mutableIntClass, "value", "I"); jint arg = env->GetIntField(javaArg, valueFid); int rc = throwIfMinusOne(env, "ioctl", TEMP_FAILURE_RETRY(ioctl(fd, cmd, &arg))); if (!env->ExceptionCheck()) { env->SetIntField(javaArg, valueFid, arg); } return rc; } static jboolean Posix_isatty(JNIEnv* env, jobject, jobject javaFd) { int fd = jniGetFDFromFileDescriptor(env, javaFd); return TEMP_FAILURE_RETRY(isatty(fd)) == 1; } static void Posix_kill(JNIEnv* env, jobject, jint pid, jint sig) { throwIfMinusOne(env, "kill", TEMP_FAILURE_RETRY(kill(pid, sig))); } static void Posix_lchown(JNIEnv* env, jobject, jstring javaPath, jint uid, jint gid) { ScopedUtfChars path(env, javaPath); if (path.c_str() == NULL) { return; } throwIfMinusOne(env, "lchown", TEMP_FAILURE_RETRY(lchown(path.c_str(), uid, gid))); } static void Posix_link(JNIEnv* env, jobject, jstring javaOldPath, jstring javaNewPath) { ScopedUtfChars oldPath(env, javaOldPath); if (oldPath.c_str() == NULL) { return; } ScopedUtfChars newPath(env, javaNewPath); if (newPath.c_str() == NULL) { return; } throwIfMinusOne(env, "link", TEMP_FAILURE_RETRY(link(oldPath.c_str(), newPath.c_str()))); } static void Posix_listen(JNIEnv* env, jobject, jobject javaFd, jint backlog) { int fd = jniGetFDFromFileDescriptor(env, javaFd); throwIfMinusOne(env, "listen", TEMP_FAILURE_RETRY(listen(fd, backlog))); } static jlong Posix_lseek(JNIEnv* env, jobject, jobject javaFd, jlong offset, jint whence) { int fd = jniGetFDFromFileDescriptor(env, javaFd); return throwIfMinusOne(env, "lseek", TEMP_FAILURE_RETRY(lseek64(fd, offset, whence))); } static jobject Posix_lstat(JNIEnv* env, jobject, jstring javaPath) { return doStat(env, javaPath, true); } static void Posix_mincore(JNIEnv* env, jobject, jlong address, jlong byteCount, jbyteArray javaVector) { ScopedByteArrayRW vector(env, javaVector); if (vector.get() == NULL) { return; } void* ptr = reinterpret_cast<void*>(static_cast<uintptr_t>(address)); unsigned char* vec = reinterpret_cast<unsigned char*>(vector.get()); throwIfMinusOne(env, "mincore", TEMP_FAILURE_RETRY(mincore(ptr, byteCount, vec))); } static void Posix_mkdir(JNIEnv* env, jobject, jstring javaPath, jint mode) { ScopedUtfChars path(env, javaPath); if (path.c_str() == NULL) { return; } throwIfMinusOne(env, "mkdir", TEMP_FAILURE_RETRY(mkdir(path.c_str(), mode))); } static void Posix_mkfifo(JNIEnv* env, jobject, jstring javaPath, jint mode) { ScopedUtfChars path(env, javaPath); if (path.c_str() == NULL) { return; } throwIfMinusOne(env, "mkfifo", TEMP_FAILURE_RETRY(mkfifo(path.c_str(), mode))); } static void Posix_mlock(JNIEnv* env, jobject, jlong address, jlong byteCount) { void* ptr = reinterpret_cast<void*>(static_cast<uintptr_t>(address)); throwIfMinusOne(env, "mlock", TEMP_FAILURE_RETRY(mlock(ptr, byteCount))); } static jlong Posix_mmap(JNIEnv* env, jobject, jlong address, jlong byteCount, jint prot, jint flags, jobject javaFd, jlong offset) { int fd = jniGetFDFromFileDescriptor(env, javaFd); void* suggestedPtr = reinterpret_cast<void*>(static_cast<uintptr_t>(address)); void* ptr = mmap(suggestedPtr, byteCount, prot, flags, fd, offset); if (ptr == MAP_FAILED) { throwErrnoException(env, "mmap"); } return static_cast<jlong>(reinterpret_cast<uintptr_t>(ptr)); } static void Posix_msync(JNIEnv* env, jobject, jlong address, jlong byteCount, jint flags) { void* ptr = reinterpret_cast<void*>(static_cast<uintptr_t>(address)); throwIfMinusOne(env, "msync", TEMP_FAILURE_RETRY(msync(ptr, byteCount, flags))); } static void Posix_munlock(JNIEnv* env, jobject, jlong address, jlong byteCount) { void* ptr = reinterpret_cast<void*>(static_cast<uintptr_t>(address)); throwIfMinusOne(env, "munlock", TEMP_FAILURE_RETRY(munlock(ptr, byteCount))); } static void Posix_munmap(JNIEnv* env, jobject, jlong address, jlong byteCount) { void* ptr = reinterpret_cast<void*>(static_cast<uintptr_t>(address)); throwIfMinusOne(env, "munmap", TEMP_FAILURE_RETRY(munmap(ptr, byteCount))); } static jobject Posix_open(JNIEnv* env, jobject, jstring javaPath, jint flags, jint mode) { ScopedUtfChars path(env, javaPath); if (path.c_str() == NULL) { return NULL; } int fd = throwIfMinusOne(env, "open", TEMP_FAILURE_RETRY(open(path.c_str(), flags, mode))); return fd != -1 ? jniCreateFileDescriptor(env, fd) : NULL; } static jobjectArray Posix_pipe(JNIEnv* env, jobject) { int fds[2]; throwIfMinusOne(env, "pipe", TEMP_FAILURE_RETRY(pipe(&fds[0]))); jobjectArray result = env->NewObjectArray(2, JniConstants::fileDescriptorClass, NULL); if (result == NULL) { return NULL; } for (int i = 0; i < 2; ++i) { ScopedLocalRef<jobject> fd(env, jniCreateFileDescriptor(env, fds[i])); if (fd.get() == NULL) { return NULL; } env->SetObjectArrayElement(result, i, fd.get()); if (env->ExceptionCheck()) { return NULL; } } return result; } static jint Posix_poll(JNIEnv* env, jobject, jobjectArray javaStructs, jint timeoutMs) { static jfieldID fdFid = env->GetFieldID(JniConstants::structPollfdClass, "fd", "Ljava/io/FileDescriptor;"); static jfieldID eventsFid = env->GetFieldID(JniConstants::structPollfdClass, "events", "S"); static jfieldID reventsFid = env->GetFieldID(JniConstants::structPollfdClass, "revents", "S"); // Turn the Java android.system.StructPollfd[] into a C++ struct pollfd[]. size_t arrayLength = env->GetArrayLength(javaStructs); UniquePtr<struct pollfd[]> fds(new struct pollfd[arrayLength]); memset(fds.get(), 0, sizeof(struct pollfd) * arrayLength); size_t count = 0; // Some trailing array elements may be irrelevant. (See below.) for (size_t i = 0; i < arrayLength; ++i) { ScopedLocalRef<jobject> javaStruct(env, env->GetObjectArrayElement(javaStructs, i)); if (javaStruct.get() == NULL) { break; // We allow trailing nulls in the array for caller convenience. } ScopedLocalRef<jobject> javaFd(env, env->GetObjectField(javaStruct.get(), fdFid)); if (javaFd.get() == NULL) { break; // We also allow callers to just clear the fd field (this is what Selector does). } fds[count].fd = jniGetFDFromFileDescriptor(env, javaFd.get()); fds[count].events = env->GetShortField(javaStruct.get(), eventsFid); ++count; } std::vector<AsynchronousCloseMonitor*> monitors; for (size_t i = 0; i < count; ++i) { monitors.push_back(new AsynchronousCloseMonitor(fds[i].fd)); } int rc = poll(fds.get(), count, timeoutMs); for (size_t i = 0; i < monitors.size(); ++i) { delete monitors[i]; } if (rc == -1) { throwErrnoException(env, "poll"); return -1; } // Update the revents fields in the Java android.system.StructPollfd[]. for (size_t i = 0; i < count; ++i) { ScopedLocalRef<jobject> javaStruct(env, env->GetObjectArrayElement(javaStructs, i)); if (javaStruct.get() == NULL) { return -1; } env->SetShortField(javaStruct.get(), reventsFid, fds[i].revents); } return rc; } static void Posix_posix_fallocate(JNIEnv* env, jobject, jobject javaFd __unused, jlong offset __unused, jlong length __unused) { #ifdef __APPLE__ jniThrowException(env, "java/lang/UnsupportedOperationException", "fallocate doesn't exist on a Mac"); #else int fd = jniGetFDFromFileDescriptor(env, javaFd); errno = TEMP_FAILURE_RETRY(posix_fallocate64(fd, offset, length)); if (errno != 0) { throwErrnoException(env, "posix_fallocate"); } #endif } static jint Posix_prctl(JNIEnv* env, jobject, jint option __unused, jlong arg2 __unused, jlong arg3 __unused, jlong arg4 __unused, jlong arg5 __unused) { #ifdef __APPLE__ jniThrowException(env, "java/lang/UnsupportedOperationException", "prctl doesn't exist on a Mac"); return 0; #else int result = prctl(static_cast<int>(option), static_cast<unsigned long>(arg2), static_cast<unsigned long>(arg3), static_cast<unsigned long>(arg4), static_cast<unsigned long>(arg5)); return throwIfMinusOne(env, "prctl", result); #endif } static jint Posix_preadBytes(JNIEnv* env, jobject, jobject javaFd, jobject javaBytes, jint byteOffset, jint byteCount, jlong offset) { ScopedBytesRW bytes(env, javaBytes); if (bytes.get() == NULL) { return -1; } return IO_FAILURE_RETRY(env, ssize_t, pread64, javaFd, bytes.get() + byteOffset, byteCount, offset); } static jint Posix_pwriteBytes(JNIEnv* env, jobject, jobject javaFd, jbyteArray javaBytes, jint byteOffset, jint byteCount, jlong offset) { ScopedBytesRO bytes(env, javaBytes); if (bytes.get() == NULL) { return -1; } return IO_FAILURE_RETRY(env, ssize_t, pwrite64, javaFd, bytes.get() + byteOffset, byteCount, offset); } static jint Posix_readBytes(JNIEnv* env, jobject, jobject javaFd, jobject javaBytes, jint byteOffset, jint byteCount) { ScopedBytesRW bytes(env, javaBytes); if (bytes.get() == NULL) { return -1; } return IO_FAILURE_RETRY(env, ssize_t, read, javaFd, bytes.get() + byteOffset, byteCount); } static jstring Posix_readlink(JNIEnv* env, jobject, jstring javaPath) { ScopedUtfChars path(env, javaPath); if (path.c_str() == NULL) { return NULL; } std::string result; if (!readlink(path.c_str(), result)) { throwErrnoException(env, "readlink"); return NULL; } return env->NewStringUTF(result.c_str()); } static jint Posix_readv(JNIEnv* env, jobject, jobject javaFd, jobjectArray buffers, jintArray offsets, jintArray byteCounts) { IoVec<ScopedBytesRW> ioVec(env, env->GetArrayLength(buffers)); if (!ioVec.init(buffers, offsets, byteCounts)) { return -1; } return IO_FAILURE_RETRY(env, ssize_t, readv, javaFd, ioVec.get(), ioVec.size()); } static jint Posix_recvfromBytes(JNIEnv* env, jobject, jobject javaFd, jobject javaBytes, jint byteOffset, jint byteCount, jint flags, jobject javaInetSocketAddress) { ScopedBytesRW bytes(env, javaBytes); if (bytes.get() == NULL) { return -1; } sockaddr_storage ss; socklen_t sl = sizeof(ss); memset(&ss, 0, sizeof(ss)); sockaddr* from = (javaInetSocketAddress != NULL) ? reinterpret_cast<sockaddr*>(&ss) : NULL; socklen_t* fromLength = (javaInetSocketAddress != NULL) ? &sl : 0; jint recvCount = NET_FAILURE_RETRY(env, ssize_t, recvfrom, javaFd, bytes.get() + byteOffset, byteCount, flags, from, fromLength); fillInetSocketAddress(env, recvCount, javaInetSocketAddress, ss); return recvCount; } static void Posix_remove(JNIEnv* env, jobject, jstring javaPath) { ScopedUtfChars path(env, javaPath); if (path.c_str() == NULL) { return; } throwIfMinusOne(env, "remove", TEMP_FAILURE_RETRY(remove(path.c_str()))); } static void Posix_rename(JNIEnv* env, jobject, jstring javaOldPath, jstring javaNewPath) { ScopedUtfChars oldPath(env, javaOldPath); if (oldPath.c_str() == NULL) { return; } ScopedUtfChars newPath(env, javaNewPath); if (newPath.c_str() == NULL) { return; } throwIfMinusOne(env, "rename", TEMP_FAILURE_RETRY(rename(oldPath.c_str(), newPath.c_str()))); } static jlong Posix_sendfile(JNIEnv* env, jobject, jobject javaOutFd, jobject javaInFd, jobject javaOffset, jlong byteCount) { int outFd = jniGetFDFromFileDescriptor(env, javaOutFd); int inFd = jniGetFDFromFileDescriptor(env, javaInFd); static jfieldID valueFid = env->GetFieldID(JniConstants::mutableLongClass, "value", "J"); off_t offset = 0; off_t* offsetPtr = NULL; if (javaOffset != NULL) { // TODO: fix bionic so we can have a 64-bit off_t! offset = env->GetLongField(javaOffset, valueFid); offsetPtr = &offset; } jlong result = throwIfMinusOne(env, "sendfile", TEMP_FAILURE_RETRY(sendfile(outFd, inFd, offsetPtr, byteCount))); if (javaOffset != NULL) { env->SetLongField(javaOffset, valueFid, offset); } return result; } static jint Posix_sendtoBytes(JNIEnv* env, jobject, jobject javaFd, jobject javaBytes, jint byteOffset, jint byteCount, jint flags, jobject javaInetAddress, jint port) { ScopedBytesRO bytes(env, javaBytes); if (bytes.get() == NULL) { return -1; } sockaddr_storage ss; socklen_t sa_len = 0; if (javaInetAddress != NULL && !inetAddressToSockaddr(env, javaInetAddress, port, ss, sa_len)) { return -1; } const sockaddr* to = (javaInetAddress != NULL) ? reinterpret_cast<const sockaddr*>(&ss) : NULL; return NET_FAILURE_RETRY(env, ssize_t, sendto, javaFd, bytes.get() + byteOffset, byteCount, flags, to, sa_len); } static void Posix_setegid(JNIEnv* env, jobject, jint egid) { throwIfMinusOne(env, "setegid", TEMP_FAILURE_RETRY(setegid(egid))); } static void Posix_setenv(JNIEnv* env, jobject, jstring javaName, jstring javaValue, jboolean overwrite) { ScopedUtfChars name(env, javaName); if (name.c_str() == NULL) { return; } ScopedUtfChars value(env, javaValue); if (value.c_str() == NULL) { return; } throwIfMinusOne(env, "setenv", setenv(name.c_str(), value.c_str(), overwrite)); } static void Posix_seteuid(JNIEnv* env, jobject, jint euid) { throwIfMinusOne(env, "seteuid", TEMP_FAILURE_RETRY(seteuid(euid))); } static void Posix_setgid(JNIEnv* env, jobject, jint gid) { throwIfMinusOne(env, "setgid", TEMP_FAILURE_RETRY(setgid(gid))); } static jint Posix_setsid(JNIEnv* env, jobject) { return throwIfMinusOne(env, "setsid", TEMP_FAILURE_RETRY(setsid())); } static void Posix_setsockoptByte(JNIEnv* env, jobject, jobject javaFd, jint level, jint option, jint value) { int fd = jniGetFDFromFileDescriptor(env, javaFd); u_char byte = value; throwIfMinusOne(env, "setsockopt", TEMP_FAILURE_RETRY(setsockopt(fd, level, option, &byte, sizeof(byte)))); } static void Posix_setsockoptIfreq(JNIEnv* env, jobject, jobject javaFd, jint level, jint option, jstring javaInterfaceName) { struct ifreq req; if (!fillIfreq(env, javaInterfaceName, req)) { return; } int fd = jniGetFDFromFileDescriptor(env, javaFd); throwIfMinusOne(env, "setsockopt", TEMP_FAILURE_RETRY(setsockopt(fd, level, option, &req, sizeof(req)))); } static void Posix_setsockoptInt(JNIEnv* env, jobject, jobject javaFd, jint level, jint option, jint value) { int fd = jniGetFDFromFileDescriptor(env, javaFd); throwIfMinusOne(env, "setsockopt", TEMP_FAILURE_RETRY(setsockopt(fd, level, option, &value, sizeof(value)))); } #if defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED < 1070 // Mac OS didn't support modern multicast APIs until 10.7. static void Posix_setsockoptIpMreqn(JNIEnv*, jobject, jobject, jint, jint, jint) { abort(); } static void Posix_setsockoptGroupReq(JNIEnv*, jobject, jobject, jint, jint, jobject) { abort(); } static void Posix_setsockoptGroupSourceReq(JNIEnv*, jobject, jobject, jint, jint, jobject) { abort(); } #else static void Posix_setsockoptIpMreqn(JNIEnv* env, jobject, jobject javaFd, jint level, jint option, jint value) { ip_mreqn req; memset(&req, 0, sizeof(req)); req.imr_ifindex = value; int fd = jniGetFDFromFileDescriptor(env, javaFd); throwIfMinusOne(env, "setsockopt", TEMP_FAILURE_RETRY(setsockopt(fd, level, option, &req, sizeof(req)))); } static void Posix_setsockoptGroupReq(JNIEnv* env, jobject, jobject javaFd, jint level, jint option, jobject javaGroupReq) { struct group_req req; memset(&req, 0, sizeof(req)); static jfieldID grInterfaceFid = env->GetFieldID(JniConstants::structGroupReqClass, "gr_interface", "I"); req.gr_interface = env->GetIntField(javaGroupReq, grInterfaceFid); // Get the IPv4 or IPv6 multicast address to join or leave. static jfieldID grGroupFid = env->GetFieldID(JniConstants::structGroupReqClass, "gr_group", "Ljava/net/InetAddress;"); ScopedLocalRef<jobject> javaGroup(env, env->GetObjectField(javaGroupReq, grGroupFid)); socklen_t sa_len; if (!inetAddressToSockaddrVerbatim(env, javaGroup.get(), 0, req.gr_group, sa_len)) { return; } int fd = jniGetFDFromFileDescriptor(env, javaFd); int rc = TEMP_FAILURE_RETRY(setsockopt(fd, level, option, &req, sizeof(req))); if (rc == -1 && errno == EINVAL) { // Maybe we're a 32-bit binary talking to a 64-bit kernel? // glibc doesn't automatically handle this. // http://sourceware.org/bugzilla/show_bug.cgi?id=12080 struct group_req64 { uint32_t gr_interface; uint32_t my_padding; sockaddr_storage gr_group; }; group_req64 req64; req64.gr_interface = req.gr_interface; memcpy(&req64.gr_group, &req.gr_group, sizeof(req.gr_group)); rc = TEMP_FAILURE_RETRY(setsockopt(fd, level, option, &req64, sizeof(req64))); } throwIfMinusOne(env, "setsockopt", rc); } static void Posix_setsockoptGroupSourceReq(JNIEnv* env, jobject, jobject javaFd, jint level, jint option, jobject javaGroupSourceReq) { socklen_t sa_len; struct group_source_req req; memset(&req, 0, sizeof(req)); static jfieldID gsrInterfaceFid = env->GetFieldID(JniConstants::structGroupSourceReqClass, "gsr_interface", "I"); req.gsr_interface = env->GetIntField(javaGroupSourceReq, gsrInterfaceFid); // Get the IPv4 or IPv6 multicast address to join or leave. static jfieldID gsrGroupFid = env->GetFieldID(JniConstants::structGroupSourceReqClass, "gsr_group", "Ljava/net/InetAddress;"); ScopedLocalRef<jobject> javaGroup(env, env->GetObjectField(javaGroupSourceReq, gsrGroupFid)); if (!inetAddressToSockaddrVerbatim(env, javaGroup.get(), 0, req.gsr_group, sa_len)) { return; } // Get the IPv4 or IPv6 multicast address to add to the filter. static jfieldID gsrSourceFid = env->GetFieldID(JniConstants::structGroupSourceReqClass, "gsr_source", "Ljava/net/InetAddress;"); ScopedLocalRef<jobject> javaSource(env, env->GetObjectField(javaGroupSourceReq, gsrSourceFid)); if (!inetAddressToSockaddrVerbatim(env, javaSource.get(), 0, req.gsr_source, sa_len)) { return; } int fd = jniGetFDFromFileDescriptor(env, javaFd); int rc = TEMP_FAILURE_RETRY(setsockopt(fd, level, option, &req, sizeof(req))); if (rc == -1 && errno == EINVAL) { // Maybe we're a 32-bit binary talking to a 64-bit kernel? // glibc doesn't automatically handle this. // http://sourceware.org/bugzilla/show_bug.cgi?id=12080 struct group_source_req64 { uint32_t gsr_interface; uint32_t my_padding; sockaddr_storage gsr_group; sockaddr_storage gsr_source; }; group_source_req64 req64; req64.gsr_interface = req.gsr_interface; memcpy(&req64.gsr_group, &req.gsr_group, sizeof(req.gsr_group)); memcpy(&req64.gsr_source, &req.gsr_source, sizeof(req.gsr_source)); rc = TEMP_FAILURE_RETRY(setsockopt(fd, level, option, &req64, sizeof(req64))); } throwIfMinusOne(env, "setsockopt", rc); } #endif static void Posix_setsockoptLinger(JNIEnv* env, jobject, jobject javaFd, jint level, jint option, jobject javaLinger) { static jfieldID lOnoffFid = env->GetFieldID(JniConstants::structLingerClass, "l_onoff", "I"); static jfieldID lLingerFid = env->GetFieldID(JniConstants::structLingerClass, "l_linger", "I"); int fd = jniGetFDFromFileDescriptor(env, javaFd); struct linger value; value.l_onoff = env->GetIntField(javaLinger, lOnoffFid); value.l_linger = env->GetIntField(javaLinger, lLingerFid); throwIfMinusOne(env, "setsockopt", TEMP_FAILURE_RETRY(setsockopt(fd, level, option, &value, sizeof(value)))); } static void Posix_setsockoptTimeval(JNIEnv* env, jobject, jobject javaFd, jint level, jint option, jobject javaTimeval) { static jfieldID tvSecFid = env->GetFieldID(JniConstants::structTimevalClass, "tv_sec", "J"); static jfieldID tvUsecFid = env->GetFieldID(JniConstants::structTimevalClass, "tv_usec", "J"); int fd = jniGetFDFromFileDescriptor(env, javaFd); struct timeval value; value.tv_sec = env->GetLongField(javaTimeval, tvSecFid); value.tv_usec = env->GetLongField(javaTimeval, tvUsecFid); throwIfMinusOne(env, "setsockopt", TEMP_FAILURE_RETRY(setsockopt(fd, level, option, &value, sizeof(value)))); } static void Posix_setuid(JNIEnv* env, jobject, jint uid) { throwIfMinusOne(env, "setuid", TEMP_FAILURE_RETRY(setuid(uid))); } static void Posix_shutdown(JNIEnv* env, jobject, jobject javaFd, jint how) { int fd = jniGetFDFromFileDescriptor(env, javaFd); throwIfMinusOne(env, "shutdown", TEMP_FAILURE_RETRY(shutdown(fd, how))); } static jobject Posix_socket(JNIEnv* env, jobject, jint domain, jint type, jint protocol) { int fd = throwIfMinusOne(env, "socket", TEMP_FAILURE_RETRY(socket(domain, type, protocol))); return fd != -1 ? jniCreateFileDescriptor(env, fd) : NULL; } static void Posix_socketpair(JNIEnv* env, jobject, jint domain, jint type, jint protocol, jobject javaFd1, jobject javaFd2) { int fds[2]; int rc = throwIfMinusOne(env, "socketpair", TEMP_FAILURE_RETRY(socketpair(domain, type, protocol, fds))); if (rc != -1) { jniSetFileDescriptorOfFD(env, javaFd1, fds[0]); jniSetFileDescriptorOfFD(env, javaFd2, fds[1]); } } static jobject Posix_stat(JNIEnv* env, jobject, jstring javaPath) { return doStat(env, javaPath, false); } static jobject Posix_statvfs(JNIEnv* env, jobject, jstring javaPath) { ScopedUtfChars path(env, javaPath); if (path.c_str() == NULL) { return NULL; } struct statvfs sb; int rc = TEMP_FAILURE_RETRY(statvfs(path.c_str(), &sb)); if (rc == -1) { throwErrnoException(env, "statvfs"); return NULL; } return makeStructStatVfs(env, sb); } static jstring Posix_strerror(JNIEnv* env, jobject, jint errnum) { char buffer[BUFSIZ]; const char* message = jniStrError(errnum, buffer, sizeof(buffer)); return env->NewStringUTF(message); } static jstring Posix_strsignal(JNIEnv* env, jobject, jint signal) { return env->NewStringUTF(strsignal(signal)); } static void Posix_symlink(JNIEnv* env, jobject, jstring javaOldPath, jstring javaNewPath) { ScopedUtfChars oldPath(env, javaOldPath); if (oldPath.c_str() == NULL) { return; } ScopedUtfChars newPath(env, javaNewPath); if (newPath.c_str() == NULL) { return; } throwIfMinusOne(env, "symlink", TEMP_FAILURE_RETRY(symlink(oldPath.c_str(), newPath.c_str()))); } static jlong Posix_sysconf(JNIEnv* env, jobject, jint name) { // Since -1 is a valid result from sysconf(3), detecting failure is a little more awkward. errno = 0; long result = sysconf(name); if (result == -1L && errno == EINVAL) { throwErrnoException(env, "sysconf"); } return result; } static void Posix_tcdrain(JNIEnv* env, jobject, jobject javaFd) { int fd = jniGetFDFromFileDescriptor(env, javaFd); throwIfMinusOne(env, "tcdrain", TEMP_FAILURE_RETRY(tcdrain(fd))); } static void Posix_tcsendbreak(JNIEnv* env, jobject, jobject javaFd, jint duration) { int fd = jniGetFDFromFileDescriptor(env, javaFd); throwIfMinusOne(env, "tcsendbreak", TEMP_FAILURE_RETRY(tcsendbreak(fd, duration))); } static jint Posix_umaskImpl(JNIEnv*, jobject, jint mask) { return umask(mask); } static jobject Posix_uname(JNIEnv* env, jobject) { struct utsname buf; if (TEMP_FAILURE_RETRY(uname(&buf)) == -1) { return NULL; // Can't happen. } return makeStructUtsname(env, buf); } static void Posix_unsetenv(JNIEnv* env, jobject, jstring javaName) { ScopedUtfChars name(env, javaName); if (name.c_str() == NULL) { return; } throwIfMinusOne(env, "unsetenv", unsetenv(name.c_str())); } static jint Posix_waitpid(JNIEnv* env, jobject, jint pid, jobject javaStatus, jint options) { int status; int rc = throwIfMinusOne(env, "waitpid", TEMP_FAILURE_RETRY(waitpid(pid, &status, options))); if (rc != -1) { static jfieldID valueFid = env->GetFieldID(JniConstants::mutableIntClass, "value", "I"); env->SetIntField(javaStatus, valueFid, status); } return rc; } static jint Posix_writeBytes(JNIEnv* env, jobject, jobject javaFd, jbyteArray javaBytes, jint byteOffset, jint byteCount) { ScopedBytesRO bytes(env, javaBytes); if (bytes.get() == NULL) { return -1; } return IO_FAILURE_RETRY(env, ssize_t, write, javaFd, bytes.get() + byteOffset, byteCount); } static jint Posix_writev(JNIEnv* env, jobject, jobject javaFd, jobjectArray buffers, jintArray offsets, jintArray byteCounts) { IoVec<ScopedBytesRO> ioVec(env, env->GetArrayLength(buffers)); if (!ioVec.init(buffers, offsets, byteCounts)) { return -1; } return IO_FAILURE_RETRY(env, ssize_t, writev, javaFd, ioVec.get(), ioVec.size()); } static JNINativeMethod gMethods[] = { NATIVE_METHOD(Posix, accept, "(Ljava/io/FileDescriptor;Ljava/net/InetSocketAddress;)Ljava/io/FileDescriptor;"), NATIVE_METHOD(Posix, access, "(Ljava/lang/String;I)Z"), NATIVE_METHOD(Posix, android_getaddrinfo, "(Ljava/lang/String;Landroid/system/StructAddrinfo;I)[Ljava/net/InetAddress;"), NATIVE_METHOD(Posix, bind, "(Ljava/io/FileDescriptor;Ljava/net/InetAddress;I)V"), NATIVE_METHOD(Posix, chmod, "(Ljava/lang/String;I)V"), NATIVE_METHOD(Posix, chown, "(Ljava/lang/String;II)V"), NATIVE_METHOD(Posix, close, "(Ljava/io/FileDescriptor;)V"), NATIVE_METHOD(Posix, connect, "(Ljava/io/FileDescriptor;Ljava/net/InetAddress;I)V"), NATIVE_METHOD(Posix, dup, "(Ljava/io/FileDescriptor;)Ljava/io/FileDescriptor;"), NATIVE_METHOD(Posix, dup2, "(Ljava/io/FileDescriptor;I)Ljava/io/FileDescriptor;"), NATIVE_METHOD(Posix, environ, "()[Ljava/lang/String;"), NATIVE_METHOD(Posix, execv, "(Ljava/lang/String;[Ljava/lang/String;)V"), NATIVE_METHOD(Posix, execve, "(Ljava/lang/String;[Ljava/lang/String;[Ljava/lang/String;)V"), NATIVE_METHOD(Posix, fchmod, "(Ljava/io/FileDescriptor;I)V"), NATIVE_METHOD(Posix, fchown, "(Ljava/io/FileDescriptor;II)V"), NATIVE_METHOD(Posix, fcntlVoid, "(Ljava/io/FileDescriptor;I)I"), NATIVE_METHOD(Posix, fcntlLong, "(Ljava/io/FileDescriptor;IJ)I"), NATIVE_METHOD(Posix, fcntlFlock, "(Ljava/io/FileDescriptor;ILandroid/system/StructFlock;)I"), NATIVE_METHOD(Posix, fdatasync, "(Ljava/io/FileDescriptor;)V"), NATIVE_METHOD(Posix, fstat, "(Ljava/io/FileDescriptor;)Landroid/system/StructStat;"), NATIVE_METHOD(Posix, fstatvfs, "(Ljava/io/FileDescriptor;)Landroid/system/StructStatVfs;"), NATIVE_METHOD(Posix, fsync, "(Ljava/io/FileDescriptor;)V"), NATIVE_METHOD(Posix, ftruncate, "(Ljava/io/FileDescriptor;J)V"), NATIVE_METHOD(Posix, gai_strerror, "(I)Ljava/lang/String;"), NATIVE_METHOD(Posix, getegid, "()I"), NATIVE_METHOD(Posix, geteuid, "()I"), NATIVE_METHOD(Posix, getgid, "()I"), NATIVE_METHOD(Posix, getenv, "(Ljava/lang/String;)Ljava/lang/String;"), NATIVE_METHOD(Posix, getnameinfo, "(Ljava/net/InetAddress;I)Ljava/lang/String;"), NATIVE_METHOD(Posix, getpeername, "(Ljava/io/FileDescriptor;)Ljava/net/SocketAddress;"), NATIVE_METHOD(Posix, getpid, "()I"), NATIVE_METHOD(Posix, getppid, "()I"), NATIVE_METHOD(Posix, getpwnam, "(Ljava/lang/String;)Landroid/system/StructPasswd;"), NATIVE_METHOD(Posix, getpwuid, "(I)Landroid/system/StructPasswd;"), NATIVE_METHOD(Posix, getsockname, "(Ljava/io/FileDescriptor;)Ljava/net/SocketAddress;"), NATIVE_METHOD(Posix, getsockoptByte, "(Ljava/io/FileDescriptor;II)I"), NATIVE_METHOD(Posix, getsockoptInAddr, "(Ljava/io/FileDescriptor;II)Ljava/net/InetAddress;"), NATIVE_METHOD(Posix, getsockoptInt, "(Ljava/io/FileDescriptor;II)I"), NATIVE_METHOD(Posix, getsockoptLinger, "(Ljava/io/FileDescriptor;II)Landroid/system/StructLinger;"), NATIVE_METHOD(Posix, getsockoptTimeval, "(Ljava/io/FileDescriptor;II)Landroid/system/StructTimeval;"), NATIVE_METHOD(Posix, getsockoptUcred, "(Ljava/io/FileDescriptor;II)Landroid/system/StructUcred;"), NATIVE_METHOD(Posix, gettid, "()I"), NATIVE_METHOD(Posix, getuid, "()I"), NATIVE_METHOD(Posix, if_indextoname, "(I)Ljava/lang/String;"), NATIVE_METHOD(Posix, inet_pton, "(ILjava/lang/String;)Ljava/net/InetAddress;"), NATIVE_METHOD(Posix, ioctlInetAddress, "(Ljava/io/FileDescriptor;ILjava/lang/String;)Ljava/net/InetAddress;"), NATIVE_METHOD(Posix, ioctlInt, "(Ljava/io/FileDescriptor;ILandroid/util/MutableInt;)I"), NATIVE_METHOD(Posix, isatty, "(Ljava/io/FileDescriptor;)Z"), NATIVE_METHOD(Posix, kill, "(II)V"), NATIVE_METHOD(Posix, lchown, "(Ljava/lang/String;II)V"), NATIVE_METHOD(Posix, link, "(Ljava/lang/String;Ljava/lang/String;)V"), NATIVE_METHOD(Posix, listen, "(Ljava/io/FileDescriptor;I)V"), NATIVE_METHOD(Posix, lseek, "(Ljava/io/FileDescriptor;JI)J"), NATIVE_METHOD(Posix, lstat, "(Ljava/lang/String;)Landroid/system/StructStat;"), NATIVE_METHOD(Posix, mincore, "(JJ[B)V"), NATIVE_METHOD(Posix, mkdir, "(Ljava/lang/String;I)V"), NATIVE_METHOD(Posix, mkfifo, "(Ljava/lang/String;I)V"), NATIVE_METHOD(Posix, mlock, "(JJ)V"), NATIVE_METHOD(Posix, mmap, "(JJIILjava/io/FileDescriptor;J)J"), NATIVE_METHOD(Posix, msync, "(JJI)V"), NATIVE_METHOD(Posix, munlock, "(JJ)V"), NATIVE_METHOD(Posix, munmap, "(JJ)V"), NATIVE_METHOD(Posix, open, "(Ljava/lang/String;II)Ljava/io/FileDescriptor;"), NATIVE_METHOD(Posix, pipe, "()[Ljava/io/FileDescriptor;"), NATIVE_METHOD(Posix, poll, "([Landroid/system/StructPollfd;I)I"), NATIVE_METHOD(Posix, posix_fallocate, "(Ljava/io/FileDescriptor;JJ)V"), NATIVE_METHOD(Posix, prctl, "(IJJJJ)I"), NATIVE_METHOD(Posix, preadBytes, "(Ljava/io/FileDescriptor;Ljava/lang/Object;IIJ)I"), NATIVE_METHOD(Posix, pwriteBytes, "(Ljava/io/FileDescriptor;Ljava/lang/Object;IIJ)I"), NATIVE_METHOD(Posix, readBytes, "(Ljava/io/FileDescriptor;Ljava/lang/Object;II)I"), NATIVE_METHOD(Posix, readlink, "(Ljava/lang/String;)Ljava/lang/String;"), NATIVE_METHOD(Posix, readv, "(Ljava/io/FileDescriptor;[Ljava/lang/Object;[I[I)I"), NATIVE_METHOD(Posix, recvfromBytes, "(Ljava/io/FileDescriptor;Ljava/lang/Object;IIILjava/net/InetSocketAddress;)I"), NATIVE_METHOD(Posix, remove, "(Ljava/lang/String;)V"), NATIVE_METHOD(Posix, rename, "(Ljava/lang/String;Ljava/lang/String;)V"), NATIVE_METHOD(Posix, sendfile, "(Ljava/io/FileDescriptor;Ljava/io/FileDescriptor;Landroid/util/MutableLong;J)J"), NATIVE_METHOD(Posix, sendtoBytes, "(Ljava/io/FileDescriptor;Ljava/lang/Object;IIILjava/net/InetAddress;I)I"), NATIVE_METHOD(Posix, setegid, "(I)V"), NATIVE_METHOD(Posix, setenv, "(Ljava/lang/String;Ljava/lang/String;Z)V"), NATIVE_METHOD(Posix, seteuid, "(I)V"), NATIVE_METHOD(Posix, setgid, "(I)V"), NATIVE_METHOD(Posix, setsid, "()I"), NATIVE_METHOD(Posix, setsockoptByte, "(Ljava/io/FileDescriptor;III)V"), NATIVE_METHOD(Posix, setsockoptIfreq, "(Ljava/io/FileDescriptor;IILjava/lang/String;)V"), NATIVE_METHOD(Posix, setsockoptInt, "(Ljava/io/FileDescriptor;III)V"), NATIVE_METHOD(Posix, setsockoptIpMreqn, "(Ljava/io/FileDescriptor;III)V"), NATIVE_METHOD(Posix, setsockoptGroupReq, "(Ljava/io/FileDescriptor;IILandroid/system/StructGroupReq;)V"), NATIVE_METHOD(Posix, setsockoptGroupSourceReq, "(Ljava/io/FileDescriptor;IILandroid/system/StructGroupSourceReq;)V"), NATIVE_METHOD(Posix, setsockoptLinger, "(Ljava/io/FileDescriptor;IILandroid/system/StructLinger;)V"), NATIVE_METHOD(Posix, setsockoptTimeval, "(Ljava/io/FileDescriptor;IILandroid/system/StructTimeval;)V"), NATIVE_METHOD(Posix, setuid, "(I)V"), NATIVE_METHOD(Posix, shutdown, "(Ljava/io/FileDescriptor;I)V"), NATIVE_METHOD(Posix, socket, "(III)Ljava/io/FileDescriptor;"), NATIVE_METHOD(Posix, socketpair, "(IIILjava/io/FileDescriptor;Ljava/io/FileDescriptor;)V"), NATIVE_METHOD(Posix, stat, "(Ljava/lang/String;)Landroid/system/StructStat;"), NATIVE_METHOD(Posix, statvfs, "(Ljava/lang/String;)Landroid/system/StructStatVfs;"), NATIVE_METHOD(Posix, strerror, "(I)Ljava/lang/String;"), NATIVE_METHOD(Posix, strsignal, "(I)Ljava/lang/String;"), NATIVE_METHOD(Posix, symlink, "(Ljava/lang/String;Ljava/lang/String;)V"), NATIVE_METHOD(Posix, sysconf, "(I)J"), NATIVE_METHOD(Posix, tcdrain, "(Ljava/io/FileDescriptor;)V"), NATIVE_METHOD(Posix, tcsendbreak, "(Ljava/io/FileDescriptor;I)V"), NATIVE_METHOD(Posix, umaskImpl, "(I)I"), NATIVE_METHOD(Posix, uname, "()Landroid/system/StructUtsname;"), NATIVE_METHOD(Posix, unsetenv, "(Ljava/lang/String;)V"), NATIVE_METHOD(Posix, waitpid, "(ILandroid/util/MutableInt;I)I"), NATIVE_METHOD(Posix, writeBytes, "(Ljava/io/FileDescriptor;Ljava/lang/Object;II)I"), NATIVE_METHOD(Posix, writev, "(Ljava/io/FileDescriptor;[Ljava/lang/Object;[I[I)I"), }; void register_libcore_io_Posix(JNIEnv* env) { jniRegisterNativeMethods(env, "libcore/io/Posix", gMethods, NELEM(gMethods)); }
s20121035/rk3288_android5.1_repo
libcore/luni/src/main/native/libcore_io_Posix.cpp
C++
gpl-3.0
68,241
// Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) package MJDecompiler; import java.io.IOException; // Referenced classes of package MJDecompiler: // bm, bf, bh, bj, // bc final class as extends CpField { as(ClazzInputStream bc, ClassFile bj1) throws IOException { super(bc, bj1); } final void writeBytecode(ByteCodeOutput bf1) throws IOException { bf1.writeByte(9); bf1.writeUshort(super.b); bf1.writeUshort(super.o); } final String type() { return super.a.getConstant(super.o).type(); } final String a(ClassFile bj1) { return "FieldRef(" + super.b + ":" + bj1.getConstant(super.b).a(bj1) + ", " + super.o + ":" + bj1.getConstant(super.o).a(bj1) + ")"; } }
ghostgzt/STX
src/MJDecompiler/as.java
Java
gpl-3.0
839
package com.zalthrion.zylroth.handler; import net.minecraft.client.settings.KeyBinding; import org.lwjgl.input.Keyboard; import cpw.mods.fml.client.registry.ClientRegistry; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; public class KeyHandler { @SideOnly(Side.CLIENT) public static KeyBinding openSummonGui; public static void init() { openSummonGui = new KeyBinding("key.zylroth:summongui", Keyboard.KEY_Z, "key.categories.zylroth"); ClientRegistry.registerKeyBinding(openSummonGui); } }
Zalthrion/Zyl-Roth
src/main/java/com/zalthrion/zylroth/handler/KeyHandler.java
Java
gpl-3.0
533
/* * Copyright (c) 2014 Ian Bondoc * * This file is part of Jen8583 * * Jen8583 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. * * Jen8583 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.chiknrice.iso.codec; import org.chiknrice.iso.config.ComponentDef.Encoding; import java.nio.ByteBuffer; /** * The main contract for a codec used across encoding and decoding of message components. Each field/component of the * ISO message would have its own instance of codec which contains the definition of how the value should be * encoded/decoded. The codec should be designed to be thread safe as the instance would live throughout the life of the * IsoMessageDef. Any issues encountered during encoding/decoding should be throwing a CodecException. Any issues * encountered during codec configuration/construction the constructor should throw a ConfigException. A ConfigException * should generally happen during startup while CodecException happens when the Codec is being used. * * @author <a href="mailto:[email protected]">Ian Bondoc</a> */ public interface Codec<T> { /** * The implementation should define how the value T should be decoded from the ByteBuffer provided. The * implementation could either decode the value from a certain number of bytes or consume the whole ByteBuffer. * * @param buf * @return the decoded value */ T decode(ByteBuffer buf); /** * The implementation should define how the value T should be encoded to the ByteBuffer provided. The ByteBuffer * assumes the value would be encoded from the current position. * * @param buf * @param value the value to be encoded */ void encode(ByteBuffer buf, T value); /** * Defines how the value should be encoded/decoded. * * @return the encoding defined for the value. */ Encoding getEncoding(); }
chiknrice/jen8583
src/main/java/org/chiknrice/iso/codec/Codec.java
Java
gpl-3.0
2,477
#!/usr/bin/env python # # Copyright 2011 Facebook # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Miscellaneous network utility code.""" from __future__ import absolute_import, division, print_function, with_statement import errno import os import re import socket import ssl import stat from lib.tornado.concurrent import dummy_executor, run_on_executor from lib.tornado.ioloop import IOLoop from lib.tornado.platform.auto import set_close_exec from lib.tornado.util import Configurable def bind_sockets(port, address=None, family=socket.AF_UNSPEC, backlog=128, flags=None): """Creates listening sockets bound to the given port and address. Returns a list of socket objects (multiple sockets are returned if the given address maps to multiple IP addresses, which is most common for mixed IPv4 and IPv6 use). Address may be either an IP address or hostname. If it's a hostname, the server will listen on all IP addresses associated with the name. Address may be an empty string or None to listen on all available interfaces. Family may be set to either `socket.AF_INET` or `socket.AF_INET6` to restrict to IPv4 or IPv6 addresses, otherwise both will be used if available. The ``backlog`` argument has the same meaning as for `socket.listen() <socket.socket.listen>`. ``flags`` is a bitmask of AI_* flags to `~socket.getaddrinfo`, like ``socket.AI_PASSIVE | socket.AI_NUMERICHOST``. """ sockets = [] if address == "": address = None if not socket.has_ipv6 and family == socket.AF_UNSPEC: # Python can be compiled with --disable-ipv6, which causes # operations on AF_INET6 sockets to fail, but does not # automatically exclude those results from getaddrinfo # results. # http://bugs.python.org/issue16208 family = socket.AF_INET if flags is None: flags = socket.AI_PASSIVE for res in set(socket.getaddrinfo(address, port, family, socket.SOCK_STREAM, 0, flags)): af, socktype, proto, canonname, sockaddr = res sock = socket.socket(af, socktype, proto) set_close_exec(sock.fileno()) if os.name != 'nt': sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if af == socket.AF_INET6: # On linux, ipv6 sockets accept ipv4 too by default, # but this makes it impossible to bind to both # 0.0.0.0 in ipv4 and :: in ipv6. On other systems, # separate sockets *must* be used to listen for both ipv4 # and ipv6. For consistency, always disable ipv4 on our # ipv6 sockets and use a separate ipv4 socket when needed. # # Python 2.x on windows doesn't have IPPROTO_IPV6. if hasattr(socket, "IPPROTO_IPV6"): sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1) sock.setblocking(0) sock.bind(sockaddr) sock.listen(backlog) sockets.append(sock) return sockets if hasattr(socket, 'AF_UNIX'): def bind_unix_socket(file, mode=0o600, backlog=128): """Creates a listening unix socket. If a socket with the given name already exists, it will be deleted. If any other file with that name exists, an exception will be raised. Returns a socket object (not a list of socket objects like `bind_sockets`) """ sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) set_close_exec(sock.fileno()) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.setblocking(0) try: st = os.stat(file) except OSError as err: if err.errno != errno.ENOENT: raise else: if stat.S_ISSOCK(st.st_mode): os.remove(file) else: raise ValueError("File %s exists and is not a socket", file) sock.bind(file) os.chmod(file, mode) sock.listen(backlog) return sock def add_accept_handler(sock, callback, io_loop=None): """Adds an `.IOLoop` event handler to accept new connections on ``sock``. When a connection is accepted, ``callback(connection, address)`` will be run (``connection`` is a socket object, and ``address`` is the address of the other end of the connection). Note that this signature is different from the ``callback(fd, events)`` signature used for `.IOLoop` handlers. """ if io_loop is None: io_loop = IOLoop.current() def accept_handler(fd, events): while True: try: connection, address = sock.accept() except socket.error as e: if e.args[0] in (errno.EWOULDBLOCK, errno.EAGAIN): return raise callback(connection, address) io_loop.add_handler(sock.fileno(), accept_handler, IOLoop.READ) def is_valid_ip(ip): """Returns true if the given string is a well-formed IP address. Supports IPv4 and IPv6. """ try: res = socket.getaddrinfo(ip, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_NUMERICHOST) return bool(res) except socket.gaierror as e: if e.args[0] == socket.EAI_NONAME: return False raise return True class Resolver(Configurable): """Configurable asynchronous DNS resolver interface. By default, a blocking implementation is used (which simply calls `socket.getaddrinfo`). An alternative implementation can be chosen with the `Resolver.configure <.Configurable.configure>` class method:: Resolver.configure('tornado.netutil.ThreadedResolver') The implementations of this interface included with Tornado are * `tornado.netutil.BlockingResolver` * `tornado.netutil.ThreadedResolver` * `tornado.netutil.OverrideResolver` * `tornado.platform.twisted.TwistedResolver` * `tornado.platform.caresresolver.CaresResolver` """ @classmethod def configurable_base(cls): return Resolver @classmethod def configurable_default(cls): return BlockingResolver def resolve(self, host, port, family=socket.AF_UNSPEC, callback=None): """Resolves an address. The ``host`` argument is a string which may be a hostname or a literal IP address. Returns a `.Future` whose result is a list of (family, address) pairs, where address is a tuple suitable to pass to `socket.connect <socket.socket.connect>` (i.e. a ``(host, port)`` pair for IPv4; additional fields may be present for IPv6). If a ``callback`` is passed, it will be run with the result as an argument when it is complete. """ raise NotImplementedError() class ExecutorResolver(Resolver): def initialize(self, io_loop=None, executor=None): self.io_loop = io_loop or IOLoop.current() self.executor = executor or dummy_executor @run_on_executor def resolve(self, host, port, family=socket.AF_UNSPEC): addrinfo = socket.getaddrinfo(host, port, family) results = [] for family, socktype, proto, canonname, address in addrinfo: results.append((family, address)) return results class BlockingResolver(ExecutorResolver): """Default `Resolver` implementation, using `socket.getaddrinfo`. The `.IOLoop` will be blocked during the resolution, although the callback will not be run until the next `.IOLoop` iteration. """ def initialize(self, io_loop=None): super(BlockingResolver, self).initialize(io_loop=io_loop) class ThreadedResolver(ExecutorResolver): """Multithreaded non-blocking `Resolver` implementation. Requires the `concurrent.futures` package to be installed (available in the standard library since Python 3.2, installable with ``pip install futures`` in older versions). The thread pool size can be configured with:: Resolver.configure('tornado.netutil.ThreadedResolver', num_threads=10) """ def initialize(self, io_loop=None, num_threads=10): from concurrent.futures import ThreadPoolExecutor super(ThreadedResolver, self).initialize( io_loop=io_loop, executor=ThreadPoolExecutor(num_threads)) class OverrideResolver(Resolver): """Wraps a resolver with a mapping of overrides. This can be used to make local DNS changes (e.g. for testing) without modifying system-wide settings. The mapping can contain either host strings or host-port pairs. """ def initialize(self, resolver, mapping): self.resolver = resolver self.mapping = mapping def resolve(self, host, port, *args, **kwargs): if (host, port) in self.mapping: host, port = self.mapping[(host, port)] elif host in self.mapping: host = self.mapping[host] return self.resolver.resolve(host, port, *args, **kwargs) # These are the keyword arguments to ssl.wrap_socket that must be translated # to their SSLContext equivalents (the other arguments are still passed # to SSLContext.wrap_socket). _SSL_CONTEXT_KEYWORDS = frozenset(['ssl_version', 'certfile', 'keyfile', 'cert_reqs', 'ca_certs', 'ciphers']) def ssl_options_to_context(ssl_options): """Try to convert an ``ssl_options`` dictionary to an `~ssl.SSLContext` object. The ``ssl_options`` dictionary contains keywords to be passed to `ssl.wrap_socket`. In Python 3.2+, `ssl.SSLContext` objects can be used instead. This function converts the dict form to its `~ssl.SSLContext` equivalent, and may be used when a component which accepts both forms needs to upgrade to the `~ssl.SSLContext` version to use features like SNI or NPN. """ if isinstance(ssl_options, dict): assert all(k in _SSL_CONTEXT_KEYWORDS for k in ssl_options), ssl_options if (not hasattr(ssl, 'SSLContext') or isinstance(ssl_options, ssl.SSLContext)): return ssl_options context = ssl.SSLContext( ssl_options.get('ssl_version', ssl.PROTOCOL_SSLv23)) if 'certfile' in ssl_options: context.load_cert_chain(ssl_options['certfile'], ssl_options.get('keyfile', None)) if 'cert_reqs' in ssl_options: context.verify_mode = ssl_options['cert_reqs'] if 'ca_certs' in ssl_options: context.load_verify_locations(ssl_options['ca_certs']) if 'ciphers' in ssl_options: context.set_ciphers(ssl_options['ciphers']) return context def ssl_wrap_socket(socket, ssl_options, server_hostname=None, **kwargs): """Returns an ``ssl.SSLSocket`` wrapping the given socket. ``ssl_options`` may be either a dictionary (as accepted by `ssl_options_to_context`) or an `ssl.SSLContext` object. Additional keyword arguments are passed to ``wrap_socket`` (either the `~ssl.SSLContext` method or the `ssl` module function as appropriate). """ context = ssl_options_to_context(ssl_options) if hasattr(ssl, 'SSLContext') and isinstance(context, ssl.SSLContext): if server_hostname is not None and getattr(ssl, 'HAS_SNI'): # Python doesn't have server-side SNI support so we can't # really unittest this, but it can be manually tested with # python3.2 -m tornado.httpclient https://sni.velox.ch return context.wrap_socket(socket, server_hostname=server_hostname, **kwargs) else: return context.wrap_socket(socket, **kwargs) else: return ssl.wrap_socket(socket, **dict(context, **kwargs)) if hasattr(ssl, 'match_hostname'): # python 3.2+ ssl_match_hostname = ssl.match_hostname SSLCertificateError = ssl.CertificateError else: # match_hostname was added to the standard library ssl module in python 3.2. # The following code was backported for older releases and copied from # https://bitbucket.org/brandon/backports.ssl_match_hostname class SSLCertificateError(ValueError): pass def _dnsname_to_pat(dn): pats = [] for frag in dn.split(r'.'): if frag == '*': # When '*' is a fragment by itself, it matches a non-empty dotless # fragment. pats.append('[^.]+') else: # Otherwise, '*' matches any dotless fragment. frag = re.escape(frag) pats.append(frag.replace(r'\*', '[^.]*')) return re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE) def ssl_match_hostname(cert, hostname): """Verify that *cert* (in decoded format as returned by SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 rules are mostly followed, but IP addresses are not accepted for *hostname*. CertificateError is raised on failure. On success, the function returns nothing. """ if not cert: raise ValueError("empty or no certificate") dnsnames = [] san = cert.get('subjectAltName', ()) for key, value in san: if key == 'DNS': if _dnsname_to_pat(value).match(hostname): return dnsnames.append(value) if not san: # The subject is only checked when subjectAltName is empty for sub in cert.get('subject', ()): for key, value in sub: # XXX according to RFC 2818, the most specific Common Name # must be used. if key == 'commonName': if _dnsname_to_pat(value).match(hostname): return dnsnames.append(value) if len(dnsnames) > 1: raise SSLCertificateError("hostname %r " "doesn't match either of %s" % (hostname, ', '.join(map(repr, dnsnames)))) elif len(dnsnames) == 1: raise SSLCertificateError("hostname %r " "doesn't match %r" % (hostname, dnsnames[0])) else: raise SSLCertificateError("no appropriate commonName or " "subjectAltName fields were found")
mountainpenguin/BySH
server/lib/tornado/netutil.py
Python
gpl-3.0
15,081
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MiniQuick.Events { public class BaseEvent : IEvent { private int _MaxRetryCount = 3; private TimeSpan _timeinterval = TimeSpan.FromMilliseconds(1000); public string CommandId { get; set; } public int RetryCount { get { return this._MaxRetryCount; } } public TimeSpan Timeinterval { get { return this._timeinterval; } } } }
fzf003/MiniQuick
MiniQuick/Events/BaseEvent.cs
C#
gpl-3.0
606
/************************************************************************ Copyright 2008 Mark Pictor This file is part of RS274NGC. RS274NGC 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. RS274NGC 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 RS274NGC. If not, see <http://www.gnu.org/licenses/>. This software is based on software that was produced by the National Institute of Standards and Technology (NIST). ************************************************************************/ #include "stdafx.h" extern CANON_TOOL_TABLE _tools[]; /* in canon.cc */ extern int _tool_max; /* in canon.cc */ extern char _parameter_file_name[100]; /* in canon.cc */ FILE * _outfile; /* where to print, set in main */ /* This file contains the source code for an emulation of using the six-axis rs274 interpreter from the EMC system. */ /*********************************************************************/ /* report_error Returned Value: none Side effects: an error message is printed on stderr Called by: interpret_from_file interpret_from_keyboard main This 1. calls rs274ngc_error_text to get the text of the error message whose code is error_code and prints the message, 2. calls rs274ngc_line_text to get the text of the line on which the error occurred and prints the text, and 3. if print_stack is on, repeatedly calls rs274ngc_stack_name to get the names of the functions on the function call stack and prints the names. The first function named is the one that sent the error message. */ void report_error( /* ARGUMENTS */ int error_code, /* the code number of the error message */ int print_stack) /* print stack if ON, otherwise not */ { char buffer[RS274NGC_TEXT_SIZE]; int k; rs274ngc_error_text(error_code, buffer, sizeof(buffer), 5); /* for coverage of code */ rs274ngc_error_text(error_code, buffer, sizeof(buffer), RS274NGC_TEXT_SIZE); fprintf(stderr, "%s\n", ((buffer[0] IS 0) ? "Unknown error, bad error code" : buffer)); rs274ngc_line_text(buffer, RS274NGC_TEXT_SIZE); fprintf(stderr, "%s\n", buffer); if (print_stack IS ON) { for (k SET_TO 0; ; k++) { rs274ngc_stack_name(k, buffer, RS274NGC_TEXT_SIZE); if (buffer[0] ISNT 0) fprintf(stderr, "%s\n", buffer); else break; } } } /***********************************************************************/ /* interpret_from_keyboard Returned Value: int (0) Side effects: Lines of NC code entered by the user are interpreted. Called by: interpret_from_file main This prompts the user to enter a line of rs274 code. When the user hits <enter> at the end of the line, the line is executed. Then the user is prompted to enter another line. Any canonical commands resulting from executing the line are printed on the monitor (stdout). If there is an error in reading or executing the line, an error message is printed on the monitor (stderr). To exit, the user must enter "quit" (followed by a carriage return). */ int interpret_from_keyboard( /* ARGUMENTS */ int block_delete, /* switch which is ON or OFF */ int print_stack) /* option which is ON or OFF */ { char line[RS274NGC_TEXT_SIZE]; int status; for(; ;) { printf("READ => "); fgets(line, sizeof(line), stdin); if (strcmp (line, "quit") IS 0) return 0; status SET_TO rs274ngc_read(line); if ((status IS RS274NGC_EXECUTE_FINISH) AND (block_delete IS ON)); else if (status IS RS274NGC_ENDFILE); else if ((status ISNT RS274NGC_EXECUTE_FINISH) AND (status ISNT RS274NGC_OK)) report_error(status, print_stack); else { status SET_TO rs274ngc_execute(); if ((status IS RS274NGC_EXIT) OR (status IS RS274NGC_EXECUTE_FINISH)); else if (status ISNT RS274NGC_OK) report_error(status, print_stack); } } } /*********************************************************************/ /* interpret_from_file Returned Value: int (0 or 1) If any of the following errors occur, this returns 1. Otherwise, it returns 0. 1. rs274ngc_read returns something other than RS274NGC_OK or RS274NGC_EXECUTE_FINISH, no_stop is off, and the user elects not to continue. 2. rs274ngc_execute returns something other than RS274NGC_OK, EXIT, or RS274NGC_EXECUTE_FINISH, no_stop is off, and the user elects not to continue. Side Effects: An open NC-program file is interpreted. Called By: main This emulates the way the EMC system uses the interpreter. If the do_next argument is 1, this goes into MDI mode if an error is found. In that mode, the user may (1) enter code or (2) enter "quit" to get out of MDI. Once out of MDI, this asks the user whether to continue interpreting the file. If the do_next argument is 0, an error does not stop interpretation. If the do_next argument is 2, an error stops interpretation. */ int interpret_from_file( /* ARGUMENTS */ int do_next, /* what to do if error */ int block_delete, /* switch which is ON or OFF */ int print_stack) /* option which is ON or OFF */ { int status; char line[RS274NGC_TEXT_SIZE]; for(; ;) { status SET_TO rs274ngc_read(NULL); if ((status IS RS274NGC_EXECUTE_FINISH) AND (block_delete IS ON)) continue; else if (status IS RS274NGC_ENDFILE) break; if ((status ISNT RS274NGC_OK) AND // should not be EXIT (status ISNT RS274NGC_EXECUTE_FINISH)) { report_error(status, print_stack); if ((status IS NCE_FILE_ENDED_WITH_NO_PERCENT_SIGN) OR (do_next IS 2)) /* 2 means stop */ { status SET_TO 1; break; } else if (do_next IS 1) /* 1 means MDI */ { fprintf(stderr, "starting MDI\n"); interpret_from_keyboard(block_delete, print_stack); fprintf(stderr, "continue program? y/n =>"); fgets(line, sizeof(line), stdin); if (line[0] ISNT 'y') { status SET_TO 1; break; } else continue; } else /* if do_next IS 0 -- 0 means continue */ continue; } status SET_TO rs274ngc_execute(); if ((status ISNT RS274NGC_OK) AND (status ISNT RS274NGC_EXIT) AND (status ISNT RS274NGC_EXECUTE_FINISH)) { report_error(status, print_stack); status SET_TO 1; if (do_next IS 1) /* 1 means MDI */ { fprintf(stderr, "starting MDI\n"); interpret_from_keyboard(block_delete, print_stack); fprintf(stderr, "continue program? y/n =>"); fgets(line,sizeof(line), stdin); if (line[0] ISNT 'y') break; } else if (do_next IS 2) /* 2 means stop */ break; } else if (status IS RS274NGC_EXIT) break; } return ((status IS 1) ? 1 : 0); } /************************************************************************/ /* read_tool_file Returned Value: int If any of the following errors occur, this returns 1. Otherwise, it returns 0. 1. The file named by the user cannot be opened. 2. No blank line is found. 3. A line of data cannot be read. 4. A tool slot number is less than 1 or >= _tool_max Side Effects: Values in the tool table of the machine setup are changed, as specified in the file. Called By: main Tool File Format ----------------- Everything above the first blank line is read and ignored, so any sort of header material may be used. Everything after the first blank line should be data. Each line of data should have four or more items separated by white space. The four required items are slot, tool id, tool length offset, and tool diameter. Other items might be the holder id and tool description, but these are optional and will not be read. Here is a sample line: 20 1419 4.299 1.0 1 inch carbide end mill The tool_table is indexed by slot number. */ int read_tool_file( /* ARGUMENTS */ char * file_name) /* name of tool file */ { FILE * tool_file_port; char buffer[1000]; int slot; int tool_id; double offset; double diameter; if (file_name[0] IS 0) /* ask for name if given name is empty string */ { fprintf(stderr, "name of tool file => "); fgets(buffer, sizeof(buffer), stdin); fopen_s(&tool_file_port,buffer, "r"); } else fopen_s(&tool_file_port,file_name, "r"); if (tool_file_port IS NULL) { fprintf(stderr, "Cannot open %s\n", ((file_name[0] IS 0) ? buffer : file_name)); return 1; } for(;;) /* read and discard header, checking for blank line */ { if (fgets(buffer, 1000, tool_file_port) IS NULL) { fprintf(stderr, "Bad tool file format\n"); return 1; } else if (buffer[0] IS '\n') break; } for (slot SET_TO 0; slot <= _tool_max; slot++)/* initialize */ { _tools[slot].id SET_TO -1; _tools[slot].length SET_TO 0; _tools[slot].diameter SET_TO 0; } for (; (fgets(buffer, 1000, tool_file_port) ISNT NULL); ) { if (sscanf_s(buffer, "%d %d %lf %lf", &slot, &tool_id, &offset, &diameter) < 4) { fprintf(stderr, "Bad input line \"%s\" in tool file\n", buffer); return 1; } if ((slot < 0) OR (slot > _tool_max)) /* zero and max both OK */ { fprintf(stderr, "Out of range tool slot number %d\n", slot); return 1; } _tools[slot].id SET_TO tool_id; _tools[slot].length SET_TO offset; _tools[slot].diameter SET_TO diameter; } fclose(tool_file_port); return 0; } /************************************************************************/ /* designate_parameter_file Returned Value: int If any of the following errors occur, this returns 1. Otherwise, it returns 0. 1. The file named by the user cannot be opened. Side Effects: The name of a parameter file given by the user is put in the file_name string. Called By: main */ int designate_parameter_file(char * file_name, size_t length) { FILE * test_port; unsigned int ilength; ilength = (int)length; fprintf(stderr, "name of parameter file => "); fgets(file_name, ilength, stdin); fopen_s(&test_port,file_name, "r"); if (test_port IS NULL) { fprintf(stderr, "Cannot open %s\n", file_name); return 1; } fclose(test_port); return 0; } /************************************************************************/ /* adjust_error_handling Returned Value: int (0) Side Effects: The values of print_stack and do_next are set. Called By: main This function allows the user to set one or two aspects of error handling. By default the driver does not print the function stack in case of error. This function always allows the user to turn stack printing on if it is off or to turn stack printing off if it is on. When interpreting from the keyboard, the driver always goes ahead if there is an error. When interpreting from a file, the default behavior is to stop in case of an error. If the user is interpreting from a file (indicated by args being 2 or 3), this lets the user change what it does on an error. If the user has not asked for output to a file (indicated by args being 2), the user can choose any of three behaviors in case of an error (1) continue, (2) stop, (3) go into MDI mode. This function allows the user to cycle among the three. If the user has asked for output to a file (indicated by args being 3), the user can choose any of two behaviors in case of an error (1) continue, (2) stop. This function allows the user to toggle between the two. */ int adjust_error_handling( int args, int * print_stack, int * do_next) { char buffer[80]; int choice; for(;;) { fprintf(stderr, "enter a number:\n"); fprintf(stderr, "1 = done with error handling\n"); fprintf(stderr, "2 = %sprint stack on error\n", ((*print_stack IS ON) ? "do not " : "")); if (args IS 3) { if (*do_next IS 0) /* 0 means continue */ fprintf(stderr, "3 = stop on error (do not continue)\n"); else /* if do_next IS 2 -- 2 means stopping on error */ fprintf(stderr, "3 = continue on error (do not stop)\n"); } else if (args IS 2) { if (*do_next IS 0) /* 0 means continue */ fprintf(stderr, "3 = mdi on error (do not continue or stop)\n"); else if (*do_next IS 1) /* 1 means MDI */ fprintf(stderr, "3 = stop on error (do not mdi or continue)\n"); else /* if do_next IS 2 -- 2 means stopping on error */ fprintf(stderr, "3 = continue on error (do not stop or mdi)\n"); } fprintf(stderr, "enter choice => "); fgets(buffer, sizeof(buffer), stdin); if (sscanf_s(buffer, "%d", &choice) ISNT 1) continue; if (choice IS 1) break; else if (choice IS 2) *print_stack SET_TO ((*print_stack IS OFF) ? ON : OFF); else if ((choice IS 3) AND (args IS 3)) *do_next SET_TO ((*do_next IS 0) ? 2 : 0); else if ((choice IS 3) AND (args IS 2)) *do_next SET_TO ((*do_next IS 2) ? 0 : (*do_next + 1)); } return 0; } /************************************************************************/ /* main The executable exits with either 0 (under all conditions not listed below) or 1 (under the following conditions): 1. A fatal error occurs while interpreting from a file. 2. Read_tool_file fails. 3. An error occurs in rs274ngc_init. *********************************************************************** Here are three ways in which the rs274abc executable may be called. Any other sort of call to the executable will cause an error message to be printed and the interpreter will not run. Other executables may be called similarly. 1. If the rs274abc stand-alone executable is called with no arguments, input is taken from the keyboard, and an error in the input does not cause the rs274abc executable to exit. EXAMPLE: 1A. To interpret from the keyboard, enter: rs274abc *********************************************************************** 2. If the executable is called with one argument, the argument is taken to be the name of an NC file and the file is interpreted as described in the documentation of interpret_from_file. EXAMPLES: 2A. To interpret the file "cds.abc" and read the results on the screen, enter: rs274abc cds.abc 2B. To interpret the file "cds.abc" and print the results in the file "cds.prim", enter: rs274abc cds.abc > cds.prim *********************************************************************** Whichever way the executable is called, this gives the user several choices before interpretation starts 1 = start interpreting 2 = choose parameter file 3 = read tool file ... 4 = turn block delete switch ON 5 = adjust error handling... Interpretation starts when option 1 is chosen. Until that happens, the user is repeatedly given the five choices listed above. Item 4 toggles between "turn block delete switch ON" and "turn block delete switch OFF". See documentation of adjust_error_handling regarding what option 5 does. User instructions are printed to stderr (with fprintf) so that output can be redirected to a file. When output is redirected and user instructions are printed to stdout (with printf), the instructions get redirected and the user does not see them. */ int main (int argc, char ** argv) { int status; int choice; int do_next; /* 0=continue, 1=mdi, 2=stop */ int block_delete; char buffer[80]; int tool_flag; int gees[RS274NGC_ACTIVE_G_CODES]; int ems[RS274NGC_ACTIVE_M_CODES]; double sets[RS274NGC_ACTIVE_SETTINGS]; char default_name[] SET_TO "rs274ngc.var"; int print_stack; if (argc > 3) { fprintf(stderr, "Usage \"%s\"\n", argv[0]); fprintf(stderr, " or \"%s <input file>\"\n", argv[0]); fprintf(stderr, " or \"%s <input file> <output file>\"\n", argv[0]); exit(1); } do_next SET_TO 2; /* 2=stop */ block_delete SET_TO OFF; print_stack SET_TO OFF; tool_flag SET_TO 0; strcpy_s(_parameter_file_name, sizeof(_parameter_file_name), default_name); _outfile SET_TO stdout; /* may be reset below */ for(; ;) { fprintf(stderr, "enter a number:\n"); fprintf(stderr, "1 = start interpreting\n"); fprintf(stderr, "2 = choose parameter file ...\n"); fprintf(stderr, "3 = read tool file ...\n"); fprintf(stderr, "4 = turn block delete switch %s\n", ((block_delete IS OFF) ? "ON" : "OFF")); fprintf(stderr, "5 = adjust error handling...\n"); fprintf(stderr, "enter choice => "); fgets(buffer, sizeof(buffer), stdin); if (sscanf_s(buffer,"%d", &choice) ISNT 1) continue; if (choice IS 1) break; else if (choice IS 2) { if (designate_parameter_file(_parameter_file_name,sizeof(_parameter_file_name)) ISNT 0) exit(1); } else if (choice IS 3) { if (read_tool_file("") ISNT 0) exit(1); tool_flag SET_TO 1; } else if (choice IS 4) block_delete SET_TO ((block_delete IS OFF) ? ON : OFF); else if (choice IS 5) adjust_error_handling(argc, &print_stack, &do_next); } fprintf(stderr, "executing\n"); if (tool_flag IS 0) { if (read_tool_file("rs274ngc.tool_default") ISNT 0) exit(1); } if (argc IS 3) { fopen_s(&_outfile ,argv[2], "w"); if (_outfile IS NULL) { fprintf(stderr, "could not open output file %s\n", argv[2]); exit(1); } } if ((status SET_TO rs274ngc_init()) ISNT RS274NGC_OK) { report_error(status, print_stack); exit(1); } if (argc IS 1) status SET_TO interpret_from_keyboard(block_delete, print_stack); else /* if (argc IS 2 or argc IS 3) */ { status SET_TO rs274ngc_open(argv[1]); if (status ISNT RS274NGC_OK) /* do not need to close since not open */ { report_error(status, print_stack); exit(1); } status SET_TO interpret_from_file(do_next, block_delete, print_stack); rs274ngc_file_name(buffer, 5); /* called to exercise the function */ rs274ngc_file_name(buffer, 79); /* called to exercise the function */ rs274ngc_close(); } rs274ngc_line_length(); /* called to exercise the function */ rs274ngc_sequence_number(); /* called to exercise the function */ rs274ngc_active_g_codes(gees); /* called to exercise the function */ rs274ngc_active_m_codes(ems); /* called to exercise the function */ rs274ngc_active_settings(sets); /* called to exercise the function */ rs274ngc_exit(); /* saves parameters */ exit(status); } /***********************************************************************/
charlie-x/rs274ngc
rs274ngc/driver.cpp
C++
gpl-3.0
21,770
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head prefix="og: http://ogp.me/ns# dc: http://purl.org/dc/terms/"> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries --> <!--[if lt IE 9]> <script src="//oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="//oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]--> <title>Fan page: B. Stanis</title> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous"> <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous"> <style type="text/css"> #top{ width: 100%; float: left; } #place{ width: 100%; float: left; } #address{ width: 15%; float: left; } #sgvzl{ width: 80%; float: left; } #credits{ width: 100%; float: left; clear: both; } #location-marker{ width: 1em; } #male-glyph{ width: 1em; } </style> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <script type="text/javascript" src="https://www.google.com/jsapi"></script> <script type="text/javascript" id="sgvzlr_script" src="http://mgskjaeveland.github.io/sgvizler/v/0.6/sgvizler.min.js"></script> <script type="text/javascript"> sgvizler .defaultEndpointURL("http://bibfram.es/fuseki/cobra/query"); //// Leave this as is. Ready, steady, go! $(document).ready(sgvizler.containerDrawAll); </script> <!-- Latest compiled and minified JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script> <meta name="title" content="B. Stanis"> <meta property="dc:title" content="B. Stanis"> <meta property="og:title" content="B. Stanis"> <meta name="author" content="B. Stanis"> <meta name="dc:creator" content="B. Stanis"> </head> <body prefix="cbo: http://comicmeta.org/cbo/ dc: http://purl.org/dc/elements/1.1/ dcterms: http://purl.org/dc/terms/ foaf: http://xmlns.com/foaf/0.1/ oa: http://www.w3.org/ns/oa# rdf: http://www.w3.org/1999/02/22-rdf-syntax-ns# schema: http://schema.org/ skos: http://www.w3.org/2004/02/skos/core# xsd: http://www.w3.org/2001/XMLSchema#"> <div id="wrapper" class="container" about="http://ivmooc-cobra2.github.io/resources/fan/1403" typeof="http://comicmeta.org/cbo/Fan"> <div id="top"> <h1> <span property="http://schema.org/name">B. Stanis</span> </h1> <dl> <dt> <label for="http://comicmeta.org/cbo/Fan"> <span>type</span> </label> </dt> <dd> <span>http://comicmeta.org/cbo/Fan</span> </dd> </dl> <dl> <dt> <label for="http://schema.org/name"> <span> <a href="http://schema.org/name">name</a> </span> </label> </dt> <dd> <span property="http://schema.org/name">B. Stanis</span> </dd> </dl> </div> <div id="place" rel="http://schema.org/address" resource="http://ivmooc-cobra2.github.io/resources/place/1341" typeof="http://schema.org/Place"> <h2>Location <a href="http://ivmooc-cobra2.github.io/resources/place/1341"> <img id="location-marker" src="/static/resources/img/location.svg" alt="location marker glyph"> </a> </h2> <div id="address" rel="http://schema.org/address" typeof="http://schema.org/PostalAddress" resource="http://ivmooc-cobra2.github.io/resources/place/1341/address"> <dl> <dt> <label for="http://schema.org/streetAddress"> <span> <a href="http://schema.org/streetAddress">Street address</a> </span> </label> </dt> <dd> <span property="http://schema.org/streetAddress">NULL</span> </dd> </dl> <dl> <dt> <label for="http://schema.org/addressLocality"> <span> <a href="http://schema.org/addressLocality">Address locality</a> </span> </label> </dt> <dd> <span property="http://schema.org/addressLocality">Waterbury</span> </dd> </dl> <dl> <dt> <label for="http://schema.org/addressRegion"> <span> <a href="http://schema.org/addressRegion">Address region</a> </span> </label> </dt> <dd> <span property="http://schema.org/addressRegion">CT</span> </dd> </dl> <dl> <dt> <label for="http://schema.org/postalCode"> <span> <a href="http://schema.org/postalCode">Postal code</a> </span> </label> </dt> <dd> <span property="http://schema.org/postalCode">NULL</span> </dd> </dl> <dl> <dt> <label for="http://schema.org/addressCountry"> <span> <a href="http://schema.org/addressCountry">Address country</a> </span> </label> </dt> <dd> <span property="http://schema.org/addressCountry">US</span> </dd> </dl> </div> <div id="sgvzl" data-sgvizler-endpoint="http://bibfram.es/fuseki/cobra/query" data-sgvizler-query="PREFIX dc: <http://purl.org/dc/elements/1.1/&gt; &#xA;PREFIX cbo: <http://comicmeta.org/cbo/&gt; &#xA;PREFIX foaf: <http://xmlns.com/foaf/0.1/&gt;&#xA;PREFIX schema: <http://schema.org/&gt;&#xA;SELECT ?lat ?long &#xA;WHERE {&#xA; ?fan schema:address ?Place .&#xA; ?Place schema:geo ?Geo .&#xA; ?Geo schema:latitude ?lat .&#xA; ?Geo schema:longitude ?long .&#xA; FILTER(?fan = <http://ivmooc-cobra2.github.io/resources/fan/1403&gt;)&#xA;}" data-sgvizler-chart="google.visualization.GeoChart" data-sgvizler-loglevel="2" style="width:800px; height:400px;"></div> </div> <div id="letter" rel="http://purl.org/dc/elements/1.1/creator" resource="http://ivmooc-cobra2.github.io/resources/letter/1515"> <dl> <dt> <label for="http://schema.org/streetAddress"> <span> <a href="http://schema.org/streetAddress">Street address</a> </span> </label> </dt> <dd> <span property="http://schema.org/streetAddress">NULL</span> </dd> </dl> </div> <div id="credits">Icons made by <a href="http://www.flaticon.com/authors/simpleicon" title="SimpleIcon">SimpleIcon</a> from <a href="http://www.flaticon.com" title="Flaticon">www.flaticon.com</a> is licensed by <a href="http://creativecommons.org/licenses/by/3.0/" title="Creative Commons BY 3.0" target="_blank">CC 3.0 BY</a> </div> </div> </body> </html>
Timathom/timathom.github.io
discovery/resources/fan/1403/index.html
HTML
gpl-3.0
8,174
#!/bin/sh STAGING_DIR=$PWD/9ML-toolkit.d mkdir -p $STAGING_DIR mkdir -p $STAGING_DIR/bin ${CHICKEN_HOME}/bin/chicken-install -init $STAGING_DIR rm $STAGING_DIR/setup-download.* $STAGING_DIR/tcp.* $STAGING_DIR/srfi-18.* $CHICKEN_HOME/bin/chicken-install -deploy -prefix $STAGING_DIR \ datatype typeclass regex make bind vector-lib iset rb-tree easyffi flsim format-graph getopt-long input-parse lalr matchable mathh miniML static-modules \ numbers object-graph random-mtzig dyn-vector signal-diagram silex sxml-transforms ssax sxpath defstruct uri-generic utf8 ersatz $CHICKEN_HOME/bin/chicken-install -deploy -prefix $STAGING_DIR 9ML-toolkit mv $STAGING_DIR/bin/9ML-network/9ML-network $STAGING_DIR mv $STAGING_DIR/bin/9ML-ivp/9ML-ivp $STAGING_DIR rm -rf $STAGING_DIR/bin
iraikov/9ML-toolkit
scripts/deploy-linux.sh
Shell
gpl-3.0
786
/* *************************************************************************** * This file is part of SharpNEAT - Evolution of Neural Networks. * * Copyright 2004-2006, 2009-2010 Colin Green ([email protected]) * * SharpNEAT 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. * * SharpNEAT 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 SharpNEAT. If not, see <http://www.gnu.org/licenses/>. */ using System; using Redzen.Numerics; using SharpNeat.Utility; namespace SharpNeat.Network { /// <summary> /// Gaussian activation function. Output range is 0 to 1, that is, the tails of the gaussian /// distribution curve tend towards 0 as abs(x) -> Infinity and the gaussian's peak is at x = 0. /// </summary> public class RbfGaussian : IActivationFunction { /// <summary> /// Default instance provided as a public static field. /// </summary> public static readonly IActivationFunction __DefaultInstance = new RbfGaussian(0.1, 0.1); double _auxArgsMutationSigmaCenter; double _auxArgsMutationSigmaRadius; #region Constructor /// <summary> /// Construct with the specified radial basis function auxiliary arguments. /// </summary> /// <param name="auxArgsMutationSigmaCenter">Radial basis function center.</param> /// <param name="auxArgsMutationSigmaRadius">Radial basis function radius.</param> public RbfGaussian(double auxArgsMutationSigmaCenter, double auxArgsMutationSigmaRadius) { _auxArgsMutationSigmaCenter = auxArgsMutationSigmaCenter; _auxArgsMutationSigmaRadius = auxArgsMutationSigmaRadius; } #endregion /// <summary> /// Gets the unique ID of the function. Stored in network XML to identify which function a network or neuron /// is using. /// </summary> public string FunctionId { get { return this.GetType().Name; } } /// <summary> /// Gets a human readable string representation of the function. E.g 'y=1/x'. /// </summary> public string FunctionString { get { return "y = e^(-((x-center)*epsilon)^2)"; } } /// <summary> /// Gets a human readable verbose description of the activation function. /// </summary> public string FunctionDescription { get { return "Gaussian.\r\nEffective yrange->[0,1]"; } } /// <summary> /// Gets a flag that indicates if the activation function accepts auxiliary arguments. /// </summary> public bool AcceptsAuxArgs { get { return true; } } /// <summary> /// Calculates the output value for the specified input value and activation function auxiliary arguments. /// </summary> public double Calculate(double x, double[] auxArgs) { // auxArgs[0] - RBF center. // auxArgs[1] - RBF gaussian epsilon. double d = (x-auxArgs[0]) * Math.Sqrt(auxArgs[1]) * 4.0; return Math.Exp(-(d*d)); } /// <summary> /// Calculates the output value for the specified input value and activation function auxiliary arguments. /// This single precision overload of Calculate() will be used in neural network code /// that has been specifically written to use floats instead of doubles. /// </summary> public float Calculate(float x, float[] auxArgs) { // auxArgs[0] - RBF center. // auxArgs[1] - RBF gaussian epsilon. float d = (x-auxArgs[0]) * (float)Math.Sqrt(auxArgs[1]) * 4f; return (float)Math.Exp(-(d*d)); } /// <summary> /// For activation functions that accept auxiliary arguments; generates random initial values for aux arguments for newly /// added nodes (from an 'add neuron' mutation). /// </summary> public double[] GetRandomAuxArgs(XorShiftRandom rng, double connectionWeightRange) { double[] auxArgs = new double[2]; auxArgs[0] = (rng.NextDouble()-0.5) * 2.0; auxArgs[1] = rng.NextDouble(); return auxArgs; } /// <summary> /// Genetic mutation for auxiliary argument data. /// </summary> public void MutateAuxArgs(double[] auxArgs, XorShiftRandom rng, ZigguratGaussianSampler gaussianSampler, double connectionWeightRange) { // Mutate center. // Add gaussian ditribution sample and clamp result to +-connectionWeightRange. double tmp = auxArgs[0] + gaussianSampler.NextSample(0, _auxArgsMutationSigmaCenter); if(tmp < -connectionWeightRange) { auxArgs[0] = -connectionWeightRange; } else if(tmp > connectionWeightRange) { auxArgs[0] = connectionWeightRange; } else { auxArgs[0] = tmp; } // Mutate radius. // Add gaussian ditribution sample and clamp result to [0,1] tmp = auxArgs[1] + gaussianSampler.NextSample(0, _auxArgsMutationSigmaRadius); if(tmp < 0.0) { auxArgs[1] = 0.0; } else if(tmp > 1.0) { auxArgs[1] = 1.0; } else { auxArgs[1] = tmp; } } } }
BLueders/ENTM_CSharpPort
src/SharpNeatLib/Network/ActivationFunctions/RadialBasis/RbfGaussian.cs
C#
gpl-3.0
5,987
'use strict'; /*global require, after, before*/ var async = require('async'), assert = require('assert'), db = require('../mocks/databasemock'); describe('Set methods', function() { describe('setAdd()', function() { it('should add to a set', function(done) { db.setAdd('testSet1', 5, function(err) { assert.equal(err, null); assert.equal(arguments.length, 1); done(); }); }); it('should add an array to a set', function(done) { db.setAdd('testSet1', [1, 2, 3, 4], function(err) { assert.equal(err, null); assert.equal(arguments.length, 1); done(); }); }); }); describe('getSetMembers()', function() { before(function(done) { db.setAdd('testSet2', [1,2,3,4,5], done); }); it('should return an empty set', function(done) { db.getSetMembers('doesnotexist', function(err, set) { assert.equal(err, null); assert.equal(arguments.length, 2); assert.equal(Array.isArray(set), true); assert.equal(set.length, 0); done(); }); }); it('should return a set with all elements', function(done) { db.getSetMembers('testSet2', function(err, set) { assert.equal(err, null); assert.equal(set.length, 5); set.forEach(function(value) { assert.notEqual(['1', '2', '3', '4', '5'].indexOf(value), -1); }); done(); }); }); }); describe('setsAdd()', function() { it('should add to multiple sets', function(done) { db.setsAdd(['set1', 'set2'], 'value', function(err) { assert.equal(err, null); assert.equal(arguments.length, 1); done(); }); }); }); describe('getSetsMembers()', function() { before(function(done) { db.setsAdd(['set3', 'set4'], 'value', done); }); it('should return members of two sets', function(done) { db.getSetsMembers(['set3', 'set4'], function(err, sets) { assert.equal(err, null); assert.equal(Array.isArray(sets), true); assert.equal(arguments.length, 2); assert.equal(Array.isArray(sets[0]) && Array.isArray(sets[1]), true); assert.strictEqual(sets[0][0], 'value'); assert.strictEqual(sets[1][0], 'value'); done(); }); }); }); describe('isSetMember()', function() { before(function(done) { db.setAdd('testSet3', 5, done); }); it('should return false if element is not member of set', function(done) { db.isSetMember('testSet3', 10, function(err, isMember) { assert.equal(err, null); assert.equal(arguments.length, 2); assert.equal(isMember, false); done(); }); }); it('should return true if element is a member of set', function(done) { db.isSetMember('testSet3', 5, function(err, isMember) { assert.equal(err, null); assert.equal(arguments.length, 2); assert.equal(isMember, true); done(); }); }); }); describe('isSetMembers()', function() { before(function(done) { db.setAdd('testSet4', [1, 2, 3, 4, 5], done); }); it('should return an array of booleans', function(done) { db.isSetMembers('testSet4', ['1', '2', '10', '3'], function(err, members) { assert.equal(err, null); assert.equal(arguments.length, 2); assert.equal(Array.isArray(members), true); assert.deepEqual(members, [true, true, false, true]); done(); }); }); }); describe('isMemberOfSets()', function() { before(function(done) { db.setsAdd(['set1', 'set2'], 'value', done); }); it('should return an array of booleans', function(done) { db.isMemberOfSets(['set1', 'testSet1', 'set2', 'doesnotexist'], 'value', function(err, members) { assert.equal(err, null); assert.equal(arguments.length, 2); assert.equal(Array.isArray(members), true); assert.deepEqual(members, [true, false, true, false]); done(); }); }); }); describe('setCount()', function() { before(function(done) { db.setAdd('testSet5', [1,2,3,4,5], done); }); it('should return the element count of set', function(done) { db.setCount('testSet5', function(err, count) { assert.equal(err, null); assert.equal(arguments.length, 2); assert.strictEqual(count, 5); done(); }); }); }); describe('setsCount()', function() { before(function(done) { async.parallel([ async.apply(db.setAdd, 'set5', [1,2,3,4,5]), async.apply(db.setAdd, 'set6', 1), async.apply(db.setAdd, 'set7', 2) ], done); }); it('should return the element count of sets', function(done) { db.setsCount(['set5', 'set6', 'set7', 'doesnotexist'], function(err, counts) { assert.equal(err, null); assert.equal(arguments.length, 2); assert.equal(Array.isArray(counts), true); assert.deepEqual(counts, [5, 1, 1, 0]); done(); }); }); }); describe('setRemove()', function() { before(function(done) { db.setAdd('testSet6', [1, 2], done); }); it('should remove a element from set', function(done) { db.setRemove('testSet6', '2', function(err) { assert.equal(err, null); assert.equal(arguments.length, 1); db.isSetMember('testSet6', '2', function(err, isMember) { assert.equal(err, null); assert.equal(isMember, false); done(); }); }); }); }); describe('setsRemove()', function() { before(function(done) { db.setsAdd(['set1', 'set2'], 'value', done); }); it('should remove a element from multiple sets', function(done) { db.setsRemove(['set1', 'set2'], 'value', function(err) { assert.equal(err, null); assert.equal(arguments.length, 1); db.isMemberOfSets(['set1', 'set2'], 'value', function(err, members) { assert.equal(err, null); assert.deepEqual(members, [false, false]); done(); }); }); }); }); describe('setRemoveRandom()', function() { before(function(done) { db.setAdd('testSet7', [1,2,3,4,5], done); }); it('should remove a random element from set', function(done) { db.setRemoveRandom('testSet7', function(err, element) { assert.equal(err, null); assert.equal(arguments.length, 2); db.isSetMember('testSet', element, function(err, ismember) { assert.equal(err, null); assert.equal(ismember, false); done(); }); }); }); }); after(function(done) { db.flushdb(done); }); });
seafruit/NodeBB
test/database/sets.js
JavaScript
gpl-3.0
6,160
//////////////////////////////////////////////////////// // // GEM - Graphics Environment for Multimedia // // Implementation file // // Copyright (c) 2002-2011 IOhannes m zmölnig. forum::für::umläute. IEM. [email protected] // [email protected] // For information on usage and redistribution, and for a DISCLAIMER // * OF ALL WARRANTIES, see the file, "GEM.LICENSE.TERMS" // // this file has been generated... //////////////////////////////////////////////////////// #include "GEMglTexParameteri.h" CPPEXTERN_NEW_WITH_THREE_ARGS ( GEMglTexParameteri , t_floatarg, A_DEFFLOAT, t_floatarg, A_DEFFLOAT, t_floatarg, A_DEFFLOAT); ///////////////////////////////////////////////////////// // // GEMglViewport // ///////////////////////////////////////////////////////// // Constructor // GEMglTexParameteri :: GEMglTexParameteri (t_floatarg arg0=0, t_floatarg arg1=0, t_floatarg arg2=0) : target(static_cast<GLenum>(arg0)), pname(static_cast<GLenum>(arg1)), param(static_cast<GLint>(arg2)) { m_inlet[0] = inlet_new(this->x_obj, &this->x_obj->ob_pd, &s_float, gensym("target")); m_inlet[1] = inlet_new(this->x_obj, &this->x_obj->ob_pd, &s_float, gensym("pname")); m_inlet[2] = inlet_new(this->x_obj, &this->x_obj->ob_pd, &s_float, gensym("param")); } ///////////////////////////////////////////////////////// // Destructor // GEMglTexParameteri :: ~GEMglTexParameteri () { inlet_free(m_inlet[0]); inlet_free(m_inlet[1]); inlet_free(m_inlet[2]); } ///////////////////////////////////////////////////////// // Render // void GEMglTexParameteri :: render(GemState *state) { glTexParameteri (target, pname, param); } ///////////////////////////////////////////////////////// // Variables // void GEMglTexParameteri :: targetMess (t_float arg1) { // FUN target = static_cast<GLenum>(arg1); setModified(); } void GEMglTexParameteri :: pnameMess (t_float arg1) { // FUN pname = static_cast<GLenum>(arg1); setModified(); } void GEMglTexParameteri :: paramMess (t_float arg1) { // FUN param = static_cast<GLint>(arg1); setModified(); } ///////////////////////////////////////////////////////// // static member functions // void GEMglTexParameteri :: obj_setupCallback(t_class *classPtr) { class_addmethod(classPtr, reinterpret_cast<t_method>(&GEMglTexParameteri::targetMessCallback), gensym("target"), A_DEFFLOAT, A_NULL); class_addmethod(classPtr, reinterpret_cast<t_method>(&GEMglTexParameteri::pnameMessCallback), gensym("pname"), A_DEFFLOAT, A_NULL); class_addmethod(classPtr, reinterpret_cast<t_method>(&GEMglTexParameteri::paramMessCallback), gensym("param"), A_DEFFLOAT, A_NULL); }; void GEMglTexParameteri :: targetMessCallback (void* data, t_floatarg arg0){ GetMyClass(data)->targetMess ( static_cast<t_float>(arg0)); } void GEMglTexParameteri :: pnameMessCallback (void* data, t_floatarg arg0){ GetMyClass(data)->pnameMess ( static_cast<t_float>(arg0)); } void GEMglTexParameteri :: paramMessCallback (void* data, t_floatarg arg0){ GetMyClass(data)->paramMess ( static_cast<t_float>(arg0)); }
rvega/morphasynth
vendors/pd-extended-0.43.4/externals/Gem/src/openGL/GEMglTexParameteri.cpp
C++
gpl-3.0
3,043
using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; using System.Linq.Expressions; namespace BusinessLogic.Repositories { public class Repository<T> : IRepository<T> where T : class { private readonly DbContext _context; private readonly DbSet<T> _dbSet; public Repository(DbContext context) { this._context = context; this._dbSet = context.Set<T>(); } public virtual void Add(T entity) { this._dbSet.Add(entity); this._context.SaveChanges(); } public virtual void Delete(int id, string userID) { var entry = this._dbSet.Find(id); this._dbSet.Remove(entry); this._context.SaveChanges(); } public IQueryable<T> GetAll() { return this._dbSet.AsQueryable(); } public T GetByID(int? id, string userID) { return this._dbSet.Find(id); } public void Edit(T entity) { this._context.Set<T>().AddOrUpdate(entity); this._context.SaveChanges(); } public void Edit(List<T> entities) { foreach (var entity in entities) Edit(entity); } public int GetCount() { return this._dbSet.Count(); } private IEnumerable<T> Find(Expression<Func<T, bool>> predicate) { return this._dbSet.Where(predicate); } } }
dsilva609/Project-Cinderella
BusinessLogic/Repositories/Repository.cs
C#
gpl-3.0
1,282
// pythonFlu - Python wrapping for OpenFOAM C++ API // Copyright (C) 2010- Alexey Petrov // Copyright (C) 2009-2010 Pebble Bed Modular Reactor (Pty) Limited (PBMR) // // 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/>. // // See http://sourceforge.net/projects/pythonflu // // Author : Alexey PETROV //--------------------------------------------------------------------------- #ifndef no_tmp_typemap_GeometricFields_hpp #define no_tmp_typemap_GeometricFields_hpp //--------------------------------------------------------------------------- %import "Foam/src/OpenFOAM/fields/tmp/tmp.i" %import "Foam/ext/common/ext_tmp.hxx" //--------------------------------------------------------------------------- %define NO_TMP_TYPEMAP_GEOMETRIC_FIELD( Type, TPatchField, TMesh ) %typecheck( SWIG_TYPECHECK_POINTER ) Foam::GeometricField< Type, TPatchField, TMesh >& { void *ptr; int res_T = SWIG_ConvertPtr( $input, (void **) &ptr, $descriptor( Foam::GeometricField< Type, TPatchField, TMesh > * ), 0 ); int res_tmpT = SWIG_ConvertPtr( $input, (void **) &ptr, $descriptor( Foam::tmp< Foam::GeometricField< Type, TPatchField, TMesh > > * ), 0 ); int res_ext_tmpT = SWIG_ConvertPtr( $input, (void **) &ptr, $descriptor( Foam::ext_tmp< Foam::GeometricField< Type, TPatchField, TMesh > > * ), 0 ); $1 = SWIG_CheckState( res_T ) || SWIG_CheckState( res_tmpT ) || SWIG_CheckState( res_ext_tmpT ); } %typemap( in ) Foam::GeometricField< Type, TPatchField, TMesh >& { void *argp = 0; int res = 0; res = SWIG_ConvertPtr( $input, &argp, $descriptor( Foam::GeometricField< Type, TPatchField, TMesh > * ), %convertptr_flags ); if ( SWIG_IsOK( res )&& argp ){ Foam::GeometricField< Type, TPatchField, TMesh > * res = %reinterpret_cast( argp, Foam::GeometricField< Type, TPatchField, TMesh >* ); $1 = res; } else { res = SWIG_ConvertPtr( $input, &argp, $descriptor( Foam::tmp< Foam::GeometricField< Type, TPatchField, TMesh > >* ), %convertptr_flags ); if ( SWIG_IsOK( res ) && argp ) { Foam::tmp<Foam::GeometricField< Type, TPatchField, TMesh> >* tmp_res =%reinterpret_cast( argp, Foam::tmp< Foam::GeometricField< Type, TPatchField, TMesh > > * ); $1 = tmp_res->operator->(); } else { res = SWIG_ConvertPtr( $input, &argp, $descriptor( Foam::ext_tmp< Foam::GeometricField< Type, TPatchField, TMesh > >* ), %convertptr_flags ); if ( SWIG_IsOK( res ) && argp ) { Foam::ext_tmp<Foam::GeometricField< Type, TPatchField, TMesh> >* tmp_res =%reinterpret_cast( argp, Foam::ext_tmp< Foam::GeometricField< Type, TPatchField, TMesh > > * ); $1 = tmp_res->operator->(); } else { %argument_fail( res, "$type", $symname, $argnum ); } } } } %enddef //--------------------------------------------------------------------------- %import "Foam/src/OpenFOAM/primitives/scalar.i" %include "Foam/src/finiteVolume/volMesh.hpp" %include "Foam/src/finiteVolume/fields/fvPatchFields/fvPatchField.cpp" NO_TMP_TYPEMAP_GEOMETRIC_FIELD( Foam::scalar, Foam::fvPatchField, Foam::volMesh ); //---------------------------------------------------------------------------- %import "Foam/src/OpenFOAM/primitives/vector.i" %include "Foam/src/finiteVolume/volMesh.hpp" %include "Foam/src/finiteVolume/fields/fvPatchFields/fvPatchField.cpp" NO_TMP_TYPEMAP_GEOMETRIC_FIELD( Foam::Vector< Foam::scalar >, Foam::fvPatchField, Foam::volMesh ); //---------------------------------------------------------------------------- %import "Foam/src/OpenFOAM/primitives/tensor.i" %include "Foam/src/finiteVolume/volMesh.hpp" %include "Foam/src/finiteVolume/fields/fvPatchFields/fvPatchField.cpp" NO_TMP_TYPEMAP_GEOMETRIC_FIELD( Foam::Tensor< Foam::scalar >, Foam::fvPatchField, Foam::volMesh ); //----------------------------------------------------------------------------- %import "Foam/src/OpenFOAM/primitives/symmTensor.i" %include "Foam/src/finiteVolume/volMesh.hpp" %include "Foam/src/finiteVolume/fields/fvPatchFields/fvPatchField.cpp" NO_TMP_TYPEMAP_GEOMETRIC_FIELD( Foam::SymmTensor< Foam::scalar >, Foam::fvPatchField, Foam::volMesh ); //------------------------------------------------------------------------------ %import "Foam/src/OpenFOAM/primitives/sphericalTensor.i" %include "Foam/src/finiteVolume/volMesh.hpp" %include "Foam/src/finiteVolume/fields/fvPatchFields/fvPatchField.cpp" NO_TMP_TYPEMAP_GEOMETRIC_FIELD( Foam::SphericalTensor< Foam::scalar >, Foam::fvPatchField, Foam::volMesh ); //------------------------------------------------------------------------------ %import "Foam/src/OpenFOAM/primitives/scalar.i" %include "Foam/src/finiteVolume/surfaceMesh.hpp" %include "Foam/src/finiteVolume/fields/fvsPatchFields/fvsPatchField.cpp" NO_TMP_TYPEMAP_GEOMETRIC_FIELD( Foam::scalar, Foam::fvsPatchField, Foam::surfaceMesh ); //------------------------------------------------------------------------------- %import "Foam/src/OpenFOAM/primitives/vector.i" %include "Foam/src/finiteVolume/surfaceMesh.hpp" %include "Foam/src/finiteVolume/fields/fvsPatchFields/fvsPatchField.cpp" NO_TMP_TYPEMAP_GEOMETRIC_FIELD( Foam::Vector< Foam::scalar >, Foam::fvsPatchField, Foam::surfaceMesh ); //------------------------------------------------------------------------------- %import "Foam/src/OpenFOAM/primitives/tensor.i" %include "Foam/src/finiteVolume/surfaceMesh.hpp" %include "Foam/src/finiteVolume/fields/fvsPatchFields/fvsPatchField.cpp" NO_TMP_TYPEMAP_GEOMETRIC_FIELD( Foam::Tensor< Foam::scalar >, Foam::fvsPatchField, Foam::surfaceMesh ); //------------------------------------------------------------------------------- #endif
ivan7farre/PyFreeFOAM
Foam/src/OpenFOAM/fields/GeometricFields/no_tmp_typemap_GeometricFields.hpp
C++
gpl-3.0
6,243
#ifndef VALUE_H_ #define VALUE_H_ // Cost parameters #define CARCOST 100 #define TICKETCOST 300 #define CENTSPERLITRE 130 #define METERSPERLITRE 15000 // Headers #include <limits.h> #include <immintrin.h> #include "instance.h" #include "random.h" #include "macros.h" #include "types.h" #define COST(I, DR, L) ((DR)[(I)] ? (PATHCOST((L)[I]) + CARCOST) : TICKETCOST) #define PATHCOST(p) ROUND(value, (float)(p) / METERSPERLITRE * CENTSPERLITRE) #define EURO(i) ((float)(i) / 100) #define R5 2520 #define R4 90 #define R3 6 meter minpath(agent *c, agent n, agent dr, const meter *sp); #endif /* VALUE_H_ */
filippobistaffa/SR-CFSS
value.h
C
gpl-3.0
613
//----------------------------------------------------------------------------------- // The confidential and proprietary information contained in this file may // only be used by a person authorised under and to the extent permitted // by a subsisting licensing agreement from ARM Limited or its affiliates // or between you and a party authorised by ARM // // (C) COPYRIGHT [2016] ARM Limited or its affiliates // ALL RIGHT RESERVED // // This entire notice must be reproduced on all copies of this file // and copies of this files may only be made by a person if such person is // permitted to do so under the terms of a subsisting license agreement // from ARM Limited or its affiliates or between you and a party authorised by ARM //----------------------------------------------------------------------------------- #ifndef CRYS_RND_H #define CRYS_RND_H #include "crys_error.h" #include "ssi_aes.h" #ifdef __cplusplus extern "C" { #endif /*! @file @brief This file contains the CRYS APIs used for random number generation. The random-number generation module implements referenced standard [SP800-90]. */ /************************ Defines ******************************/ /*! Maximal reseed counter - indicates maximal number of requests allowed between reseeds; according to NIST 800-90 it is (2^48 - 1), our restriction is : (0xFFFFFFFF - 0xF).*/ #define CRYS_RND_MAX_RESEED_COUNTER (0xFFFFFFFF - 0xF) /* maximal requested size counter (12 bits active) - maximal count of generated random 128 bit blocks allowed per one request of Generate function according NIST 800-90 it is (2^12 - 1) = 0x3FFFF */ #define CRYS_RND_REQUESTED_SIZE_COUNTER 0x3FFFF /*! AES output block size in words. */ #define CRYS_RND_AES_BLOCK_SIZE_IN_WORDS SASI_AES_BLOCK_SIZE_IN_WORDS /* RND seed and additional input sizes */ #define CRYS_RND_SEED_MAX_SIZE_WORDS 12 #ifndef CRYS_RND_ADDITINAL_INPUT_MAX_SIZE_WORDS #define CRYS_RND_ADDITINAL_INPUT_MAX_SIZE_WORDS CRYS_RND_SEED_MAX_SIZE_WORDS #endif /* Max size of generated random vector in bits according uint16_t type of * * input size parameter in CRYS_RND_Generate function */ #define CRYS_RND_MAX_GEN_VECTOR_SIZE_BYTES 0xFFFF /* allowed sizes of AES Key, in words */ #define CRYS_RND_AES_KEY_128_SIZE_WORDS 4 #define CRYS_RND_AES_KEY_192_SIZE_WORDS 6 #define CRYS_RND_AES_KEY_256_SIZE_WORDS 8 /* Definitions of temp buffer for RND_DMA version of CRYS_RND */ /*******************************************************************/ /* Definitions of temp buffer for DMA version of CRYS_RND */ #define CRYS_RND_WORK_BUFFER_SIZE_WORDS 1528 /*! A definition for RAM buffer to be internally used in instantiation (or reseeding) operation. */ typedef struct { /* include the specific fields that are used by the low level */ uint32_t crysRndWorkBuff[CRYS_RND_WORK_BUFFER_SIZE_WORDS]; }CRYS_RND_WorkBuff_t; #define CRYS_RND_EntropyEstimatData_t CRYS_RND_WorkBuff_t #define crysRndEntrIntBuff crysRndWorkBuff /* RND source buffer inner (entrpopy) offset */ #define CRYS_RND_TRNG_SRC_INNER_OFFSET_WORDS 2 /* Max size for one RNG operation */ #define CRYS_RND_MAX_SIZE_OF_OUTPUT_BYTES 3*1024 /* Size of the expected output buffer used by FIPS KAT */ #define CRYS_PRNG_FIPS_KAT_OUT_DATA_SIZE 64 /************************ Enumerators ****************************/ /* Definition of Fast or Slow mode of random generator (TRNG)*/ typedef enum { CRYS_RND_Fast = 0, CRYS_RND_Slow = 1, CRYS_RND_ModeLast = 0x7FFFFFFF, } CRYS_RND_mode_t; /************************ Structs *****************************/ /* The internal state of DRBG mechanism based on AES CTR and CBC-MAC algorithms. It is set as global data defined by the following structure */ typedef struct { /* Seed buffer, consists from concatenated Key||V: max size 12 words */ uint32_t Seed[CRYS_RND_SEED_MAX_SIZE_WORDS]; /* Previous value for continuous test */ uint32_t PreviousRandValue[SASI_AES_BLOCK_SIZE_IN_WORDS]; /* AdditionalInput buffer max size = seed max size words + 4w for padding*/ uint32_t PreviousAdditionalInput[CRYS_RND_ADDITINAL_INPUT_MAX_SIZE_WORDS+3]; uint32_t AdditionalInput[CRYS_RND_ADDITINAL_INPUT_MAX_SIZE_WORDS+4]; uint32_t AddInputSizeWords; /* size of additional data set by user, words */ /* entropy source size in words */ uint32_t EntropySourceSizeWords; /* reseed counter (32 bits active) - indicates number of requests for entropy since instantiation or reseeding */ uint32_t ReseedCounter; /* key size: 4 or 8 words according to security strength 128 bits or 256 bits*/ uint32_t KeySizeWords; /* State flag (see definition of StateFlag above), containing bit-fields, defining: - b'0: instantiation steps: 0 - not done, 1 - done; - 2b'9,8: working or testing mode: 0 - working, 1 - KAT DRBG test, 2 - KAT TRNG test; b'16: flag defining is Previous random valid or not: 0 - not valid, 1 - valid */ uint32_t StateFlag; /* Trng processing flag - indicates which ROSC lengths are: - allowed (bits 0-3); - total started (bits 8-11); - processed (bits 16-19); - started, but not processed (bits24-27) */ uint32_t TrngProcesState; /* validation tag */ uint32_t ValidTag; /* Rnd source entropy size in bits */ uint32_t EntropySizeBits; } CRYS_RND_State_t; /*! The RND Generate vector function pointer type definition. The prototype intendent for External and CRYS internal RND functions pointers definitions. Full description can be found in ::CRYS_RND_GenerateVector function API. */ typedef uint32_t (*SaSiRndGenerateVectWorkFunc_t)( \ CRYS_RND_State_t *rndState_ptr, /*context*/ \ uint16_t outSizeBytes, /*in*/ \ uint8_t *out_ptr /*out*/); /*! definition of RND context that includes CRYS RND state structure and a function pointer for rnd generate function */ typedef struct { /* The pointer to internal state of RND */ CRYS_RND_State_t rndState; /* The pointer to user given function for generation random vector */ SaSiRndGenerateVectWorkFunc_t rndGenerateVectFunc; } CRYS_RND_Context_t; /*! Required for internal FIPS verification for PRNG KAT. */ typedef struct { CRYS_RND_WorkBuff_t rndWorkBuff; uint8_t rndOutputBuff[CRYS_PRNG_FIPS_KAT_OUT_DATA_SIZE]; } CRYS_PrngFipsKatCtx_t; /*****************************************************************************/ /********************** Public Functions *************************/ /*****************************************************************************/ /*! @brief This function initializes the RND context. It must be called at least once prior to using this context with any API that requires it as a parameter (e.g., other RND APIs, asymmetric cryptography key generation and signatures). It is called as part of ARM TrustZone CryptoCell library initialization, which initializes and returns the primary RND context. This primary context can be used as a single global context for all RND needs. Alternatively, other contexts may be initialized and used with a more limited scope (for specific applications or specific threads). The call to this function must be followed by a call to ::CRYS_RND_SetGenerateVectorFunc API to set the generate vector function. It implements referenced standard [SP800-90] - 10.2.1.3.2 - CTR-DRBG Instantiate algorithm using AES (FIPS-PUB 197) and Derivation Function (DF). \note Additional data can be mixed with the random seed (personalization data or nonce). If required, this data should be provided by calling ::CRYS_RND_AddAdditionalInput prior to using this API. @return CRYS_OK on success. @return A non-zero value from crys_rnd_error.h on failure. */ CIMPORT_C CRYSError_t CRYS_RND_Instantiation( CRYS_RND_Context_t *rndContext_ptr, /*!< [in/out] Pointer to the RND context buffer allocated by the user, which is used to maintain the RND state, as well as pointers to the functions used for random vector generation. This context must be saved and provided as a parameter to any API that uses the RND module. \note the context must be cleared before sent to the function. */ CRYS_RND_WorkBuff_t *rndWorkBuff_ptr /*!< [in/out] Scratchpad for the RND module's work. */ ); /*! @brief Clears existing RNG instantiation state. @return CRYS_OK on success. @return A non-zero value from crys_rnd_error.h on failure. */ CIMPORT_C CRYSError_t CRYS_RND_UnInstantiation( CRYS_RND_Context_t *rndContext_ptr /*!< [in/out] Pointer to the RND context buffer. */ ); /*! @brief This function is used for reseeding the RNG with additional entropy and additional user-provided input. (additional data should be provided by calling ::CRYS_RND_AddAdditionalInput prior to using this API). It implements referenced standard [SP800-90] - 10.2.1.4.2 - CTR-DRBG Reseeding algorithm, using AES (FIPS-PUB 197) and Derivation Function (DF). @return CRYS_OK on success. @return A non-zero value from crys_rnd_error.h on failure. */ CIMPORT_C CRYSError_t CRYS_RND_Reseeding( CRYS_RND_Context_t *rndContext_ptr, /*!< [in/out] Pointer to the RND context buffer. */ CRYS_RND_WorkBuff_t *rndWorkBuff_ptr /*!< [in/out] Scratchpad for the RND module's work. */ ); /****************************************************************************************/ /*! @brief Generates a random vector according to the algorithm defined in referenced standard [SP800-90] - 10.2.1.5.2 - CTR-DRBG. The generation algorithm uses AES (FIPS-PUB 197) and Derivation Function (DF). \note <ul id="noteb"><li> The RND module must be instantiated prior to invocation of this API.</li> <li> In the following cases, Reseeding operation must be performed prior to vector generation:</li> <ul><li> Prediction resistance is required.</li> <li> The function returns CRYS_RND_RESEED_COUNTER_OVERFLOW_ERROR, stating that the Reseed Counter has passed its upper-limit (2^32-2).</li></ul></ul> @return CRYS_OK on success. @return A non-zero value from crys_rnd_error.h on failure. */ CIMPORT_C CRYSError_t CRYS_RND_GenerateVector( CRYS_RND_State_t *rndState_ptr, /*!< [in/out] Pointer to the RND state structure, which is part of the RND context structure. Use rndContext->rndState field of the context for this parameter. */ uint16_t outSizeBytes, /*!< [in] The size in bytes of the random vector required. The maximal size is 2^16 -1 bytes. */ uint8_t *out_ptr /*!< [out] The pointer to output buffer. */ ); /****************************************************************************************/ /*! @brief This function sets the RND vector generation function into the RND context. It must be called after ::CRYS_RND_Instantiation, and prior to any other API that requires the RND context as parameter. It is called as part of ARM TrustZone CryptoCell library initialization, to set the RND vector generation function into the primary RND context, after ::CRYS_RND_Instantiation is called. @return CRYS_OK on success. @return A non-zero value from crys_rnd_error.h on failure. */ CRYSError_t CRYS_RND_SetGenerateVectorFunc( CRYS_RND_Context_t *rndContext_ptr, /*!< [in/out] Pointer to the RND context buffer allocated by the user, which is used to maintain the RND state as well as pointers to the functions used for random vector generation. */ SaSiRndGenerateVectWorkFunc_t rndGenerateVectFunc /*!< [in] Pointer to the random vector generation function. The pointer should point to the ::CRYS_RND_GenerateVector function. */ ); /**********************************************************************************************************/ /*! @brief Generates a random vector with specific limitations by testing candidates (described and used in FIPS 186-4: B.1.2, B.4.2 etc.). This function will draw a random vector, compare it to the range limits, and if within range - return it in rndVect_ptr. If outside the range, the function will continue retrying until a conforming vector is found, or the maximal retries limit is exceeded. If maxVect_ptr is provided, rndSizeInBits specifies its size, and the output vector must conform to the range [1 < rndVect < maxVect_ptr]. If maxVect_ptr is NULL, rndSizeInBits specifies the exact required vector size, and the output vector must be the exact same bit size (with its most significant bit = 1). \note The RND module must be instantiated prior to invocation of this API. @return CRYS_OK on success. @return A non-zero value from crys_rnd_error.h on failure. */ CIMPORT_C CRYSError_t CRYS_RND_GenerateVectorInRange( CRYS_RND_Context_t *rndContext_ptr, /*!< [in/out] Pointer to the RND context buffer. */ uint32_t rndSizeInBits, /*!< [in] The size in bits of the random vector required. The allowed size in range 2 <= rndSizeInBits < 2^19-1, bits. */ uint8_t *maxVect_ptr, /*!< [in] Pointer to the vector defining the upper limit for the random vector output, Given as little-endian byte array. If not NULL, its actual size is treated as [(rndSizeInBits+7)/8] bytes. */ uint8_t *rndVect_ptr /*!< [in/out] Pointer to the output buffer for the random vector. Must be at least [(rndSizeInBits+7)/8] bytes. Treated as little-endian byte array. */ ); /*************************************************************************************/ /*! @brief Used for adding additional input/personalization data provided by the user, to be later used by the ::CRYS_RND_Instantiation/::CRYS_RND_Reseeding/::CRYS_RND_GenerateVector functions. @return CRYS_OK on success. @return A non-zero value from crys_rnd_error.h on failure. */ CIMPORT_C CRYSError_t CRYS_RND_AddAdditionalInput( CRYS_RND_Context_t *rndContext_ptr, /*!< [in/out] Pointer to the RND context buffer. */ uint8_t *additonalInput_ptr, /*!< [in] The Additional Input buffer. */ uint16_t additonalInputSize /*!< [in] The size of the Additional Input buffer. Must be <= 48, and a multiple of 4. */ ); /*! @brief The CRYS_RND_EnterKatMode function sets KAT mode bit into StateFlag of global CRYS_RND_WorkingState structure. The user must call this function before calling functions performing KAT tests. \note Total size of entropy and nonce must be not great than: ::CRYS_RND_MAX_KAT_ENTROPY_AND_NONCE_SIZE, defined. @return CRYS_OK on success. @return A non-zero value from crys_rnd_error.h on failure. */ CIMPORT_C CRYSError_t CRYS_RND_EnterKatMode( CRYS_RND_Context_t *rndContext_ptr, /*!< [in/out] Pointer to the RND context buffer. */ uint8_t *entrData_ptr, /*!< [in] Entropy data. */ uint32_t entrSize, /*!< [in] Entropy size in bytes. */ uint8_t *nonce_ptr, /*!< [in] Nonce. */ uint32_t nonceSize, /*!< [in] Entropy size in bytes. */ CRYS_RND_WorkBuff_t *workBuff_ptr /*!< [out] RND working buffer, must be the same buffer, which should be passed into Instantiation/Reseeding functions. */ ); /**********************************************************************************************************/ /*! @brief The CRYS_RND_DisableKatMode function disables KAT mode bit into StateFlag of global CRYS_RND_WorkingState structure. The user must call this function after KAT tests before actual using RND module (Instantiation etc.). @return CRYS_OK on success. @return A non-zero value from crys_rnd_error.h on failure. */ CIMPORT_C void CRYS_RND_DisableKatMode( CRYS_RND_Context_t *rndContext_ptr /*!< [in/out] Pointer to the RND context buffer. */ ); #ifdef __cplusplus } #endif #endif /* #ifndef CRYS_RND_H */
jogosa/flip_dot_clock_fw301
MODIFIED_SDK_13.0.0_04a0bfd/external/nrf_cc310/include/crys_rnd.h
C
gpl-3.0
16,531
namespace Tsu.Voltmeters.Appa { partial class Multimeter109NControl { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { this.Disconnect(); if (disposing && (components != null)) { com2usb.Dispose(); components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { components = new System.ComponentModel.Container(); } #endregion } }
romul/Measurement-Studio
APPA_Multimeter/Multimeter109nControl.Designer.cs
C#
gpl-3.0
1,142
# _attributevaluebeforechange _namespace: [SMRUCC.genomics.Data.Reactome.LocalMySQL.Tables.gk_current](./index.md)_ -- DROP TABLE IF EXISTS `_attributevaluebeforechange`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `_attributevaluebeforechange` ( `DB_ID` int(10) unsigned NOT NULL, `changedAttribute` text, PRIMARY KEY (`DB_ID`), FULLTEXT KEY `changedAttribute` (`changedAttribute`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; --
amethyst-asuka/GCModeller
manual/sdk_api/docs/SMRUCC.genomics.Data.Reactome.LocalMySQL.Tables.gk_current/_attributevaluebeforechange.md
Markdown
gpl-3.0
579
package ru.trolsoft.utils.files; import ru.trolsoft.utils.StrUtils; import java.io.*; import java.util.Random; /** * Created on 07/02/17. */ public class IntelHexWriter { private final Writer writer; /** * */ private int segmentAddress = 0; public IntelHexWriter(Writer writer) { if (writer instanceof BufferedWriter) { this.writer = writer; } else { this.writer = new BufferedWriter(writer); } } // public IntelHexWriter(String fileName) throws IOException { // this(new FileWriter(fileName)); // } public void addData(int offset, byte data[], int bytesPerLine) throws IOException { if (data.length == 0) { return; } //System.out.println("::" + data.length); byte buf[] = new byte[bytesPerLine]; int pos = 0; int bytesToAdd = data.length; while (bytesToAdd > 0) { if (offset % bytesPerLine != 0) { // can be true for first line if offset doesn't aligned buf = new byte[bytesPerLine - offset % bytesPerLine]; } else if (bytesToAdd < bytesPerLine) { // last line buf = new byte[bytesToAdd]; } else if (buf.length != bytesPerLine) { buf = new byte[bytesPerLine]; } System.arraycopy(data, pos, buf, 0, buf.length); // Goto next segment if no more space available in current if (offset + buf.length - 1 > segmentAddress + 0xffff) { int nextSegment = ((offset + bytesPerLine) >> 4) << 4; addSegmentRecord(nextSegment); segmentAddress = nextSegment; } addDataRecord(offset & 0xffff, buf); bytesToAdd -= buf.length; offset += buf.length; pos += buf.length; } } private void addSegmentRecord(int offset) throws IOException { int paragraph = offset >> 4; int hi = (paragraph >> 8) & 0xff; int lo = paragraph & 0xff; int crc = 2 + 2 + hi + lo; crc = (-crc) & 0xff; String rec = ":02000002" + hex(hi) + hex(lo) + hex(crc); write(rec); // 02 0000 02 10 00 EC //:02 0000 04 00 01 F9 } private void addEofRecord() throws IOException { write(":00000001FF"); } private void write(String s) throws IOException { writer.write(s); //writer.write(0x0d); writer.write(0x0a); } private void addDataRecord(int offset, byte[] data) throws IOException { int hi = (offset >> 8) & 0xff; int lo = offset & 0xff; int crc = data.length + hi + lo; String rec = ":" + hex(data.length) + hex(hi) + hex(lo) + "00"; for (byte d : data) { rec += hex(d); crc += d; } crc = (-crc) & 0xff; rec += hex(crc); write(rec); } private static String hex(int b) { return StrUtils.byteToHexStr((byte)b); } public void done() throws IOException { addEofRecord(); writer.flush(); } public static void main(String ... args) throws IOException { IntelHexWriter w = new IntelHexWriter(new OutputStreamWriter(System.out)); // w.addDataRecord(0x0190, new byte[] {0x56, 0x45, 0x52, 0x53, 0x49, 0x4F, 0x4E, 0x0D, 0x0A, 0x00, 0x0D, 0x0A, 0x41, // 0x54, 0x0D, 0x0A}); byte[] data = new byte[Math.abs(new Random().nextInt() % 1024)]; for (int i = 0; i < data.length; i++) { data[i] = (byte) (i % 0xff); } w.addData(0x10000 - 0x100, data, 16); w.done(); } }
trol73/avr-bootloader
software/java/src/ru/trolsoft/utils/files/IntelHexWriter.java
Java
gpl-3.0
3,697
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_131) on Mon May 29 22:14:24 CST 2017 --> <title>org.cripac.isee.vpe.alg.pedestrian.attr Class Hierarchy</title> <meta name="date" content="2017-05-29"> <link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title = "org.cripac.isee.vpe.alg.pedestrian.attr Class Hierarchy"; } } catch (err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li>Use</li> <li class="navBarCell1Rev">Tree</li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../../../org/cripac/isee/vpe/alg/package-tree.html">Prev</a></li> <li><a href="../../../../../../../org/cripac/isee/vpe/alg/pedestrian/reid/package-tree.html">Next</a></li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?org/cripac/isee/vpe/alg/pedestrian/attr/package-tree.html" target="_top">Frames</a></li> <li><a href="package-tree.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if (window == top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 class="title">Hierarchy For Package org.cripac.isee.vpe.alg.pedestrian.attr</h1> <span class="packageHierarchyLabel">Package Hierarchies:</span> <ul class="horizontal"> <li><a href="../../../../../../../overview-tree.html">All Packages</a></li> </ul> </div> <div class="contentContainer"> <h2 title="Class Hierarchy">Class Hierarchy</h2> <ul> <li type="circle">java.lang.<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang"><span class="typeNameLink">Object</span></a> <ul> <li type="circle">org.cripac.isee.vpe.alg.pedestrian.attr.<a href="../../../../../../../org/cripac/isee/vpe/alg/pedestrian/attr/PedestrianAttrRecogAppTest.html" title="class in org.cripac.isee.vpe.alg.pedestrian.attr"><span class="typeNameLink">PedestrianAttrRecogAppTest</span></a> </li> <li type="circle">org.cripac.isee.vpe.common.<a href="../../../../../../../org/cripac/isee/vpe/common/SparkStreamingApp.html" title="class in org.cripac.isee.vpe.common"><span class="typeNameLink">SparkStreamingApp</span></a> (implements java.io.<a href="http://docs.oracle.com/javase/8/docs/api/java/io/Serializable.html?is-external=true" title="class or interface in java.io">Serializable</a>) <ul> <li type="circle">org.cripac.isee.vpe.alg.pedestrian.attr.<a href="../../../../../../../org/cripac/isee/vpe/alg/pedestrian/attr/PedestrianAttrRecogApp.html" title="class in org.cripac.isee.vpe.alg.pedestrian.attr"><span class="typeNameLink">PedestrianAttrRecogApp</span></a> </li> </ul> </li> <li type="circle">org.cripac.isee.vpe.common.<a href="../../../../../../../org/cripac/isee/vpe/common/Stream.html" title="class in org.cripac.isee.vpe.common"><span class="typeNameLink">Stream</span></a> (implements java.io.<a href="http://docs.oracle.com/javase/8/docs/api/java/io/Serializable.html?is-external=true" title="class or interface in java.io">Serializable</a>) <ul> <li type="circle">org.cripac.isee.vpe.alg.pedestrian.attr.<a href="../../../../../../../org/cripac/isee/vpe/alg/pedestrian/attr/PedestrianAttrRecogApp.RecogStream.html" title="class in org.cripac.isee.vpe.alg.pedestrian.attr"><span class="typeNameLink">PedestrianAttrRecogApp.RecogStream</span></a> </li> </ul> </li> <li type="circle">org.cripac.isee.vpe.ctrl.<a href="../../../../../../../org/cripac/isee/vpe/ctrl/SystemPropertyCenter.html" title="class in org.cripac.isee.vpe.ctrl"><span class="typeNameLink">SystemPropertyCenter</span></a> (implements java.io.<a href="http://docs.oracle.com/javase/8/docs/api/java/io/Serializable.html?is-external=true" title="class or interface in java.io">Serializable</a>) <ul> <li type="circle">org.cripac.isee.vpe.alg.pedestrian.attr.<a href="../../../../../../../org/cripac/isee/vpe/alg/pedestrian/attr/PedestrianAttrRecogApp.AppPropertyCenter.html" title="class in org.cripac.isee.vpe.alg.pedestrian.attr"><span class="typeNameLink">PedestrianAttrRecogApp.AppPropertyCenter</span></a> </li> </ul> </li> </ul> </li> </ul> <h2 title="Enum Hierarchy">Enum Hierarchy</h2> <ul> <li type="circle">java.lang.<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang"><span class="typeNameLink">Object</span></a> <ul> <li type="circle">java.lang.<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Enum.html?is-external=true" title="class or interface in java.lang"><span class="typeNameLink">Enum</span></a>&lt;E&gt; (implements java.lang.<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Comparable.html?is-external=true" title="class or interface in java.lang">Comparable</a>&lt;T&gt;, java.io.<a href="http://docs.oracle.com/javase/8/docs/api/java/io/Serializable.html?is-external=true" title="class or interface in java.io">Serializable</a>) <ul> <li type="circle">org.cripac.isee.vpe.alg.pedestrian.attr.<a href="../../../../../../../org/cripac/isee/vpe/alg/pedestrian/attr/PedestrianAttrRecogApp.Algorithm.html" title="enum in org.cripac.isee.vpe.alg.pedestrian.attr"><span class="typeNameLink">PedestrianAttrRecogApp.Algorithm</span></a> </li> </ul> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li>Use</li> <li class="navBarCell1Rev">Tree</li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../../../org/cripac/isee/vpe/alg/package-tree.html">Prev</a></li> <li><a href="../../../../../../../org/cripac/isee/vpe/alg/pedestrian/reid/package-tree.html">Next</a></li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?org/cripac/isee/vpe/alg/pedestrian/attr/package-tree.html" target="_top">Frames</a></li> <li><a href="package-tree.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if (window == top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
kyu-sz/LaS-VPE-Platform
docs/org/cripac/isee/vpe/alg/pedestrian/attr/package-tree.html
HTML
gpl-3.0
10,524
<?php /** * @package omeka * @subpackage solr-search * @copyright 2012 Rector and Board of Visitors, University of Virginia * @license http://www.apache.org/licenses/LICENSE-2.0.html */ class SolrSearch_AdminController extends Omeka_Controller_AbstractActionController { /** * Display the "Server Configuration" form. */ public function serverAction() { $form = new SolrSearch_Form_Server(); // If a valid form was submitted. if ($this->_request->isPost() && $form->isValid($_POST)) { // Set the options. foreach ($form->getValues() as $option => $value) { set_option($option, $value); } } // Are the current parameters valid? if (SolrSearch_Helpers_Index::pingSolrServer()) { // Notify valid connection. $this->_helper->flashMessenger( __('Solr connection is valid.'), 'success' ); } // Notify invalid connection. else $this->_helper->flashMessenger( __('Solr connection is invalid.'), 'error' ); $this->view->form = $form; } /** * Display the "Collection Configuration" form. * * @return void * @author Eric Rochester <[email protected]> **/ public function collectionsAction() { if ($this->_request->isPost()) { $this->_updateCollections($this->_request->getPost()); } $this->view->form = $this->_collectionsForm(); } /** * Retourne l'état actuel de l'indexation Solr en JSON */ public function getIndexStatusAction() { $this->view->status = SolrSearch_Helpers_Index::getStatusViaHandler(); } /** * This updates the excluded collections. * * @param array $post The post data to update from. * @return void * @author Eric Rochester <[email protected]> **/ protected function _updateCollections($post) { $etable = $this->_helper->db->getTable('SolrSearchExclude'); $etable->query("DELETE FROM {$etable->getTableName()};"); $c = 0; if (isset($post['solrexclude'])) { foreach ($post['solrexclude'] as $exc) { $exclude = new SolrSearchExclude(); $exclude->collection_id = $exc; $exclude->save(); $c += 1; } } $this->_helper->_flashMessenger("$c collection(s) excluded."); } /** * This returns the form for the collections. * * @return Zend_Form * @author Eric Rochester <[email protected]> **/ protected function _collectionsForm() { $ctable = $this->_helper->db->getTable('Collection'); $collections = $ctable->findBy(array('public' => 1)); $form = new Zend_Form(); $form->setAction(url('solr-search/collections'))->setMethod('post'); $collbox = new Zend_Form_Element_MultiCheckbox('solrexclude'); $form->addElement($collbox); foreach ($collections as $c) { $title = metadata($c, array('Dublin Core', 'Title')); $collbox->addMultiOption("{$c->id}", $title); } $etable = $this->_helper->db->getTable('SolrSearchExclude'); $excludes = array(); foreach ($etable->findAll() as $exclude) { $excludes[] = "{$exclude->collection_id}"; } $collbox->setValue($excludes); $form->addElement('submit', 'Exclude'); return $form; } /** * Display the "Field Configuration" form. */ public function fieldsAction() { // Get the facet mapping table. $fieldTable = $this->_helper->db->getTable('SolrSearchField'); // If the form was submitted. if ($this->_request->isPost()) { // Gather the POST arguments. $post = $this->_request->getPost(); // Save the facets. foreach ($post['facets'] as $name => $data) { // Were "Is Indexed?" and "Is Facet?" checked? $indexed = array_key_exists('is_indexed', $data) ? 1 : 0; $faceted = array_key_exists('is_facet', $data) ? 1 : 0; // Load the facet mapping. $facet = $fieldTable->findBySlug($name); // Apply the updated values. $facet->label = $data['label']; $facet->is_indexed = $indexed; $facet->is_facet = $faceted; $facet->save(); } // Flash success. $this->_helper->flashMessenger( __('Fields successfully updated! Be sure to reindex.'), 'success' ); } // Assign the facet groups. $this->view->groups = $fieldTable->groupByElementSet(); } /** * Display the "Results Configuration" form. */ public function resultsAction() { $form = new SolrSearch_Form_Results(); // If a valid form was submitted. if ($this->_request->isPost() && $form->isValid($_POST)) { // Set the options. foreach ($form->getValues() as $option => $value) { set_option($option, $value); } // Flash success. $this->_helper->flashMessenger( __('Highlighting options successfully saved!'), 'success' ); } $this->view->form = $form; } /** * Display the "Index Items" form. */ public function reindexAction() { $form = new SolrSearch_Form_Reindex(); if ($this->_request->isPost()) { try { // Clear and reindex. Zend_Registry::get('job_dispatcher')->sendLongRunning( 'SolrSearch_Job_Reindex' ); } catch (Exception $err) { } } $totalDocumentCount = $this->_helper->db->getTable('NewspaperReaderDocuments')->count(); $this->view->form = $form; $this->view->totalDocumentCount = $totalDocumentCount; } }
moobee/omeka-newspaper-reader
SolrSearch/controllers/AdminController.php
PHP
gpl-3.0
6,232
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="fr"> <head> <!-- Generated by javadoc (version 1.7.0_21) on Fri Feb 07 15:34:51 CET 2014 --> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>Uses of Interface fr.ece.ostis.DroneStatusChangedListener</title> <meta name="date" content="2014-02-07"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Interface fr.ece.ostis.DroneStatusChangedListener"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../fr/ece/ostis/DroneStatusChangedListener.html" title="interface in fr.ece.ostis">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?fr/ece/ostis/class-use/DroneStatusChangedListener.html" target="_top">Frames</a></li> <li><a href="DroneStatusChangedListener.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Interface fr.ece.ostis.DroneStatusChangedListener" class="title">Uses of Interface<br>fr.ece.ostis.DroneStatusChangedListener</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../fr/ece/ostis/DroneStatusChangedListener.html" title="interface in fr.ece.ostis">DroneStatusChangedListener</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#fr.ece.ostis">fr.ece.ostis</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#fr.ece.ostis.ui">fr.ece.ostis.ui</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="fr.ece.ostis"> <!-- --> </a> <h3>Uses of <a href="../../../../fr/ece/ostis/DroneStatusChangedListener.html" title="interface in fr.ece.ostis">DroneStatusChangedListener</a> in <a href="../../../../fr/ece/ostis/package-summary.html">fr.ece.ostis</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing fields, and an explanation"> <caption><span>Fields in <a href="../../../../fr/ece/ostis/package-summary.html">fr.ece.ostis</a> with type parameters of type <a href="../../../../fr/ece/ostis/DroneStatusChangedListener.html" title="interface in fr.ece.ostis">DroneStatusChangedListener</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>protected <a href="file:/C:/Program Files Indie/Android/SDK/docs/reference/java/util/ArrayList.html?is-external=true" title="class or interface in java.util">ArrayList</a>&lt;<a href="../../../../fr/ece/ostis/DroneStatusChangedListener.html" title="interface in fr.ece.ostis">DroneStatusChangedListener</a>&gt;</code></td> <td class="colLast"><span class="strong">OstisService.</span><code><strong><a href="../../../../fr/ece/ostis/OstisService.html#mDroneStatusChangedListeners">mDroneStatusChangedListeners</a></strong></code>&nbsp;</td> </tr> </tbody> </table> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../fr/ece/ostis/package-summary.html">fr.ece.ostis</a> with parameters of type <a href="../../../../fr/ece/ostis/DroneStatusChangedListener.html" title="interface in fr.ece.ostis">DroneStatusChangedListener</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><span class="strong">OstisService.</span><code><strong><a href="../../../../fr/ece/ostis/OstisService.html#registerStatusChangedListener(fr.ece.ostis.DroneStatusChangedListener)">registerStatusChangedListener</a></strong>(<a href="../../../../fr/ece/ostis/DroneStatusChangedListener.html" title="interface in fr.ece.ostis">DroneStatusChangedListener</a>&nbsp;listener)</code> <div class="block">Registers a drone-status-changed listener.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><span class="strong">OstisService.</span><code><strong><a href="../../../../fr/ece/ostis/OstisService.html#unregisterStatusChangedListener(fr.ece.ostis.DroneStatusChangedListener)">unregisterStatusChangedListener</a></strong>(<a href="../../../../fr/ece/ostis/DroneStatusChangedListener.html" title="interface in fr.ece.ostis">DroneStatusChangedListener</a>&nbsp;listener)</code> <div class="block">Unregisters a drone-status-changed listener.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="fr.ece.ostis.ui"> <!-- --> </a> <h3>Uses of <a href="../../../../fr/ece/ostis/DroneStatusChangedListener.html" title="interface in fr.ece.ostis">DroneStatusChangedListener</a> in <a href="../../../../fr/ece/ostis/ui/package-summary.html">fr.ece.ostis.ui</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../../fr/ece/ostis/ui/package-summary.html">fr.ece.ostis.ui</a> that implement <a href="../../../../fr/ece/ostis/DroneStatusChangedListener.html" title="interface in fr.ece.ostis">DroneStatusChangedListener</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../fr/ece/ostis/ui/FlyActivity.html" title="class in fr.ece.ostis.ui">FlyActivity</a></strong></code> <div class="block">TODO</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../fr/ece/ostis/ui/NetworkWizardActivity.html" title="class in fr.ece.ostis.ui">NetworkWizardActivity</a></strong></code> <div class="block">TODO</div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../fr/ece/ostis/DroneStatusChangedListener.html" title="interface in fr.ece.ostis">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?fr/ece/ostis/class-use/DroneStatusChangedListener.html" target="_top">Frames</a></li> <li><a href="DroneStatusChangedListener.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
Ostis/Ostis
doc/fr/ece/ostis/class-use/DroneStatusChangedListener.html
HTML
gpl-3.0
9,542
import re import traceback from urllib.parse import quote from requests.utils import dict_from_cookiejar from sickchill import logger from sickchill.helper.common import convert_size, try_int from sickchill.oldbeard import tvcache from sickchill.oldbeard.bs4_parser import BS4Parser from sickchill.providers.torrent.TorrentProvider import TorrentProvider class Provider(TorrentProvider): def __init__(self): super().__init__("Pretome") self.username = None self.password = None self.pin = None self.minseed = 0 self.minleech = 0 self.urls = { "base_url": "https://pretome.info", "login": "https://pretome.info/takelogin.php", "detail": "https://pretome.info/details.php?id=%s", "search": "https://pretome.info/browse.php?search=%s%s", "download": "https://pretome.info/download.php/%s/%s.torrent", } self.url = self.urls["base_url"] self.categories = "&st=1&cat%5B%5D=7" self.proper_strings = ["PROPER", "REPACK"] self.cache = tvcache.TVCache(self) def _check_auth(self): if not self.username or not self.password or not self.pin: logger.warning("Invalid username or password or pin. Check your settings") return True def login(self): if any(dict_from_cookiejar(self.session.cookies).values()): return True login_params = {"username": self.username, "password": self.password, "login_pin": self.pin} response = self.get_url(self.urls["login"], post_data=login_params, returns="text") if not response: logger.warning("Unable to connect to provider") return False if re.search("Username or password incorrect", response): logger.warning("Invalid username or password. Check your settings") return False return True def search(self, search_params, age=0, ep_obj=None): results = [] if not self.login(): return results for mode in search_params: items = [] logger.debug(_("Search Mode: {mode}".format(mode=mode))) for search_string in search_params[mode]: if mode != "RSS": logger.debug(_("Search String: {search_string}".format(search_string=search_string))) search_url = self.urls["search"] % (quote(search_string), self.categories) data = self.get_url(search_url, returns="text") if not data: continue try: with BS4Parser(data, "html5lib") as html: # Continue only if one Release is found empty = html.find("h2", text="No .torrents fit this filter criteria") if empty: logger.debug("Data returned from provider does not contain any torrents") continue torrent_table = html.find("table", style="border: none; width: 100%;") if not torrent_table: logger.exception("Could not find table of torrents") continue torrent_rows = torrent_table("tr", class_="browse") for result in torrent_rows: cells = result("td") size = None link = cells[1].find("a", style="font-size: 1.25em; font-weight: bold;") torrent_id = link["href"].replace("details.php?id=", "") try: if link.get("title", ""): title = link["title"] else: title = link.contents[0] download_url = self.urls["download"] % (torrent_id, link.contents[0]) seeders = int(cells[9].contents[0]) leechers = int(cells[10].contents[0]) # Need size for failed downloads handling if size is None: torrent_size = cells[7].text size = convert_size(torrent_size) or -1 except (AttributeError, TypeError): continue if not all([title, download_url]): continue # Filter unseeded torrent if seeders < self.minseed or leechers < self.minleech: if mode != "RSS": logger.debug( "Discarding torrent because it doesn't meet the minimum seeders or leechers: {0} (S:{1} L:{2})".format( title, seeders, leechers ) ) continue item = {"title": title, "link": download_url, "size": size, "seeders": seeders, "leechers": leechers, "hash": ""} if mode != "RSS": logger.debug("Found result: {0} with {1} seeders and {2} leechers".format(title, seeders, leechers)) items.append(item) except Exception: logger.exception("Failed parsing provider. Traceback: {0}".format(traceback.format_exc())) # For each search mode sort all the items by seeders if available items.sort(key=lambda d: try_int(d.get("seeders", 0)), reverse=True) results += items return results
h3llrais3r/SickRage
sickchill/oldbeard/providers/pretome.py
Python
gpl-3.0
5,958
/* General Demo Style */ @import url(https://fonts.googleapis.com/css?family=Lato:300,400,700); *, *:after, *:before { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; padding: 0; margin: 0; } /* Clearfix hack by Nicolas Gallagher: http://nicolasgallagher.com/micro-clearfix-hack/ */ .clearfix:before, .clearfix:after { content: " "; display: table; } .clearfix:after { clear: both; } .clearfix { *zoom: 1; } a { color: #555; text-decoration: none; } .container { width: 100%; position: relative; } .main, .container > header { width: 90%; max-width: 960px; margin: 0 auto; position: relative; padding: 0 10px; } .container > header { padding: 40px 10px 50px; border-bottom: 1px solid #ddd; box-shadow: 0 1px rgba(255,255,255,0.8); margin-bottom: 30px; } .container > header h1 { font-size: 34px; line-height: 38px; margin: 0; font-weight: 700; color: #333; float: left; } .container > header h1 span { display: block; font-size: 20px; font-weight: 300; } .fleft { float: left; width: 49%; min-width: 300px; } .main p { color: #AAA; padding: 20px 30px 0px 0px; font-size: 20px; line-height: 34px; font-weight: 300; text-shadow: 0 1px 1px rgba(255, 255, 255, 0.8); } /* Header Style */ .codrops-top { line-height: 24px; font-size: 11px; background: #fff; background: rgba(255, 255, 255, 0.5); text-transform: uppercase; z-index: 9999; position: relative; box-shadow: 1px 0px 2px rgba(0,0,0,0.2); } .codrops-top a { padding: 0px 10px; letter-spacing: 1px; color: #333; display: inline-block; } .codrops-top a:hover { background: rgba(255,255,255,0.8); color: #000; } .codrops-top span.right { float: right; } .codrops-top span.right a { float: left; display: block; } /* Demo Buttons Style */ .codrops-demos { float: right; padding-top: 10px; } .codrops-demos a { display: inline-block; margin: 10px; color: #666; font-weight: 700; line-height: 30px; border-bottom: 4px solid transparent; } .codrops-demos a:hover { color: #000; border-color: #000; } .codrops-demos a.current-demo, .codrops-demos a.current-demo:hover { color: #aaa; border-color: #aaa; } @media screen and (max-width: 730px){ .fleft { width: 100%; float: none; text-align: center; } }
hk1953/hk1953.github.io
css/demo.css
CSS
gpl-3.0
2,440
/* * Copyright (c) 2010 The University of Reading * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University of Reading, nor the names of the * authors or contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 uk.ac.rdg.resc.edal.coverage.domain; import java.util.List; import org.opengis.referencing.crs.CoordinateReferenceSystem; /** * A geospatial/temporal domain: defines the set of points for which a {@link DiscreteCoverage} * is defined. The domain is comprised of a set of unique domain objects in a * defined order. The domain therefore has the semantics of both a {@link Set} * and a {@link List} of domain objects. * @param <DO> The type of the domain object * @author Jon */ public interface Domain<DO> { /** * Gets the coordinate reference system to which objects in this domain are * referenced. Returns null if the domain objects cannot be referenced * to an external coordinate reference system. * @return the coordinate reference system to which objects in this domain are * referenced, or null if the domain objects are not externally referenced. */ public CoordinateReferenceSystem getCoordinateReferenceSystem(); /** * Returns the {@link List} of domain objects that comprise this domain. * @todo There may be issues for large grids if the number of domain objects * is greater than Integer.MAX_VALUE, as the size of this list will be recorded * incorrectly. This will only happen for very large domains (e.g. large grids). */ public List<DO> getDomainObjects(); /** * <p>Returns the number of domain objects in the domain.</p> * <p>This is a long integer because grids can grow very large, beyond the * range of a 4-byte integer.</p> */ public long size(); }
nansencenter/GreenSeasADC-portlet
docroot/WEB-INF/src/uk/ac/rdg/resc/edal/coverage/domain/Domain.java
Java
gpl-3.0
3,145
/***************************************************************** * This file is part of Managing Agricultural Research for Learning & * Outcomes Platform (MARLO). * MARLO 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. * MARLO 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 MARLO. If not, see <http://www.gnu.org/licenses/>. *****************************************************************/ package org.cgiar.ccafs.marlo.data.manager.impl; import org.cgiar.ccafs.marlo.data.dao.ReportSynthesisGovernanceDAO; import org.cgiar.ccafs.marlo.data.manager.ReportSynthesisGovernanceManager; import org.cgiar.ccafs.marlo.data.model.ReportSynthesisGovernance; import java.util.List; import javax.inject.Inject; import javax.inject.Named; /** * @author CCAFS */ @Named public class ReportSynthesisGovernanceManagerImpl implements ReportSynthesisGovernanceManager { private ReportSynthesisGovernanceDAO reportSynthesisGovernanceDAO; // Managers @Inject public ReportSynthesisGovernanceManagerImpl(ReportSynthesisGovernanceDAO reportSynthesisGovernanceDAO) { this.reportSynthesisGovernanceDAO = reportSynthesisGovernanceDAO; } @Override public void deleteReportSynthesisGovernance(long reportSynthesisGovernanceId) { reportSynthesisGovernanceDAO.deleteReportSynthesisGovernance(reportSynthesisGovernanceId); } @Override public boolean existReportSynthesisGovernance(long reportSynthesisGovernanceID) { return reportSynthesisGovernanceDAO.existReportSynthesisGovernance(reportSynthesisGovernanceID); } @Override public List<ReportSynthesisGovernance> findAll() { return reportSynthesisGovernanceDAO.findAll(); } @Override public ReportSynthesisGovernance getReportSynthesisGovernanceById(long reportSynthesisGovernanceID) { return reportSynthesisGovernanceDAO.find(reportSynthesisGovernanceID); } @Override public ReportSynthesisGovernance saveReportSynthesisGovernance(ReportSynthesisGovernance reportSynthesisGovernance) { return reportSynthesisGovernanceDAO.save(reportSynthesisGovernance); } }
CCAFS/MARLO
marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/manager/impl/ReportSynthesisGovernanceManagerImpl.java
Java
gpl-3.0
2,612
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_51) on Mon Mar 17 10:31:37 CDT 2014 --> <title>TIntFloatMapDecorator (Trove 3.1a1)</title> <meta name="date" content="2014-03-17"> <link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="TIntFloatMapDecorator (Trove 3.1a1)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-all.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><em><a href="http://trove4j.sourceforge.net/">GNU Trove</a></em></div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../gnu/trove/decorator/TIntDoubleMapDecorator.html" title="class in gnu.trove.decorator"><span class="strong">Prev Class</span></a></li> <li><a href="../../../gnu/trove/decorator/TIntIntMapDecorator.html" title="class in gnu.trove.decorator"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../index.html?gnu/trove/decorator/TIntFloatMapDecorator.html" target="_top">Frames</a></li> <li><a href="TIntFloatMapDecorator.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li><a href="#nested_classes_inherited_from_class_java.util.AbstractMap">Nested</a>&nbsp;|&nbsp;</li> <li><a href="#field_summary">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field_detail">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">gnu.trove.decorator</div> <h2 title="Class TIntFloatMapDecorator" class="title">Class TIntFloatMapDecorator</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>java.util.AbstractMap&lt;java.lang.Integer,java.lang.Float&gt;</li> <li> <ul class="inheritance"> <li>gnu.trove.decorator.TIntFloatMapDecorator</li> </ul> </li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Implemented Interfaces:</dt> <dd>java.io.Externalizable, java.io.Serializable, java.lang.Cloneable, java.util.Map&lt;java.lang.Integer,java.lang.Float&gt;</dd> </dl> <hr> <br> <pre>public class <span class="strong">TIntFloatMapDecorator</span> extends java.util.AbstractMap&lt;java.lang.Integer,java.lang.Float&gt; implements java.util.Map&lt;java.lang.Integer,java.lang.Float&gt;, java.io.Externalizable, java.lang.Cloneable</pre> <div class="block">Wrapper class to make a TIntFloatMap conform to the <tt>java.util.Map</tt> API. This class simply decorates an underlying TIntFloatMap and translates the Object-based APIs into their Trove primitive analogs. <p/> Note that wrapping and unwrapping primitive values is extremely inefficient. If possible, users of this class should override the appropriate methods in this class and use a table of canonical values. <p/> Created: Mon Sep 23 22:07:40 PDT 2002</div> <dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../serialized-form.html#gnu.trove.decorator.TIntFloatMapDecorator">Serialized Form</a></dd></dl> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ======== NESTED CLASS SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="nested_class_summary"> <!-- --> </a> <h3>Nested Class Summary</h3> <ul class="blockList"> <li class="blockList"><a name="nested_classes_inherited_from_class_java.util.AbstractMap"> <!-- --> </a> <h3>Nested classes/interfaces inherited from class&nbsp;java.util.AbstractMap</h3> <code>java.util.AbstractMap.SimpleEntry&lt;K,V&gt;, java.util.AbstractMap.SimpleImmutableEntry&lt;K,V&gt;</code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="nested_classes_inherited_from_class_java.util.Map"> <!-- --> </a> <h3>Nested classes/interfaces inherited from interface&nbsp;java.util.Map</h3> <code>java.util.Map.Entry&lt;K,V&gt;</code></li> </ul> </li> </ul> <!-- =========== FIELD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="field_summary"> <!-- --> </a> <h3>Field Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation"> <caption><span>Fields</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>protected <a href="../../../gnu/trove/map/TIntFloatMap.html" title="interface in gnu.trove.map">TIntFloatMap</a></code></td> <td class="colLast"><code><strong><a href="../../../gnu/trove/decorator/TIntFloatMapDecorator.html#_map">_map</a></strong></code> <div class="block">the wrapped primitive map</div> </td> </tr> </table> </li> </ul> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><strong><a href="../../../gnu/trove/decorator/TIntFloatMapDecorator.html#TIntFloatMapDecorator()">TIntFloatMapDecorator</a></strong>()</code> <div class="block">FOR EXTERNALIZATION ONLY!!</div> </td> </tr> <tr class="rowColor"> <td class="colOne"><code><strong><a href="../../../gnu/trove/decorator/TIntFloatMapDecorator.html#TIntFloatMapDecorator(gnu.trove.map.TIntFloatMap)">TIntFloatMapDecorator</a></strong>(<a href="../../../gnu/trove/map/TIntFloatMap.html" title="interface in gnu.trove.map">TIntFloatMap</a>&nbsp;map)</code> <div class="block">Creates a wrapper that decorates the specified primitive map.</div> </td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span>Methods</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../gnu/trove/decorator/TIntFloatMapDecorator.html#clear()">clear</a></strong>()</code> <div class="block">Empties the map.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><strong><a href="../../../gnu/trove/decorator/TIntFloatMapDecorator.html#containsKey(java.lang.Object)">containsKey</a></strong>(java.lang.Object&nbsp;key)</code> <div class="block">Checks for the present of <tt>key</tt> in the keys of the map.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><strong><a href="../../../gnu/trove/decorator/TIntFloatMapDecorator.html#containsValue(java.lang.Object)">containsValue</a></strong>(java.lang.Object&nbsp;val)</code> <div class="block">Checks for the presence of <tt>val</tt> in the values of the map.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>java.util.Set&lt;java.util.Map.Entry&lt;java.lang.Integer,java.lang.Float&gt;&gt;</code></td> <td class="colLast"><code><strong><a href="../../../gnu/trove/decorator/TIntFloatMapDecorator.html#entrySet()">entrySet</a></strong>()</code> <div class="block">Returns a Set view on the entries of the map.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>java.lang.Float</code></td> <td class="colLast"><code><strong><a href="../../../gnu/trove/decorator/TIntFloatMapDecorator.html#get(java.lang.Object)">get</a></strong>(java.lang.Object&nbsp;key)</code> <div class="block">Retrieves the value for <tt>key</tt></div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../gnu/trove/map/TIntFloatMap.html" title="interface in gnu.trove.map">TIntFloatMap</a></code></td> <td class="colLast"><code><strong><a href="../../../gnu/trove/decorator/TIntFloatMapDecorator.html#getMap()">getMap</a></strong>()</code> <div class="block">Returns a reference to the map wrapped by this decorator.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><strong><a href="../../../gnu/trove/decorator/TIntFloatMapDecorator.html#isEmpty()">isEmpty</a></strong>()</code> <div class="block">Indicates whether map has any entries.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>java.lang.Float</code></td> <td class="colLast"><code><strong><a href="../../../gnu/trove/decorator/TIntFloatMapDecorator.html#put(java.lang.Integer, java.lang.Float)">put</a></strong>(java.lang.Integer&nbsp;key, java.lang.Float&nbsp;value)</code> <div class="block">Inserts a key/value pair into the map.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../gnu/trove/decorator/TIntFloatMapDecorator.html#putAll(java.util.Map)">putAll</a></strong>(java.util.Map&lt;? extends java.lang.Integer,? extends java.lang.Float&gt;&nbsp;map)</code> <div class="block">Copies the key/value mappings in <tt>map</tt> into this map.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../gnu/trove/decorator/TIntFloatMapDecorator.html#readExternal(java.io.ObjectInput)">readExternal</a></strong>(java.io.ObjectInput&nbsp;in)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>java.lang.Float</code></td> <td class="colLast"><code><strong><a href="../../../gnu/trove/decorator/TIntFloatMapDecorator.html#remove(java.lang.Object)">remove</a></strong>(java.lang.Object&nbsp;key)</code> <div class="block">Deletes a key/value pair from the map.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>int</code></td> <td class="colLast"><code><strong><a href="../../../gnu/trove/decorator/TIntFloatMapDecorator.html#size()">size</a></strong>()</code> <div class="block">Returns the number of entries in the map.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>protected int</code></td> <td class="colLast"><code><strong><a href="../../../gnu/trove/decorator/TIntFloatMapDecorator.html#unwrapKey(java.lang.Object)">unwrapKey</a></strong>(java.lang.Object&nbsp;key)</code> <div class="block">Unwraps a key</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>protected float</code></td> <td class="colLast"><code><strong><a href="../../../gnu/trove/decorator/TIntFloatMapDecorator.html#unwrapValue(java.lang.Object)">unwrapValue</a></strong>(java.lang.Object&nbsp;value)</code> <div class="block">Unwraps a value</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>protected java.lang.Integer</code></td> <td class="colLast"><code><strong><a href="../../../gnu/trove/decorator/TIntFloatMapDecorator.html#wrapKey(int)">wrapKey</a></strong>(int&nbsp;k)</code> <div class="block">Wraps a key</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>protected java.lang.Float</code></td> <td class="colLast"><code><strong><a href="../../../gnu/trove/decorator/TIntFloatMapDecorator.html#wrapValue(float)">wrapValue</a></strong>(float&nbsp;k)</code> <div class="block">Wraps a value</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../gnu/trove/decorator/TIntFloatMapDecorator.html#writeExternal(java.io.ObjectOutput)">writeExternal</a></strong>(java.io.ObjectOutput&nbsp;out)</code>&nbsp;</td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_java.util.AbstractMap"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.util.AbstractMap</h3> <code>clone, equals, hashCode, keySet, toString, values</code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>finalize, getClass, notify, notifyAll, wait, wait, wait</code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_java.util.Map"> <!-- --> </a> <h3>Methods inherited from interface&nbsp;java.util.Map</h3> <code>equals, hashCode, keySet, values</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ FIELD DETAIL =========== --> <ul class="blockList"> <li class="blockList"><a name="field_detail"> <!-- --> </a> <h3>Field Detail</h3> <a name="_map"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>_map</h4> <pre>protected&nbsp;<a href="../../../gnu/trove/map/TIntFloatMap.html" title="interface in gnu.trove.map">TIntFloatMap</a> _map</pre> <div class="block">the wrapped primitive map</div> </li> </ul> </li> </ul> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="TIntFloatMapDecorator()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>TIntFloatMapDecorator</h4> <pre>public&nbsp;TIntFloatMapDecorator()</pre> <div class="block">FOR EXTERNALIZATION ONLY!!</div> </li> </ul> <a name="TIntFloatMapDecorator(gnu.trove.map.TIntFloatMap)"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>TIntFloatMapDecorator</h4> <pre>public&nbsp;TIntFloatMapDecorator(<a href="../../../gnu/trove/map/TIntFloatMap.html" title="interface in gnu.trove.map">TIntFloatMap</a>&nbsp;map)</pre> <div class="block">Creates a wrapper that decorates the specified primitive map.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>map</code> - the <tt>TIntFloatMap</tt> to wrap.</dd></dl> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method_detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="getMap()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getMap</h4> <pre>public&nbsp;<a href="../../../gnu/trove/map/TIntFloatMap.html" title="interface in gnu.trove.map">TIntFloatMap</a>&nbsp;getMap()</pre> <div class="block">Returns a reference to the map wrapped by this decorator.</div> <dl><dt><span class="strong">Returns:</span></dt><dd>the wrapped <tt>TIntFloatMap</tt> instance.</dd></dl> </li> </ul> <a name="put(java.lang.Integer, java.lang.Float)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>put</h4> <pre>public&nbsp;java.lang.Float&nbsp;put(java.lang.Integer&nbsp;key, java.lang.Float&nbsp;value)</pre> <div class="block">Inserts a key/value pair into the map.</div> <dl> <dt><strong>Specified by:</strong></dt> <dd><code>put</code>&nbsp;in interface&nbsp;<code>java.util.Map&lt;java.lang.Integer,java.lang.Float&gt;</code></dd> <dt><strong>Overrides:</strong></dt> <dd><code>put</code>&nbsp;in class&nbsp;<code>java.util.AbstractMap&lt;java.lang.Integer,java.lang.Float&gt;</code></dd> <dt><span class="strong">Parameters:</span></dt><dd><code>key</code> - an <code>Object</code> value</dd><dd><code>value</code> - an <code>Object</code> value</dd> <dt><span class="strong">Returns:</span></dt><dd>the previous value associated with <tt>key</tt>, or Float(0) if none was found.</dd></dl> </li> </ul> <a name="get(java.lang.Object)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>get</h4> <pre>public&nbsp;java.lang.Float&nbsp;get(java.lang.Object&nbsp;key)</pre> <div class="block">Retrieves the value for <tt>key</tt></div> <dl> <dt><strong>Specified by:</strong></dt> <dd><code>get</code>&nbsp;in interface&nbsp;<code>java.util.Map&lt;java.lang.Integer,java.lang.Float&gt;</code></dd> <dt><strong>Overrides:</strong></dt> <dd><code>get</code>&nbsp;in class&nbsp;<code>java.util.AbstractMap&lt;java.lang.Integer,java.lang.Float&gt;</code></dd> <dt><span class="strong">Parameters:</span></dt><dd><code>key</code> - an <code>Object</code> value</dd> <dt><span class="strong">Returns:</span></dt><dd>the value of <tt>key</tt> or null if no such mapping exists.</dd></dl> </li> </ul> <a name="clear()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>clear</h4> <pre>public&nbsp;void&nbsp;clear()</pre> <div class="block">Empties the map.</div> <dl> <dt><strong>Specified by:</strong></dt> <dd><code>clear</code>&nbsp;in interface&nbsp;<code>java.util.Map&lt;java.lang.Integer,java.lang.Float&gt;</code></dd> <dt><strong>Overrides:</strong></dt> <dd><code>clear</code>&nbsp;in class&nbsp;<code>java.util.AbstractMap&lt;java.lang.Integer,java.lang.Float&gt;</code></dd> </dl> </li> </ul> <a name="remove(java.lang.Object)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>remove</h4> <pre>public&nbsp;java.lang.Float&nbsp;remove(java.lang.Object&nbsp;key)</pre> <div class="block">Deletes a key/value pair from the map.</div> <dl> <dt><strong>Specified by:</strong></dt> <dd><code>remove</code>&nbsp;in interface&nbsp;<code>java.util.Map&lt;java.lang.Integer,java.lang.Float&gt;</code></dd> <dt><strong>Overrides:</strong></dt> <dd><code>remove</code>&nbsp;in class&nbsp;<code>java.util.AbstractMap&lt;java.lang.Integer,java.lang.Float&gt;</code></dd> <dt><span class="strong">Parameters:</span></dt><dd><code>key</code> - an <code>Object</code> value</dd> <dt><span class="strong">Returns:</span></dt><dd>the removed value, or null if it was not found in the map</dd></dl> </li> </ul> <a name="entrySet()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>entrySet</h4> <pre>public&nbsp;java.util.Set&lt;java.util.Map.Entry&lt;java.lang.Integer,java.lang.Float&gt;&gt;&nbsp;entrySet()</pre> <div class="block">Returns a Set view on the entries of the map.</div> <dl> <dt><strong>Specified by:</strong></dt> <dd><code>entrySet</code>&nbsp;in interface&nbsp;<code>java.util.Map&lt;java.lang.Integer,java.lang.Float&gt;</code></dd> <dt><strong>Specified by:</strong></dt> <dd><code>entrySet</code>&nbsp;in class&nbsp;<code>java.util.AbstractMap&lt;java.lang.Integer,java.lang.Float&gt;</code></dd> <dt><span class="strong">Returns:</span></dt><dd>a <code>Set</code> value</dd></dl> </li> </ul> <a name="containsValue(java.lang.Object)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>containsValue</h4> <pre>public&nbsp;boolean&nbsp;containsValue(java.lang.Object&nbsp;val)</pre> <div class="block">Checks for the presence of <tt>val</tt> in the values of the map.</div> <dl> <dt><strong>Specified by:</strong></dt> <dd><code>containsValue</code>&nbsp;in interface&nbsp;<code>java.util.Map&lt;java.lang.Integer,java.lang.Float&gt;</code></dd> <dt><strong>Overrides:</strong></dt> <dd><code>containsValue</code>&nbsp;in class&nbsp;<code>java.util.AbstractMap&lt;java.lang.Integer,java.lang.Float&gt;</code></dd> <dt><span class="strong">Parameters:</span></dt><dd><code>val</code> - an <code>Object</code> value</dd> <dt><span class="strong">Returns:</span></dt><dd>a <code>boolean</code> value</dd></dl> </li> </ul> <a name="containsKey(java.lang.Object)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>containsKey</h4> <pre>public&nbsp;boolean&nbsp;containsKey(java.lang.Object&nbsp;key)</pre> <div class="block">Checks for the present of <tt>key</tt> in the keys of the map.</div> <dl> <dt><strong>Specified by:</strong></dt> <dd><code>containsKey</code>&nbsp;in interface&nbsp;<code>java.util.Map&lt;java.lang.Integer,java.lang.Float&gt;</code></dd> <dt><strong>Overrides:</strong></dt> <dd><code>containsKey</code>&nbsp;in class&nbsp;<code>java.util.AbstractMap&lt;java.lang.Integer,java.lang.Float&gt;</code></dd> <dt><span class="strong">Parameters:</span></dt><dd><code>key</code> - an <code>Object</code> value</dd> <dt><span class="strong">Returns:</span></dt><dd>a <code>boolean</code> value</dd></dl> </li> </ul> <a name="size()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>size</h4> <pre>public&nbsp;int&nbsp;size()</pre> <div class="block">Returns the number of entries in the map.</div> <dl> <dt><strong>Specified by:</strong></dt> <dd><code>size</code>&nbsp;in interface&nbsp;<code>java.util.Map&lt;java.lang.Integer,java.lang.Float&gt;</code></dd> <dt><strong>Overrides:</strong></dt> <dd><code>size</code>&nbsp;in class&nbsp;<code>java.util.AbstractMap&lt;java.lang.Integer,java.lang.Float&gt;</code></dd> <dt><span class="strong">Returns:</span></dt><dd>the map's size.</dd></dl> </li> </ul> <a name="isEmpty()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>isEmpty</h4> <pre>public&nbsp;boolean&nbsp;isEmpty()</pre> <div class="block">Indicates whether map has any entries.</div> <dl> <dt><strong>Specified by:</strong></dt> <dd><code>isEmpty</code>&nbsp;in interface&nbsp;<code>java.util.Map&lt;java.lang.Integer,java.lang.Float&gt;</code></dd> <dt><strong>Overrides:</strong></dt> <dd><code>isEmpty</code>&nbsp;in class&nbsp;<code>java.util.AbstractMap&lt;java.lang.Integer,java.lang.Float&gt;</code></dd> <dt><span class="strong">Returns:</span></dt><dd>true if the map is empty</dd></dl> </li> </ul> <a name="putAll(java.util.Map)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>putAll</h4> <pre>public&nbsp;void&nbsp;putAll(java.util.Map&lt;? extends java.lang.Integer,? extends java.lang.Float&gt;&nbsp;map)</pre> <div class="block">Copies the key/value mappings in <tt>map</tt> into this map. Note that this will be a <b>deep</b> copy, as storage is by primitive value.</div> <dl> <dt><strong>Specified by:</strong></dt> <dd><code>putAll</code>&nbsp;in interface&nbsp;<code>java.util.Map&lt;java.lang.Integer,java.lang.Float&gt;</code></dd> <dt><strong>Overrides:</strong></dt> <dd><code>putAll</code>&nbsp;in class&nbsp;<code>java.util.AbstractMap&lt;java.lang.Integer,java.lang.Float&gt;</code></dd> <dt><span class="strong">Parameters:</span></dt><dd><code>map</code> - a <code>Map</code> value</dd></dl> </li> </ul> <a name="wrapKey(int)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>wrapKey</h4> <pre>protected&nbsp;java.lang.Integer&nbsp;wrapKey(int&nbsp;k)</pre> <div class="block">Wraps a key</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>k</code> - key in the underlying map</dd> <dt><span class="strong">Returns:</span></dt><dd>an Object representation of the key</dd></dl> </li> </ul> <a name="unwrapKey(java.lang.Object)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>unwrapKey</h4> <pre>protected&nbsp;int&nbsp;unwrapKey(java.lang.Object&nbsp;key)</pre> <div class="block">Unwraps a key</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>key</code> - wrapped key</dd> <dt><span class="strong">Returns:</span></dt><dd>an unwrapped representation of the key</dd></dl> </li> </ul> <a name="wrapValue(float)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>wrapValue</h4> <pre>protected&nbsp;java.lang.Float&nbsp;wrapValue(float&nbsp;k)</pre> <div class="block">Wraps a value</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>k</code> - value in the underlying map</dd> <dt><span class="strong">Returns:</span></dt><dd>an Object representation of the value</dd></dl> </li> </ul> <a name="unwrapValue(java.lang.Object)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>unwrapValue</h4> <pre>protected&nbsp;float&nbsp;unwrapValue(java.lang.Object&nbsp;value)</pre> <div class="block">Unwraps a value</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>value</code> - wrapped value</dd> <dt><span class="strong">Returns:</span></dt><dd>an unwrapped representation of the value</dd></dl> </li> </ul> <a name="readExternal(java.io.ObjectInput)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>readExternal</h4> <pre>public&nbsp;void&nbsp;readExternal(java.io.ObjectInput&nbsp;in) throws java.io.IOException, java.lang.ClassNotFoundException</pre> <dl> <dt><strong>Specified by:</strong></dt> <dd><code>readExternal</code>&nbsp;in interface&nbsp;<code>java.io.Externalizable</code></dd> <dt><span class="strong">Throws:</span></dt> <dd><code>java.io.IOException</code></dd> <dd><code>java.lang.ClassNotFoundException</code></dd></dl> </li> </ul> <a name="writeExternal(java.io.ObjectOutput)"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>writeExternal</h4> <pre>public&nbsp;void&nbsp;writeExternal(java.io.ObjectOutput&nbsp;out) throws java.io.IOException</pre> <dl> <dt><strong>Specified by:</strong></dt> <dd><code>writeExternal</code>&nbsp;in interface&nbsp;<code>java.io.Externalizable</code></dd> <dt><span class="strong">Throws:</span></dt> <dd><code>java.io.IOException</code></dd></dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-all.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><em><a href="http://trove4j.sourceforge.net/">GNU Trove</a></em></div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../gnu/trove/decorator/TIntDoubleMapDecorator.html" title="class in gnu.trove.decorator"><span class="strong">Prev Class</span></a></li> <li><a href="../../../gnu/trove/decorator/TIntIntMapDecorator.html" title="class in gnu.trove.decorator"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../index.html?gnu/trove/decorator/TIntFloatMapDecorator.html" target="_top">Frames</a></li> <li><a href="TIntFloatMapDecorator.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li><a href="#nested_classes_inherited_from_class_java.util.AbstractMap">Nested</a>&nbsp;|&nbsp;</li> <li><a href="#field_summary">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field_detail">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
achraftriki/test2
javadocs/gnu/trove/decorator/TIntFloatMapDecorator.html
HTML
gpl-3.0
29,372
/*jshint expr:true */ describe("Services: Core System Messages", function() { beforeEach(module("risevision.core.systemmessages")); beforeEach(module(function ($provide) { //stub services $provide.service("$q", function() {return Q;}); $provide.value("userState", { isRiseVisionUser: function () {return true; } }); })); it("should exist", function() { inject(function(getCoreSystemMessages) { expect(getCoreSystemMessages).be.defined; }); }); });
Rise-Vision/ng-core-api-client
test/unit/svc-system-messages-spec.js
JavaScript
gpl-3.0
499
{% load i18n %} <table class="tabledisplay"> <tbody><tr><th>{% trans 'Vraag' %}</th><th>{% trans 'Antwoord' %}</th></tr> <tr><td colspan="2"><h5><i>Algemeen</i></h5></td></tr> <tr><td>{% trans 'Beoordeling algemene gezondheid' %}</td><td>{{ questionnaire.get_health_general_display|default:"-" }}</td></tr> <tr><td>{% trans 'Beoordeling algemene gezondheid in vergelijking met vorig jaar' %}</td><td>{{ questionnaire.get_health_changes_display|default:"-" }}</td></tr> <tr><td colspan="2"><h5><i>Inspanningen</i></h5></td></tr> <tr><td>{% trans 'Forse inspanning zoals hardlopen, zware voorwerpen tillen, inspannend sporten' %}</td><td>{{ questionnaire.get_high_effort_impact_display|default:"-" }}</td></tr> <tr><td>{% trans 'Matige inspanning zoals het verplaatsen van een tafel, stofzuigen, fietsen' %}</td><td>{{ questionnaire.get_poor_effort_impact_display|default:"-" }}</td></tr> <tr><td>{% trans 'Tillen of boodschappen doen' %}</td><td>{{ questionnaire.get_carrying_impact_display|default:"-" }}</td></tr> <tr><td>{% trans 'Een paar trappen lopen' %}</td><td>{{ questionnaire.get_walking_stairs_impact_display|default:"-" }}</td></tr> <tr><td>{% trans 'Een trap lopen' %}</td><td>{{ questionnaire.get_walking_one_stair_impact_display|default:"-" }}</td></tr> <tr><td>{% trans 'Buigen, knielen of bukken' %}</td><td>{{ questionnaire.get_bent_over_impact_display|default:"-" }}</td></tr> <tr><td>{% trans 'Meer dan een kilometer lopen' %}</td><td>{{ questionnaire.get_walk_km_impact_display|default:"-" }}</td></tr> <tr><td>{% trans 'Een halve kilometer lopen' %}</td><td>{{ questionnaire.get_walk_halfkm_impact_display|default:"-" }}</td></tr> <tr><td>{% trans 'Honderd meter lopen' %}</td><td>{{ questionnaire.get_walk_tenthkm_impact_display|default:"-" }}</td></tr> <tr><td>{% trans 'Wassen of aankleden' %}</td><td>{{ questionnaire.get_wash_cloth_impact_display|default:"-" }}</td></tr> <tr><td colspan="2"><h5><i>Fysieke problemen</i></h5></td></tr> <tr><td>{% trans 'Minder tijd kunnen besteden aan werk of andere bezigheden' %}</td><td>{{ questionnaire.get_work_less_problem_display|default:"-" }}</td></tr> <tr><td>{% trans 'Minder bereikt dan u zou willen' %}</td><td>{{ questionnaire.get_achieve_problem_display|default:"-" }}</td></tr> <tr><td>{% trans 'Beperkt in het soort werk of het soort bezigheden' %}</td><td>{{ questionnaire.get_work_limitation_problem_display|default:"-" }}</td></tr> <tr><td>{% trans 'Moeite met het werk of andere bezigheden' %}</td><td>{{ questionnaire.get_work_effort_problem_display|default:"-" }}</td></tr> <tr><td colspan="2"><h5><i>Emotionele problemen</i></h5></td></tr> <tr><td>{% trans 'Minder tijd kunnen besteden aan werk of andere bezigheden' %}</td><td>{{ questionnaire.get_work_less_emotional_problem_display|default:"-" }}</td></tr> <tr><td>{% trans 'Minder bereikt dan u zou willen' %}</td><td>{{ questionnaire.get_achieve_problem_display|default:"-" }}</td></tr> <tr><td>{% trans 'Het werk of andere bezigheden niet zo zorgvuldig gedaan als u gewend bent' %}</td><td>{{ questionnaire.get_accurate_emotional_problem_display|default:"-" }}</td></tr> <tr><td colspan="2"><h5><i>Sociale en pijn impact</i></h5></td></tr> <tr><td>{% trans 'Heeft u lichamelijke of hebben uw emotionele problemen u de afgelopen 4 weken belemmerd in uw normale sociale bezigheden met gezin, vrienden, buren of anderen' %}</td><td>{{ questionnaire.get_social_impact_display|default:"-" }}</td></tr> <tr><td>{% trans 'Hoeveel pijn had u de afgelopen 4 weken' %}</td><td>{{ questionnaire.get_pain_score_display|default:"-" }}</td></tr> <tr><td>{% trans 'Heeft pijn u in de afgelopen 4 weken belemmerd bij uw normale werkzaamheden' %}</td><td>{{ questionnaire.get_pain_impact_display|default:"-" }}</td></tr> <tr><td colspan="2"><h5><i>Gevoel</i></h5></td></tr> <tr><td>{% trans 'Voelde u zich levenslustig' %}</td><td>{{ questionnaire.get_cheerful_score_display|default:"-" }}</td></tr> <tr><td>{% trans 'Voelde u zich zenuwachtig' %}</td><td>{{ questionnaire.get_nervious_score_display|default:"-" }}</td></tr> <tr><td>{% trans 'Zat u zo in de put dat niets u kon opvrolijken' %}</td><td>{{ questionnaire.get_blues_score_display|default:"-" }}</td></tr> <tr><td>{% trans 'Voelde u zich kalm en rustig' %}</td><td>{{ questionnaire.get_calm_score_display|default:"-" }}</td></tr> <tr><td>{% trans 'Voelde u zich energiek' %}</td><td>{{ questionnaire.get_energetic_score_display|default:"-" }}</td></tr> <tr><td>{% trans 'Voelde u zich neerslachtig en somber' %}</td><td>{{ questionnaire.get_depressed_score_display|default:"-" }}</td></tr> <tr><td>{% trans 'Voelde u zich uitgeblust' %}</td><td>{{ questionnaire.get_burnout_score_display|default:"-" }}</td></tr> <tr><td>{% trans 'Voelde u zich gelukkig' %}</td><td>{{ questionnaire.get_happiness_score_display|default:"-" }}</td></tr> <tr><td>{% trans 'Voelde u zich moe' %}</td><td>{{ questionnaire.get_tired_score_display|default:"-" }}</td></tr> <tr><td colspan="2"><h5><i>Sociaal</i></h5></td></tr> <tr><td>{% trans 'Hoe vaak uw lichamelijke gezondheid of uw emotionele problemen gedurende de afgelopen 4 weken uw sociale activiteiten (bijv. bezoek vrienden, familie) belemmerd' %}</td><td>{{ questionnaire.get_social_visit_impact_display|default:"-" }}</td></tr> <tr><td colspan="2"><h5><i>Relativatie</i></h5></td></tr> <tr><td>{% trans 'Ik lijk gemakkelijker ziek te worden dan andere mensen' %}</td><td>{{ questionnaire.get_easier_ill_score_display|default:"-" }}</td></tr> <tr><td>{% trans 'Ik ben net zo gezond als andere mensen die ik ken' %}</td><td>{{ questionnaire.get_even_healthy_score_display|default:"-" }}</td></tr> <tr><td>{% trans 'Ik verwacht dat mijn gezondheid achteruit zal gaan' %}</td><td>{{ questionnaire.get_health_drop_score_display|default:"-" }}</td></tr> <tr><td>{% trans 'Mijn gezondheid is uitstekend' %}</td><td>{{ questionnaire.get_health_drop_score_display|default:"-" }}</td></tr> </tbody></table>
acesonl/remotecare
remotecare/apps/questionnaire/templates/questionnaire/details/RheumatismSF36.html
HTML
gpl-3.0
6,185
/// <reference path="grid_astar.ts" /> // create abstract grid representation (no nodes here) var grid = [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1], [1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1], [1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1], [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]; var tileSize = 20; var start = [5,4]; var goal1 = [19,11]; var goal2 = [10,13]; window.onload = function() { var canvas = document.getElementById("gridCanvas"); canvas.addEventListener("mousedown", function(event) { var x = event.pageX - canvas.offsetLeft; var y = event.pageY - canvas.offsetTop; var cellX = Math.floor(x / tileSize); var cellY = Math.floor(y / tileSize); toggleGridCell(cellX, cellY); testEuclidean(); }, false); testEuclidean(); }; function toggleGridCell(x, y) { if ((x === start[0] && y === start[1]) || (x === goal1[0] && y === goal1[1]) || (x === goal2[0] && y === goal2[1])) { return; } if (grid[y][x] === 0) { grid[y][x] = 1; } else { grid[y][x] = 0; } } function drawGrid(path, visited) { var canvas = <HTMLCanvasElement>document.getElementById("gridCanvas"); var context = canvas.getContext("2d"); var h = grid.length; var w = grid[0].length; for (var x = 0; x < w; x++) { for (var y = 0; y < h; y++) { if (grid[y][x] == 0) { context.fillStyle = "#999"; } else { context.fillStyle = "black"; } context.fillRect(x*tileSize, y*tileSize, tileSize-1, tileSize-1); } } for (var i = 0; i < visited.length; i++) { var current = visited[i]; context.fillStyle = "lightgreen"; context.fillRect(current.x*tileSize, current.y*tileSize, tileSize-1, tileSize-1) } for (var i = 0; i < path.length; i++) { var current = path[i]; context.fillStyle = "green"; context.fillRect(current.x*tileSize, current.y*tileSize, tileSize-1, tileSize-1) } context.fillStyle = "yellow"; context.fillRect(start[0]*tileSize, start[1]*tileSize, tileSize-1, tileSize-1); context.fillStyle = "red"; context.fillRect(goal1[0]*tileSize, goal1[1]*tileSize, tileSize-1, tileSize-1); context.fillRect(goal2[0]*tileSize, goal2[1]*tileSize, tileSize-1, tileSize-1); } function testHeuristic(heuristic) { var graphGoal = new grid_astar.MultipleGoals([goal1,goal2]); var graph = new astar.Graph(heuristic, graphGoal); var graphStart = new grid_astar.Node(grid,start[0],start[1]); var result = graph.searchPath(graphStart); drawGrid(result.path, result.visited); var resultString = document.getElementById("info"); if (result.found) { resultString.innerHTML = "Length of path found: " + result.path.length; } else { resultString.innerHTML = "No path found."; } } function testDijkstra(){ //test graph with no heuristics testHeuristic(new grid_astar.DijkstraHeuristic()); } function testEuclidean(){ //test graph with Euclidean distance testHeuristic(new grid_astar.EuclidianHeuristic()); } function testManhattan(){ //test graph with Manhattan distance testHeuristic(new grid_astar.ManhattanHeuristic()); }
MastersOfDisasters/shrdlite-course-project
astar/grid_test.ts
TypeScript
gpl-3.0
4,016
// Copyright ©2015 The gonum Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package gonum import ( "gonum.org/v1/gonum/blas" "gonum.org/v1/gonum/lapack" ) // Dlasr applies a sequence of plane rotations to the m×n matrix A. This series // of plane rotations is implicitly represented by a matrix P. P is multiplied // by a depending on the value of side -- A = P * A if side == lapack.Left, // A = A * P^T if side == lapack.Right. // //The exact value of P depends on the value of pivot, but in all cases P is // implicitly represented by a series of 2×2 rotation matrices. The entries of // rotation matrix k are defined by s[k] and c[k] // R(k) = [ c[k] s[k]] // [-s[k] s[k]] // If direct == lapack.Forward, the rotation matrices are applied as // P = P(z-1) * ... * P(2) * P(1), while if direct == lapack.Backward they are // applied as P = P(1) * P(2) * ... * P(n). // // pivot defines the mapping of the elements in R(k) to P(k). // If pivot == lapack.Variable, the rotation is performed for the (k, k+1) plane. // P(k) = [1 ] // [ ... ] // [ 1 ] // [ c[k] s[k] ] // [ -s[k] c[k] ] // [ 1 ] // [ ... ] // [ 1] // if pivot == lapack.Top, the rotation is performed for the (1, k+1) plane, // P(k) = [c[k] s[k] ] // [ 1 ] // [ ... ] // [ 1 ] // [-s[k] c[k] ] // [ 1 ] // [ ... ] // [ 1] // and if pivot == lapack.Bottom, the rotation is performed for the (k, z) plane. // P(k) = [1 ] // [ ... ] // [ 1 ] // [ c[k] s[k]] // [ 1 ] // [ ... ] // [ 1 ] // [ -s[k] c[k]] // s and c have length m - 1 if side == blas.Left, and n - 1 if side == blas.Right. // // Dlasr is an internal routine. It is exported for testing purposes. func (impl Implementation) Dlasr(side blas.Side, pivot lapack.Pivot, direct lapack.Direct, m, n int, c, s, a []float64, lda int) { checkMatrix(m, n, a, lda) if side != blas.Left && side != blas.Right { panic(badSide) } if pivot != lapack.Variable && pivot != lapack.Top && pivot != lapack.Bottom { panic(badPivot) } if direct != lapack.Forward && direct != lapack.Backward { panic(badDirect) } if side == blas.Left { if len(c) < m-1 { panic(badSlice) } if len(s) < m-1 { panic(badSlice) } } else { if len(c) < n-1 { panic(badSlice) } if len(s) < n-1 { panic(badSlice) } } if m == 0 || n == 0 { return } if side == blas.Left { if pivot == lapack.Variable { if direct == lapack.Forward { for j := 0; j < m-1; j++ { ctmp := c[j] stmp := s[j] if ctmp != 1 || stmp != 0 { for i := 0; i < n; i++ { tmp2 := a[j*lda+i] tmp := a[(j+1)*lda+i] a[(j+1)*lda+i] = ctmp*tmp - stmp*tmp2 a[j*lda+i] = stmp*tmp + ctmp*tmp2 } } } return } for j := m - 2; j >= 0; j-- { ctmp := c[j] stmp := s[j] if ctmp != 1 || stmp != 0 { for i := 0; i < n; i++ { tmp2 := a[j*lda+i] tmp := a[(j+1)*lda+i] a[(j+1)*lda+i] = ctmp*tmp - stmp*tmp2 a[j*lda+i] = stmp*tmp + ctmp*tmp2 } } } return } else if pivot == lapack.Top { if direct == lapack.Forward { for j := 1; j < m; j++ { ctmp := c[j-1] stmp := s[j-1] if ctmp != 1 || stmp != 0 { for i := 0; i < n; i++ { tmp := a[j*lda+i] tmp2 := a[i] a[j*lda+i] = ctmp*tmp - stmp*tmp2 a[i] = stmp*tmp + ctmp*tmp2 } } } return } for j := m - 1; j >= 1; j-- { ctmp := c[j-1] stmp := s[j-1] if ctmp != 1 || stmp != 0 { for i := 0; i < n; i++ { ctmp := c[j-1] stmp := s[j-1] if ctmp != 1 || stmp != 0 { for i := 0; i < n; i++ { tmp := a[j*lda+i] tmp2 := a[i] a[j*lda+i] = ctmp*tmp - stmp*tmp2 a[i] = stmp*tmp + ctmp*tmp2 } } } } } return } if direct == lapack.Forward { for j := 0; j < m-1; j++ { ctmp := c[j] stmp := s[j] if ctmp != 1 || stmp != 0 { for i := 0; i < n; i++ { tmp := a[j*lda+i] tmp2 := a[(m-1)*lda+i] a[j*lda+i] = stmp*tmp2 + ctmp*tmp a[(m-1)*lda+i] = ctmp*tmp2 - stmp*tmp } } } return } for j := m - 2; j >= 0; j-- { ctmp := c[j] stmp := s[j] if ctmp != 1 || stmp != 0 { for i := 0; i < n; i++ { tmp := a[j*lda+i] tmp2 := a[(m-1)*lda+i] a[j*lda+i] = stmp*tmp2 + ctmp*tmp a[(m-1)*lda+i] = ctmp*tmp2 - stmp*tmp } } } return } if pivot == lapack.Variable { if direct == lapack.Forward { for j := 0; j < n-1; j++ { ctmp := c[j] stmp := s[j] if ctmp != 1 || stmp != 0 { for i := 0; i < m; i++ { tmp := a[i*lda+j+1] tmp2 := a[i*lda+j] a[i*lda+j+1] = ctmp*tmp - stmp*tmp2 a[i*lda+j] = stmp*tmp + ctmp*tmp2 } } } return } for j := n - 2; j >= 0; j-- { ctmp := c[j] stmp := s[j] if ctmp != 1 || stmp != 0 { for i := 0; i < m; i++ { tmp := a[i*lda+j+1] tmp2 := a[i*lda+j] a[i*lda+j+1] = ctmp*tmp - stmp*tmp2 a[i*lda+j] = stmp*tmp + ctmp*tmp2 } } } return } else if pivot == lapack.Top { if direct == lapack.Forward { for j := 1; j < n; j++ { ctmp := c[j-1] stmp := s[j-1] if ctmp != 1 || stmp != 0 { for i := 0; i < m; i++ { tmp := a[i*lda+j] tmp2 := a[i*lda] a[i*lda+j] = ctmp*tmp - stmp*tmp2 a[i*lda] = stmp*tmp + ctmp*tmp2 } } } return } for j := n - 1; j >= 1; j-- { ctmp := c[j-1] stmp := s[j-1] if ctmp != 1 || stmp != 0 { for i := 0; i < m; i++ { tmp := a[i*lda+j] tmp2 := a[i*lda] a[i*lda+j] = ctmp*tmp - stmp*tmp2 a[i*lda] = stmp*tmp + ctmp*tmp2 } } } return } if direct == lapack.Forward { for j := 0; j < n-1; j++ { ctmp := c[j] stmp := s[j] if ctmp != 1 || stmp != 0 { for i := 0; i < m; i++ { tmp := a[i*lda+j] tmp2 := a[i*lda+n-1] a[i*lda+j] = stmp*tmp2 + ctmp*tmp a[i*lda+n-1] = ctmp*tmp2 - stmp*tmp } } } return } for j := n - 2; j >= 0; j-- { ctmp := c[j] stmp := s[j] if ctmp != 1 || stmp != 0 { for i := 0; i < m; i++ { tmp := a[i*lda+j] tmp2 := a[i*lda+n-1] a[i*lda+j] = stmp*tmp2 + ctmp*tmp a[i*lda+n-1] = ctmp*tmp2 - stmp*tmp } } } }
pts-eduardoacuna/pachy-learning
vendor/gonum.org/v1/gonum/lapack/gonum/dlasr.go
GO
gpl-3.0
6,827
# -*- encoding: UTF-8 -*- import re import sys import os import traceback from ..ibdawg import IBDAWG from ..echo import echo from . import gc_options __all__ = [ "lang", "locales", "pkg", "name", "version", "author", \ "load", "parse", "getDictionary", \ "setOptions", "getOptions", "getOptionsLabels", "resetOptions", \ "ignoreRule", "resetIgnoreRules" ] __version__ = u"${version}" lang = u"${lang}" locales = ${loc} pkg = u"${implname}" name = u"${name}" version = u"${version}" author = u"${author}" # commons regexes _zEndOfSentence = re.compile(u'([.?!:;…][ .?!… »”")]*|.$)') _zBeginOfParagraph = re.compile(u"^\W*") _zEndOfParagraph = re.compile(u"\W*$") _zNextWord = re.compile(u" +(\w[\w-]*)") _zPrevWord = re.compile(u"(\w[\w-]*) +$") # grammar rules and dictionary _rules = None _dOptions = dict(gc_options.dOpt) # duplication necessary, to be able to reset to default _aIgnoredRules = set() _oDict = None _dAnalyses = {} # cache for data from dictionary _GLOBALS = globals() #### Parsing def parse (sText, sCountry="${country_default}", bDebug=False, dOptions=None): "analyses the paragraph sText and returns list of errors" aErrors = None sAlt = sText dDA = {} dOpt = _dOptions if not dOptions else dOptions # parse paragraph try: sNew, aErrors = _proofread(sText, sAlt, 0, True, dDA, sCountry, dOpt, bDebug) if sNew: sText = sNew except: raise # parse sentences for iStart, iEnd in _getSentenceBoundaries(sText): if 4 < (iEnd - iStart) < 2000: dDA.clear() try: _, errs = _proofread(sText[iStart:iEnd], sAlt[iStart:iEnd], iStart, False, dDA, sCountry, dOpt, bDebug) aErrors.extend(errs) except: raise return aErrors def _getSentenceBoundaries (sText): iStart = _zBeginOfParagraph.match(sText).end() for m in _zEndOfSentence.finditer(sText): yield (iStart, m.end()) iStart = m.end() def _proofread (s, sx, nOffset, bParagraph, dDA, sCountry, dOptions, bDebug): aErrs = [] bChange = False if not bParagraph: # after the first pass, we modify automatically some characters if u" " in s: s = s.replace(u" ", u' ') # nbsp bChange = True if u" " in s: s = s.replace(u" ", u' ') # nnbsp bChange = True if u"@" in s: s = s.replace(u"@", u' ') bChange = True if u"'" in s: s = s.replace(u"'", u"’") bChange = True if u"‑" in s: s = s.replace(u"‑", u"-") # nobreakdash bChange = True bIdRule = option('idrule') for sOption, lRuleGroup in _getRules(bParagraph): if not sOption or dOptions.get(sOption, False): for zRegex, bUppercase, sRuleId, lActions in lRuleGroup: if sRuleId not in _aIgnoredRules: for m in zRegex.finditer(s): for sFuncCond, cActionType, sWhat, *eAct in lActions: # action in lActions: [ condition, action type, replacement/suggestion/action[, iGroup[, message, URL]] ] try: if not sFuncCond or _GLOBALS[sFuncCond](s, sx, m, dDA, sCountry): if cActionType == "-": # grammar error # (text, replacement, nOffset, m, iGroup, sId, bUppercase, sURL, bIdRule) aErrs.append(_createError(s, sWhat, nOffset, m, eAct[0], sRuleId, bUppercase, eAct[1], eAct[2], bIdRule, sOption)) elif cActionType == "~": # text processor s = _rewrite(s, sWhat, eAct[0], m, bUppercase) bChange = True if bDebug: echo(u"~ " + s + " -- " + m.group(eAct[0]) + " # " + sRuleId) elif cActionType == "=": # disambiguation _GLOBALS[sWhat](s, m, dDA) if bDebug: echo(u"= " + m.group(0) + " # " + sRuleId + "\nDA: " + str(dDA)) else: echo("# error: unknown action at " + sRuleId) except Exception as e: raise Exception(str(e), sRuleId) if bChange: return (s, aErrs) return (False, aErrs) def _createWriterError (s, sRepl, nOffset, m, iGroup, sId, bUppercase, sMsg, sURL, bIdRule, sOption): "error for Writer (LO/OO)" xErr = SingleProofreadingError() #xErr = uno.createUnoStruct( "com.sun.star.linguistic2.SingleProofreadingError" ) xErr.nErrorStart = nOffset + m.start(iGroup) xErr.nErrorLength = m.end(iGroup) - m.start(iGroup) xErr.nErrorType = PROOFREADING xErr.aRuleIdentifier = sId # suggestions if sRepl[0:1] == "=": sugg = _GLOBALS[sRepl[1:]](s, m) if sugg: if bUppercase and m.group(iGroup)[0:1].isupper(): xErr.aSuggestions = tuple(map(str.capitalize, sugg.split("|"))) else: xErr.aSuggestions = tuple(sugg.split("|")) else: xErr.aSuggestions = () elif sRepl == "_": xErr.aSuggestions = () else: if bUppercase and m.group(iGroup)[0:1].isupper(): xErr.aSuggestions = tuple(map(str.capitalize, m.expand(sRepl).split("|"))) else: xErr.aSuggestions = tuple(m.expand(sRepl).split("|")) # Message if sMsg[0:1] == "=": sMessage = _GLOBALS[sMsg[1:]](s, m) else: sMessage = m.expand(sMsg) xErr.aShortComment = sMessage # sMessage.split("|")[0] # in context menu xErr.aFullComment = sMessage # sMessage.split("|")[-1] # in dialog if bIdRule: xErr.aShortComment += " # " + sId # URL if sURL: p = PropertyValue() p.Name = "FullCommentURL" p.Value = sURL xErr.aProperties = (p,) else: xErr.aProperties = () return xErr def _createDictError (s, sRepl, nOffset, m, iGroup, sId, bUppercase, sMsg, sURL, bIdRule, sOption): "error as a dictionary" dErr = {} dErr["nStart"] = nOffset + m.start(iGroup) dErr["nEnd"] = nOffset + m.end(iGroup) dErr["sRuleId"] = sId dErr["sType"] = sOption if sOption else "notype" # suggestions if sRepl[0:1] == "=": sugg = _GLOBALS[sRepl[1:]](s, m) if sugg: if bUppercase and m.group(iGroup)[0:1].isupper(): dErr["aSuggestions"] = list(map(str.capitalize, sugg.split("|"))) else: dErr["aSuggestions"] = sugg.split("|") else: dErr["aSuggestions"] = () elif sRepl == "_": dErr["aSuggestions"] = () else: if bUppercase and m.group(iGroup)[0:1].isupper(): dErr["aSuggestions"] = list(map(str.capitalize, m.expand(sRepl).split("|"))) else: dErr["aSuggestions"] = m.expand(sRepl).split("|") # Message if sMsg[0:1] == "=": sMessage = _GLOBALS[sMsg[1:]](s, m) else: sMessage = m.expand(sMsg) dErr["sMessage"] = sMessage if bIdRule: dErr["sMessage"] += " # " + sId # URL dErr["URL"] = sURL if sURL else "" return dErr def _rewrite (s, sRepl, iGroup, m, bUppercase): "text processor: write sRepl in s at iGroup position" ln = m.end(iGroup) - m.start(iGroup) if sRepl == "*": sNew = " " * ln elif sRepl == ">" or sRepl == "_" or sRepl == u"~": sNew = sRepl + " " * (ln-1) elif sRepl == "@": sNew = "@" * ln elif sRepl[0:1] == "=": if sRepl[1:2] != "@": sNew = _GLOBALS[sRepl[1:]](s, m) sNew = sNew + " " * (ln-len(sNew)) else: sNew = _GLOBALS[sRepl[2:]](s, m) sNew = sNew + "@" * (ln-len(sNew)) if bUppercase and m.group(iGroup)[0:1].isupper(): sNew = sNew.capitalize() else: sNew = m.expand(sRepl) sNew = sNew + " " * (ln-len(sNew)) return s[0:m.start(iGroup)] + sNew + s[m.end(iGroup):] def ignoreRule (sId): _aIgnoredRules.add(sId) def resetIgnoreRules (): _aIgnoredRules.clear() #### init try: # LibreOffice / OpenOffice from com.sun.star.linguistic2 import SingleProofreadingError from com.sun.star.text.TextMarkupType import PROOFREADING from com.sun.star.beans import PropertyValue #import lightproof_handler_${implname} as opt _createError = _createWriterError except ImportError: _createError = _createDictError def load (): global _oDict try: _oDict = IBDAWG("${binary_dic}") except: traceback.print_exc() def setOptions (dOpt): _dOptions.update(dOpt) def getOptions (): return _dOptions def getOptionsLabels (sLang): return gc_options.getUI(sLang) def resetOptions (): global _dOptions _dOptions = dict(gc_options.dOpt) def getDictionary (): return _oDict def _getRules (bParagraph): try: if not bParagraph: return _rules.lSentenceRules return _rules.lParagraphRules except: _loadRules() if not bParagraph: return _rules.lSentenceRules return _rules.lParagraphRules def _loadRules2 (): from itertools import chain from . import gc_rules global _rules _rules = gc_rules # compile rules regex for rule in chain(_rules.lParagraphRules, _rules.lSentenceRules): try: rule[1] = re.compile(rule[1]) except: echo("Bad regular expression in # " + str(rule[3])) rule[1] = "(?i)<Grammalecte>" def _loadRules (): from itertools import chain from . import gc_rules global _rules _rules = gc_rules # compile rules regex for rulegroup in chain(_rules.lParagraphRules, _rules.lSentenceRules): for rule in rulegroup[1]: try: rule[0] = re.compile(rule[0]) except: echo("Bad regular expression in # " + str(rule[2])) rule[0] = "(?i)<Grammalecte>" def _getPath (): return os.path.join(os.path.dirname(sys.modules[__name__].__file__), __name__ + ".py") #### common functions def option (sOpt): "return True if option sOpt is active" return _dOptions.get(sOpt, False) def displayInfo (dDA, tWord): "for debugging: retrieve info of word" if not tWord: echo("> nothing to find") return True if tWord[1] not in _dAnalyses and not _storeMorphFromFSA(tWord[1]): echo("> not in FSA") return True if tWord[0] in dDA: echo("DA: " + str(dDA[tWord[0]])) echo("FSA: " + str(_dAnalyses[tWord[1]])) return True def _storeMorphFromFSA (sWord): "retrieves morphologies list from _oDict -> _dAnalyses" global _dAnalyses _dAnalyses[sWord] = _oDict.getMorph(sWord) return True if _dAnalyses[sWord] else False def morph (dDA, tWord, sPattern, bStrict=True, bNoWord=False): "analyse a tuple (position, word), return True if sPattern in morphologies (disambiguation on)" if not tWord: return bNoWord if tWord[1] not in _dAnalyses and not _storeMorphFromFSA(tWord[1]): return False lMorph = dDA[tWord[0]] if tWord[0] in dDA else _dAnalyses[tWord[1]] if not lMorph: return False p = re.compile(sPattern) if bStrict: return all(p.search(s) for s in lMorph) return any(p.search(s) for s in lMorph) def morphex (dDA, tWord, sPattern, sNegPattern, bNoWord=False): "analyse a tuple (position, word), returns True if not sNegPattern in word morphologies and sPattern in word morphologies (disambiguation on)" if not tWord: return bNoWord if tWord[1] not in _dAnalyses and not _storeMorphFromFSA(tWord[1]): return False lMorph = dDA[tWord[0]] if tWord[0] in dDA else _dAnalyses[tWord[1]] # check negative condition np = re.compile(sNegPattern) if any(np.search(s) for s in lMorph): return False # search sPattern p = re.compile(sPattern) return any(p.search(s) for s in lMorph) def analyse (sWord, sPattern, bStrict=True): "analyse a word, return True if sPattern in morphologies (disambiguation off)" if sWord not in _dAnalyses and not _storeMorphFromFSA(sWord): return False if not _dAnalyses[sWord]: return False p = re.compile(sPattern) if bStrict: return all(p.search(s) for s in _dAnalyses[sWord]) return any(p.search(s) for s in _dAnalyses[sWord]) def analysex (sWord, sPattern, sNegPattern): "analyse a word, returns True if not sNegPattern in word morphologies and sPattern in word morphologies (disambiguation off)" if sWord not in _dAnalyses and not _storeMorphFromFSA(sWord): return False # check negative condition np = re.compile(sNegPattern) if any(np.search(s) for s in _dAnalyses[sWord]): return False # search sPattern p = re.compile(sPattern) return any(p.search(s) for s in _dAnalyses[sWord]) def stem (sWord): "returns a list of sWord's stems" if not sWord: return [] if sWord not in _dAnalyses and not _storeMorphFromFSA(sWord): return [] return [ s[1:s.find(" ")] for s in _dAnalyses[sWord] ] ## functions to get text outside pattern scope # warning: check compile_rules.py to understand how it works def nextword (s, iStart, n): "get the nth word of the input string or empty string" m = re.match(u"( +[\\w%-]+){" + str(n-1) + u"} +([\\w%-]+)", s[iStart:]) if not m: return None return (iStart+m.start(2), m.group(2)) def prevword (s, iEnd, n): "get the (-)nth word of the input string or empty string" m = re.search(u"([\\w%-]+) +([\\w%-]+ +){" + str(n-1) + u"}$", s[:iEnd]) if not m: return None return (m.start(1), m.group(1)) def nextword1 (s, iStart): "get next word (optimization)" m = _zNextWord.match(s[iStart:]) if not m: return None return (iStart+m.start(1), m.group(1)) def prevword1 (s, iEnd): "get previous word (optimization)" m = _zPrevWord.search(s[:iEnd]) if not m: return None return (m.start(1), m.group(1)) def look (s, sPattern, sNegPattern=None): "seek sPattern in s (before/after/fulltext), if sNegPattern not in s" if sNegPattern and re.search(sNegPattern, s): return False if re.search(sPattern, s): return True return False def look_chk1 (dDA, s, nOffset, sPattern, sPatternGroup1, sNegPatternGroup1=None): "returns True if s has pattern sPattern and m.group(1) has pattern sPatternGroup1" m = re.search(sPattern, s) if not m: return False try: sWord = m.group(1) nPos = m.start(1) + nOffset except: #print("Missing group 1") return False if sNegPatternGroup1: return morphex(dDA, (nPos, sWord), sPatternGroup1, sNegPatternGroup1) return morph(dDA, (nPos, sWord), sPatternGroup1, False) #### Disambiguator def select (dDA, nPos, sWord, sPattern, lDefault=None): if not sWord: return True if nPos in dDA: return True if sWord not in _dAnalyses and not _storeMorphFromFSA(sWord): return True if len(_dAnalyses[sWord]) == 1: return True lSelect = [ sMorph for sMorph in _dAnalyses[sWord] if re.search(sPattern, sMorph) ] if lSelect: if len(lSelect) != len(_dAnalyses[sWord]): dDA[nPos] = lSelect #echo("= "+sWord+" "+str(dDA.get(nPos, "null"))) elif lDefault: dDA[nPos] = lDefault #echo("= "+sWord+" "+str(dDA.get(nPos, "null"))) return True def exclude (dDA, nPos, sWord, sPattern, lDefault=None): if not sWord: return True if nPos in dDA: return True if sWord not in _dAnalyses and not _storeMorphFromFSA(sWord): return True if len(_dAnalyses[sWord]) == 1: return True lSelect = [ sMorph for sMorph in _dAnalyses[sWord] if not re.search(sPattern, sMorph) ] if lSelect: if len(lSelect) != len(_dAnalyses[sWord]): dDA[nPos] = lSelect #echo("= "+sWord+" "+str(dDA.get(nPos, "null"))) elif lDefault: dDA[nPos] = lDefault #echo("= "+sWord+" "+str(dDA.get(nPos, "null"))) return True def define (dDA, nPos, lMorph): dDA[nPos] = lMorph #echo("= "+str(nPos)+" "+str(dDA[nPos])) return True #### GRAMMAR CHECKER PLUGINS ${plugins} ${generated}
SamuelLongchamps/grammalecte
gc_core/py/gc_engine.py
Python
gpl-3.0
17,150
/* «Camelion» - Perl storable/C struct back-and-forth translator * * Copyright (C) Alexey Shishkin 2016 * * This file is part of Project «Camelion». * * Project «Camelion» 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. * * Project «Camelion» 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 Project «Camelion». If not, see <http://www.gnu.org/licenses/>. */ #include "../serials/sread.h" CML_Error CML_SerialsReadINT8(CML_Bytes * bytes, uint32_t * bpos, int8_t * result) { if (*bpos + sizeof(int8_t) > bytes->size) return CML_ERROR_USER_BADDATA; *result = bytes->data[*bpos]; *bpos += 1; /* Need to reverse signed char */ /* It's a perl thing */ *result ^= 1 << 7; return CML_ERROR_SUCCESS; } CML_Error CML_SerialsReadUINT8(CML_Bytes * bytes, uint32_t * bpos, uint8_t * result) { if (*bpos + sizeof(uint8_t) > bytes->size) return CML_ERROR_USER_BADDATA; *result = bytes->data[*bpos]; *bpos += 1; return CML_ERROR_SUCCESS; } CML_Error CML_SerialsReadINT32(CML_Bytes * bytes, uint32_t * bpos, int32_t * result) { if (*bpos + sizeof(int32_t) > bytes->size) return CML_ERROR_USER_BADDATA; union { int32_t res; uint8_t bytes[sizeof(int32_t)]; } conv; uint32_t i; for (i = 0; i < sizeof(int32_t); i++, *bpos += 1) conv.bytes[3 - i] = bytes->data[*bpos]; *result = conv.res; return CML_ERROR_SUCCESS; } CML_Error CML_SerialsReadUINT32(CML_Bytes * bytes, uint32_t * bpos, uint32_t * result) { if (*bpos + sizeof(uint32_t) > bytes->size) return CML_ERROR_USER_BADDATA; union { uint32_t res; uint8_t bytes[sizeof(uint32_t)]; } conv; uint32_t i; for (i = 0; i < sizeof(uint32_t); i++, *bpos += 1) conv.bytes[3 - i] = bytes->data[*bpos]; *result = conv.res; return CML_ERROR_SUCCESS; } CML_Error CML_SerialsReadDATA(CML_Bytes * bytes, uint32_t * bpos, uint8_t * result, uint32_t length) { if (*bpos + length > bytes->size) return CML_ERROR_USER_BADDATA; uint32_t i; for (i = 0; i < length; i++, *bpos += 1) result[i] = bytes->data[*bpos]; result[i] = '\0'; return CML_ERROR_SUCCESS; }
kimiby/camelion
serials/sread.c
C
gpl-3.0
2,718
package com.entrepidea.jvm; import java.util.ArrayList; import java.util.List; /** * @Desc: * @Source: 深入理解Java虚拟机:JVM高级特性与最佳实践(第2版) * Created by jonat on 10/18/2019. * TODO need revisit - the code seem just running - supposedly it should end soon with exceptions. */ public class RuntimeConstantPoolOOM { public static void main(String[] args){ List<String> l = new ArrayList<>(); int i=0; while(true){ l.add(String.valueOf(i++).intern()); } } }
entrepidea/projects
java/java.core/src/main/java/com/entrepidea/jvm/RuntimeConstantPoolOOM.java
Java
gpl-3.0
551
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using LobbyClient; using PlasmaShared; using ZkData; namespace ZeroKWeb.SpringieInterface { public class StartSetup { static bool listOnlyThatLevelsModules = false; // may cause bugs /// <summary> /// Sets up all the things that Springie needs to know for the battle: how to balance, who to get extra commanders, what PlanetWars structures to create, etc. /// </summary> public static SpringBattleStartSetup GetSpringBattleStartSetup(BattleContext context) { try { AutohostMode mode = context.GetMode(); var ret = new SpringBattleStartSetup(); if (mode == AutohostMode.Planetwars) { ret.BalanceTeamsResult = Balancer.BalanceTeams(context, true,null, null); context.Players = ret.BalanceTeamsResult.Players; } var commanderTypes = new LuaTable(); var db = new ZkDataContext(); // calculate to whom to send extra comms var accountIDsWithExtraComms = new List<int>(); if (mode == AutohostMode.Planetwars || mode == AutohostMode.Generic || mode == AutohostMode.GameFFA || mode == AutohostMode.Teams) { IOrderedEnumerable<IGrouping<int, PlayerTeam>> groupedByTeam = context.Players.Where(x => !x.IsSpectator).GroupBy(x => x.AllyID).OrderByDescending(x => x.Count()); IGrouping<int, PlayerTeam> biggest = groupedByTeam.FirstOrDefault(); if (biggest != null) { foreach (var other in groupedByTeam.Skip(1)) { int cnt = biggest.Count() - other.Count(); if (cnt > 0) { foreach (Account a in other.Select(x => db.Accounts.First(y => y.AccountID == x.LobbyID)).OrderByDescending(x => x.Elo*x.EloWeight).Take( cnt)) accountIDsWithExtraComms.Add(a.AccountID); } } } } bool is1v1 = context.Players.Where(x => !x.IsSpectator).ToList().Count == 2 && context.Bots.Count == 0; // write Planetwars details to modoptions (for widget) Faction attacker = null; Faction defender = null; Planet planet = null; if (mode == AutohostMode.Planetwars) { planet = db.Galaxies.First(x => x.IsDefault).Planets.First(x => x.Resource.InternalName == context.Map); attacker = context.Players.Where(x => x.AllyID == 0 && !x.IsSpectator) .Select(x => db.Accounts.First(y => y.AccountID == x.LobbyID)) .Where(x => x.Faction != null) .Select(x => x.Faction) .First(); defender = planet.Faction; if (attacker == defender) defender = null; ret.ModOptions.Add(new SpringBattleStartSetup.ScriptKeyValuePair { Key = "attackingFaction", Value = attacker.Shortcut }); if (defender != null) ret.ModOptions.Add(new SpringBattleStartSetup.ScriptKeyValuePair { Key = "defendingFaction", Value = defender.Shortcut }); ret.ModOptions.Add(new SpringBattleStartSetup.ScriptKeyValuePair { Key = "planet", Value = planet.Name }); } // write player custom keys (level, elo, is muted, etc.) foreach (PlayerTeam p in context.Players) { Account user = db.Accounts.Find(p.LobbyID); if (user != null) { var userParams = new List<SpringBattleStartSetup.ScriptKeyValuePair>(); ret.UserParameters.Add(new SpringBattleStartSetup.UserCustomParameters { LobbyID = p.LobbyID, Parameters = userParams }); bool userBanMuted = user.PunishmentsByAccountID.Any(x => !x.IsExpired && x.BanMute); if (userBanMuted) userParams.Add(new SpringBattleStartSetup.ScriptKeyValuePair { Key = "muted", Value = "1" }); userParams.Add(new SpringBattleStartSetup.ScriptKeyValuePair { Key = "faction", Value = user.Faction != null ? user.Faction.Shortcut : "" }); userParams.Add(new SpringBattleStartSetup.ScriptKeyValuePair { Key = "clan", Value = user.Clan != null ? user.Clan.Shortcut : "" }); userParams.Add(new SpringBattleStartSetup.ScriptKeyValuePair { Key = "level", Value = user.Level.ToString() }); double elo = mode == AutohostMode.Planetwars ? user.EffectivePwElo : (is1v1 ? user.Effective1v1Elo : user.EffectiveElo); userParams.Add(new SpringBattleStartSetup.ScriptKeyValuePair { Key = "elo", Value = Math.Round(elo).ToString() }); // elo for ingame is just ordering for auto /take userParams.Add(new SpringBattleStartSetup.ScriptKeyValuePair { Key = "avatar", Value = user.Avatar }); userParams.Add(new SpringBattleStartSetup.ScriptKeyValuePair { Key = "admin", Value = (user.IsZeroKAdmin ? "1" : "0") }); if (!p.IsSpectator) { // set valid PW structure attackers if (mode == AutohostMode.Planetwars) { bool allied = user.Faction != null && defender != null && user.Faction != defender && defender.HasTreatyRight(user.Faction, x => x.EffectPreventIngamePwStructureDestruction == true, planet); if (!allied && user.Faction != null && (user.Faction == attacker || user.Faction == defender)) { userParams.Add(new SpringBattleStartSetup.ScriptKeyValuePair { Key = "canAttackPwStructures", Value = "1" }); } } var pu = new LuaTable(); bool userUnlocksBanned = user.PunishmentsByAccountID.Any(x => !x.IsExpired && x.BanUnlocks); bool userCommandersBanned = user.PunishmentsByAccountID.Any(x => !x.IsExpired && x.BanCommanders); if (!userUnlocksBanned) { if (mode != AutohostMode.Planetwars || user.Faction == null) foreach (Unlock unlock in user.AccountUnlocks.Select(x => x.Unlock)) pu.Add(unlock.Code); else { foreach (Unlock unlock in user.AccountUnlocks.Select(x => x.Unlock).Union(user.Faction.GetFactionUnlocks().Select(x => x.Unlock)).Where(x => x.UnlockType == UnlockTypes.Unit)) pu.Add(unlock.Code); } } userParams.Add(new SpringBattleStartSetup.ScriptKeyValuePair { Key = "unlocks", Value = pu.ToBase64String() }); if (accountIDsWithExtraComms.Contains(user.AccountID)) userParams.Add(new SpringBattleStartSetup.ScriptKeyValuePair { Key = "extracomm", Value = "1" }); var pc = new LuaTable(); if (!userCommandersBanned) { // set up commander data foreach (Commander c in user.Commanders.Where(x => x.Unlock != null && x.ProfileNumber <= GlobalConst.CommanderProfileCount)) { try { if (string.IsNullOrEmpty(c.Name) || c.Name.Any(x => x == '"') ) { c.Name = c.CommanderID.ToString(); } LuaTable morphTable = new LuaTable(); pc["[\"" + c.Name + "\"]"] = morphTable; // process decoration icons LuaTable decorations = new LuaTable(); foreach (Unlock d in c.CommanderDecorations.Where(x => x.Unlock != null).OrderBy( x => x.SlotID).Select(x => x.Unlock)) { CommanderDecorationIcon iconData = db.CommanderDecorationIcons.FirstOrDefault(x => x.DecorationUnlockID == d.UnlockID); if (iconData != null) { string iconName = null, iconPosition = null; // FIXME: handle avatars and preset/custom icons if (iconData.IconType == (int)DecorationIconTypes.Faction) { iconName = user.Faction != null ? user.Faction.Shortcut : null; } else if (iconData.IconType == (int)DecorationIconTypes.Clan) { iconName = user.Clan != null ? user.Clan.Shortcut : null; } if (iconName != null) { iconPosition = CommanderDecoration.GetIconPosition(d); LuaTable entry = new LuaTable(); entry.Add("image", iconName); decorations.Add("icon_" + iconPosition.ToLower(), entry); } } else decorations.Add(d.Code); } string prevKey = null; for (int i = 0; i <= GlobalConst.NumCommanderLevels; i++) { string key = string.Format("c{0}_{1}_{2}", user.AccountID, c.ProfileNumber, i); morphTable.Add(key); // TODO: maybe don't specify morph series in player data, only starting unit var comdef = new LuaTable(); commanderTypes[key] = comdef; comdef["chassis"] = c.Unlock.Code + i; var modules = new LuaTable(); comdef["modules"] = modules; comdef["decorations"] = decorations; comdef["name"] = c.Name.Substring(0, Math.Min(25, c.Name.Length)) + " level " + i; //if (i < GlobalConst.NumCommanderLevels) //{ // comdef["next"] = string.Format("c{0}_{1}_{2}", user.AccountID, c.ProfileNumber, i+1); //} //comdef["owner"] = user.Name; if (i > 0) { comdef["cost"] = c.GetTotalMorphLevelCost(i); if (listOnlyThatLevelsModules) { if (prevKey != null) comdef["prev"] = prevKey; prevKey = key; foreach (Unlock m in c.CommanderModules.Where(x => x.CommanderSlot.MorphLevel == i && x.Unlock != null).OrderBy( x => x.Unlock.UnlockType).ThenBy(x => x.SlotID).Select(x => x.Unlock)) modules.Add(m.Code); } else { foreach (Unlock m in c.CommanderModules.Where(x => x.CommanderSlot.MorphLevel <= i && x.Unlock != null).OrderBy( x => x.Unlock.UnlockType).ThenBy(x => x.SlotID).Select(x => x.Unlock)) modules.Add(m.Code); } } } } catch (Exception ex) { Trace.TraceError(ex.ToString()); throw new ApplicationException( string.Format("Error processing commander: {0} - {1} of player {2} - {3}", c.CommanderID, c.Name, user.AccountID, user.Name), ex); } } } else userParams.Add(new SpringBattleStartSetup.ScriptKeyValuePair { Key = "jokecomm", Value = "1" }); userParams.Add(new SpringBattleStartSetup.ScriptKeyValuePair { Key = "commanders", Value = pc.ToBase64String() }); } } } ret.ModOptions.Add(new SpringBattleStartSetup.ScriptKeyValuePair { Key = "commanderTypes", Value = commanderTypes.ToBase64String() }); // set PW structures if (mode == AutohostMode.Planetwars) { string owner = planet.Faction != null ? planet.Faction.Shortcut : ""; var pwStructures = new LuaTable(); foreach (PlanetStructure s in planet.PlanetStructures.Where(x => x.StructureType!= null && !string.IsNullOrEmpty(x.StructureType.IngameUnitName))) { pwStructures.Add("s" + s.StructureTypeID, new LuaTable { { "unitname", s.StructureType.IngameUnitName }, //{ "isDestroyed", s.IsDestroyed ? true : false }, { "name", string.Format("{0} {1} ({2})", owner, s.StructureType.Name, s.Account!= null ? s.Account.Name:"unowned") }, { "description", s.StructureType.Description } }); } ret.ModOptions.Add(new SpringBattleStartSetup.ScriptKeyValuePair { Key = "planetwarsStructures", Value = pwStructures.ToBase64String() }); } return ret; } catch (Exception ex) { Trace.TraceError(ex.ToString()); throw; } } } }
TurBoss/Zero-K-Infrastructure
Zero-K.info/SpringieInterface/StartSetup.cs
C#
gpl-3.0
16,808
# wp_project Project for Web Programming exam Cartelle: spec: contiene il file delle specifiche e tutto ciò che è inerente alla progettazione dell'elaborato doc: contiene tutti i file della documentazione prodotta src: contiene i file sorgenti del progetto Students: Luca Bettinelli, Michele Masciale e Matteo Mario
Luke092/wp_project
README.md
Markdown
gpl-3.0
328
package com.kimkha.finanvita.ui; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.support.v4.app.LoaderManager; import android.support.v4.content.Loader; import android.util.SparseBooleanArray; import android.view.*; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.ListView; import com.kimkha.finanvita.R; import com.kimkha.finanvita.adapters.AbstractCursorAdapter; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; public abstract class ItemListFragment extends BaseFragment implements AdapterView.OnItemClickListener, LoaderManager.LoaderCallbacks<Cursor> { public static final String RESULT_EXTRA_ITEM_ID = ItemListFragment.class.getName() + ".RESULT_EXTRA_ITEM_ID"; public static final String RESULT_EXTRA_ITEM_IDS = ItemListFragment.class.getName() + ".RESULT_EXTRA_ITEM_IDS"; // ----------------------------------------------------------------------------------------------------------------- public static final int SELECTION_TYPE_NONE = 0; public static final int SELECTION_TYPE_SINGLE = 1; public static final int SELECTION_TYPE_MULTI = 2; // ----------------------------------------------------------------------------------------------------------------- protected static final String ARG_SELECTION_TYPE = "ARG_SELECTION_TYPE"; protected static final String ARG_ITEM_IDS = "ARG_ITEM_IDS"; protected static final String ARG_IS_OPEN_DRAWER_LAYOUT = "ARG_IS_OPEN_DRAWER_LAYOUT"; // ----------------------------------------------------------------------------------------------------------------- protected static final String STATE_SELECTED_POSITIONS = "STATE_SELECTED_POSITIONS"; // ----------------------------------------------------------------------------------------------------------------- protected static final int LOADER_ITEMS = 1468; // ----------------------------------------------------------------------------------------------------------------- protected ListView list_V; protected View create_V; // ----------------------------------------------------------------------------------------------------------------- protected AbstractCursorAdapter adapter; protected int selectionType; public static Bundle makeArgs(int selectionType, long[] itemIDs) { return makeArgs(selectionType, itemIDs, false); } public static Bundle makeArgs(int selectionType, long[] itemIDs, boolean isOpenDrawerLayout) { final Bundle args = new Bundle(); args.putInt(ARG_SELECTION_TYPE, selectionType); args.putLongArray(ARG_ITEM_IDS, itemIDs); args.putBoolean(ARG_IS_OPEN_DRAWER_LAYOUT, isOpenDrawerLayout); return args; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); // Get arguments final Bundle args = getArguments(); selectionType = args != null ? args.getInt(ARG_SELECTION_TYPE, SELECTION_TYPE_NONE) : SELECTION_TYPE_NONE; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_items_list, container, false); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); // Get views list_V = (ListView) view.findViewById(R.id.list_V); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // Setup if (selectionType == SELECTION_TYPE_NONE) { create_V = LayoutInflater.from(getActivity()).inflate(R.layout.li_create_new, list_V, false); list_V.addFooterView(create_V); } adapter = createAdapter(getActivity()); list_V.setAdapter(adapter); list_V.setOnItemClickListener(this); if (getArguments().getBoolean(ARG_IS_OPEN_DRAWER_LAYOUT, false)) { final int paddingHorizontal = getResources().getDimensionPixelSize(R.dimen.dynamic_margin_drawer_narrow_horizontal); list_V.setPadding(paddingHorizontal, list_V.getPaddingTop(), paddingHorizontal, list_V.getPaddingBottom()); } if (selectionType == SELECTION_TYPE_MULTI) { list_V.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE); if (savedInstanceState != null) { final ArrayList<Integer> selectedPositions = savedInstanceState.getIntegerArrayList(STATE_SELECTED_POSITIONS); list_V.setTag(selectedPositions); } else { final long[] selectedIDs = getArguments().getLongArray(ARG_ITEM_IDS); list_V.setTag(selectedIDs); } } // Loader getLoaderManager().initLoader(LOADER_ITEMS, null, this); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (selectionType == SELECTION_TYPE_MULTI) { final ArrayList<Integer> selectedPositions = new ArrayList<Integer>(); final SparseBooleanArray listPositions = list_V.getCheckedItemPositions(); if (listPositions != null) { for (int i = 0; i < listPositions.size(); i++) { if (listPositions.get(listPositions.keyAt(i))) selectedPositions.add(listPositions.keyAt(i)); } } outState.putIntegerArrayList(STATE_SELECTED_POSITIONS, selectedPositions); } } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.items_list, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_create: startItemCreate(getActivity(), item.getActionView()); return true; } return super.onOptionsItemSelected(item); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle bundle) { switch (id) { case LOADER_ITEMS: return createItemsLoader(); } return null; } @Override public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) { switch (cursorLoader.getId()) { case LOADER_ITEMS: bindItems(cursor); break; } } @Override public void onLoaderReset(Loader<Cursor> cursorLoader) { switch (cursorLoader.getId()) { case LOADER_ITEMS: bindItems(null); break; } } @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) { switch (selectionType) { case SELECTION_TYPE_NONE: if (position == adapter.getCount()) startItemCreate(getActivity(), view); else startItemDetails(getActivity(), id, position, adapter, adapter.getCursor(), view); break; case SELECTION_TYPE_SINGLE: // Prepare extras final Bundle extras = new Bundle(); onItemSelected(id, adapter, adapter.getCursor(), extras); Intent data = new Intent(); data.putExtra(RESULT_EXTRA_ITEM_ID, id); data.putExtras(extras); getActivity().setResult(Activity.RESULT_OK, data); getActivity().finish(); break; case SELECTION_TYPE_MULTI: adapter.setSelectedIDs(list_V.getCheckedItemIds()); break; } } protected abstract AbstractCursorAdapter createAdapter(Context context); protected abstract Loader<Cursor> createItemsLoader(); /** * Called when item id along with extras should be returned to another activity. If only item id is necessary, you don't need to do anything. Just extra values should be put in outExtras. * * @param itemId Id of selected item. You don't need to put it to extras. This will be done automatically. * @param adapter Adapter for convenience. * @param c Cursor. * @param outExtras Put all additional data in here. */ protected abstract void onItemSelected(long itemId, AbstractCursorAdapter adapter, Cursor c, Bundle outExtras); /** * Called when you should start item detail activity * * @param context Context. * @param itemId Id of selected item. * @param position Selected position. * @param adapter Adapter for convenience. * @param c Cursor. * @param view */ protected abstract void startItemDetails(Context context, long itemId, int position, AbstractCursorAdapter adapter, Cursor c, View view); /** * Start item create activity here. */ protected abstract void startItemCreate(Context context, View view); public long[] getSelectedItemIDs() { return list_V.getCheckedItemIds(); } protected void bindItems(Cursor c) { boolean needUpdateSelectedIDs = adapter.getCount() == 0 && selectionType == SELECTION_TYPE_MULTI; adapter.swapCursor(c); if (needUpdateSelectedIDs && list_V.getTag() != null) { final Object tag = list_V.getTag(); if (tag instanceof ArrayList) { //noinspection unchecked final ArrayList<Integer> selectedPositions = (ArrayList<Integer>) tag; list_V.setTag(selectedPositions); //noinspection ForLoopReplaceableByForEach for (int i = 0; i < selectedPositions.size(); i++) list_V.setItemChecked(selectedPositions.get(i), true); } else if (tag instanceof long[]) { final long[] selectedIDs = (long[]) tag; final Set<Long> selectedIDsSet = new HashSet<Long>(); //noinspection ForLoopReplaceableByForEach for (int i = 0; i < selectedIDs.length; i++) selectedIDsSet.add(selectedIDs[i]); long itemId; for (int i = 0; i < adapter.getCount(); i++) { itemId = list_V.getItemIdAtPosition(i); if (selectedIDsSet.contains(itemId)) { selectedIDsSet.remove(itemId); list_V.setItemChecked(i, true); if (selectedIDsSet.size() == 0) break; } } } adapter.setSelectedIDs(list_V.getCheckedItemIds()); } } }
kimkha/Finanvita
Finanvita/src/main/java/com/kimkha/finanvita/ui/ItemListFragment.java
Java
gpl-3.0
11,290
#ifndef __LINUX_VIDEODEV_H #define __LINUX_VIDEODEV_H /* Linux V4L API, Version 1 * videodev.h from v4l driver in Linux 2.2.3 * * Used here with the explicit permission of the original author, Alan Cox. * <[email protected]> */ /* $XFree86: xc/programs/Xserver/hw/xfree86/drivers/v4l/videodev.h,v 1.8 2001/03/03 22:46:31 tsi Exp $ */ #include "Xmd.h" #define VID_TYPE_CAPTURE 1 /* Can capture */ #define VID_TYPE_TUNER 2 /* Can tune */ #define VID_TYPE_TELETEXT 4 /* Does teletext */ #define VID_TYPE_OVERLAY 8 /* Overlay onto frame buffer */ #define VID_TYPE_CHROMAKEY 16 /* Overlay by chromakey */ #define VID_TYPE_CLIPPING 32 /* Can clip */ #define VID_TYPE_FRAMERAM 64 /* Uses the frame buffer memory */ #define VID_TYPE_SCALES 128 /* Scalable */ #define VID_TYPE_MONOCHROME 256 /* Monochrome only */ #define VID_TYPE_SUBCAPTURE 512 /* Can capture subareas of the image */ struct video_capability { char name[32]; int type; int channels; /* Num channels */ int audios; /* Num audio devices */ int maxwidth; /* Supported width */ int maxheight; /* And height */ int minwidth; /* Supported width */ int minheight; /* And height */ }; struct video_channel { int channel; char name[32]; int tuners; CARD32 flags; #define VIDEO_VC_TUNER 1 /* Channel has a tuner */ #define VIDEO_VC_AUDIO 2 /* Channel has audio */ CARD16 type; #define VIDEO_TYPE_TV 1 #define VIDEO_TYPE_CAMERA 2 CARD16 norm; /* Norm set by channel */ }; struct video_tuner { int tuner; char name[32]; unsigned long rangelow, rangehigh; /* Tuner range */ CARD32 flags; #define VIDEO_TUNER_PAL 1 #define VIDEO_TUNER_NTSC 2 #define VIDEO_TUNER_SECAM 4 #define VIDEO_TUNER_LOW 8 /* Uses KHz not MHz */ #define VIDEO_TUNER_NORM 16 /* Tuner can set norm */ #define VIDEO_TUNER_STEREO_ON 128 /* Tuner is seeing stereo */ CARD16 mode; /* PAL/NTSC/SECAM/OTHER */ #define VIDEO_MODE_PAL 0 #define VIDEO_MODE_NTSC 1 #define VIDEO_MODE_SECAM 2 #define VIDEO_MODE_AUTO 3 CARD16 signal; /* Signal strength 16bit scale */ }; struct video_picture { CARD16 brightness; CARD16 hue; CARD16 colour; CARD16 contrast; CARD16 whiteness; /* Black and white only */ CARD16 depth; /* Capture depth */ CARD16 palette; /* Palette in use */ #define VIDEO_PALETTE_GREY 1 /* Linear greyscale */ #define VIDEO_PALETTE_HI240 2 /* High 240 cube (BT848) */ #define VIDEO_PALETTE_RGB565 3 /* 565 16 bit RGB */ #define VIDEO_PALETTE_RGB24 4 /* 24bit RGB */ #define VIDEO_PALETTE_RGB32 5 /* 32bit RGB */ #define VIDEO_PALETTE_RGB555 6 /* 555 15bit RGB */ #define VIDEO_PALETTE_YUV422 7 /* YUV422 capture */ #define VIDEO_PALETTE_YUYV 8 #define VIDEO_PALETTE_UYVY 9 /* The great thing about standards is ... */ #define VIDEO_PALETTE_YUV420 10 #define VIDEO_PALETTE_YUV411 11 /* YUV411 capture */ #define VIDEO_PALETTE_RAW 12 /* RAW capture (BT848) */ #define VIDEO_PALETTE_YUV422P 13 /* YUV 4:2:2 Planar */ #define VIDEO_PALETTE_YUV411P 14 /* YUV 4:1:1 Planar */ #define VIDEO_PALETTE_YUV420P 15 /* YUV 4:2:0 Planar */ #define VIDEO_PALETTE_YUV410P 16 /* YUV 4:1:0 Planar */ #define VIDEO_PALETTE_PLANAR 13 /* start of planar entries */ #define VIDEO_PALETTE_COMPONENT 7 /* start of component entries */ }; struct video_audio { int audio; /* Audio channel */ CARD16 volume; /* If settable */ CARD16 bass, treble; CARD32 flags; #define VIDEO_AUDIO_MUTE 1 #define VIDEO_AUDIO_MUTABLE 2 #define VIDEO_AUDIO_VOLUME 4 #define VIDEO_AUDIO_BASS 8 #define VIDEO_AUDIO_TREBLE 16 char name[16]; #define VIDEO_SOUND_MONO 1 #define VIDEO_SOUND_STEREO 2 #define VIDEO_SOUND_LANG1 4 #define VIDEO_SOUND_LANG2 8 CARD16 mode; CARD16 balance; /* Stereo balance */ CARD16 step; /* Step actual volume uses */ }; struct video_clip { INT32 x,y; INT32 width, height; struct video_clip *next; /* For user use/driver use only */ }; struct video_window { CARD32 x,y; /* Position of window */ CARD32 width,height; /* Its size */ CARD32 chromakey; CARD32 flags; struct video_clip *clips; /* Set only */ int clipcount; #define VIDEO_WINDOW_INTERLACE 1 #define VIDEO_CLIP_BITMAP -1 /* bitmap is 1024x625, a '1' bit represents a clipped pixel */ #define VIDEO_CLIPMAP_SIZE (128 * 625) }; struct video_capture { CARD32 x,y; /* Offsets into image */ CARD32 width, height; /* Area to capture */ CARD16 decimation; /* Decimation divder */ CARD16 flags; /* Flags for capture */ #define VIDEO_CAPTURE_ODD 0 /* Temporal */ #define VIDEO_CAPTURE_EVEN 1 }; struct video_buffer { void *base; int height,width; int depth; int bytesperline; }; struct video_mmap { unsigned int frame; /* Frame (0 - n) for double buffer */ int height,width; unsigned int format; /* should be VIDEO_PALETTE_* */ }; struct video_key { CARD8 key[8]; CARD32 flags; }; #define VIDEO_MAX_FRAME 32 struct video_mbuf { int size; /* Total memory to map */ int frames; /* Frames */ int offsets[VIDEO_MAX_FRAME]; }; #define VIDEO_NO_UNIT (-1) struct video_unit { int video; /* Video minor */ int vbi; /* VBI minor */ int radio; /* Radio minor */ int audio; /* Audio minor */ int teletext; /* Teletext minor */ }; #define VIDIOCGCAP _IOR('v',1,struct video_capability) /* Get capabilities */ #define VIDIOCGCHAN _IOWR('v',2,struct video_channel) /* Get channel info (sources) */ #define VIDIOCSCHAN _IOW('v',3,struct video_channel) /* Set channel */ #define VIDIOCGTUNER _IOWR('v',4,struct video_tuner) /* Get tuner abilities */ #define VIDIOCSTUNER _IOW('v',5,struct video_tuner) /* Tune the tuner for the current channel */ #define VIDIOCGPICT _IOR('v',6,struct video_picture) /* Get picture properties */ #define VIDIOCSPICT _IOW('v',7,struct video_picture) /* Set picture properties */ #define VIDIOCCAPTURE _IOW('v',8,int) /* Start, end capture */ #define VIDIOCGWIN _IOR('v',9, struct video_window) /* Set the video overlay window */ #define VIDIOCSWIN _IOW('v',10, struct video_window) /* Set the video overlay window - passes clip list for hardware smarts , chromakey etc */ #define VIDIOCGFBUF _IOR('v',11, struct video_buffer) /* Get frame buffer */ #define VIDIOCSFBUF _IOW('v',12, struct video_buffer) /* Set frame buffer - root only */ #define VIDIOCKEY _IOR('v',13, struct video_key) /* Video key event - to dev 255 is to all - cuts capture on all DMA windows with this key (0xFFFFFFFF == all) */ #define VIDIOCGFREQ _IOR('v',14, unsigned long) /* Set tuner */ #define VIDIOCSFREQ _IOW('v',15, unsigned long) /* Set tuner */ #define VIDIOCGAUDIO _IOR('v',16, struct video_audio) /* Get audio info */ #define VIDIOCSAUDIO _IOW('v',17, struct video_audio) /* Audio source, mute etc */ #define VIDIOCSYNC _IOW('v',18, int) /* Sync with mmap grabbing */ #define VIDIOCMCAPTURE _IOW('v',19, struct video_mmap) /* Grab frames */ #define VIDIOCGMBUF _IOR('v', 20, struct video_mbuf) /* Memory map buffer info */ #define VIDIOCGUNIT _IOR('v', 21, struct video_unit) /* Get attached units */ #define VIDIOCGCAPTURE _IOR('v',22, struct video_capture) /* Get frame buffer */ #define VIDIOCSCAPTURE _IOW('v',23, struct video_capture) /* Set frame buffer - root only */ #define BASE_VIDIOCPRIVATE 192 /* 192-255 are private */ #define VID_HARDWARE_BT848 1 #define VID_HARDWARE_QCAM_BW 2 #define VID_HARDWARE_PMS 3 #define VID_HARDWARE_QCAM_C 4 #define VID_HARDWARE_PSEUDO 5 #define VID_HARDWARE_SAA5249 6 #define VID_HARDWARE_AZTECH 7 #define VID_HARDWARE_SF16MI 8 #define VID_HARDWARE_RTRACK 9 #define VID_HARDWARE_ZOLTRIX 10 #define VID_HARDWARE_SAA7146 11 #define VID_HARDWARE_VIDEUM 12 /* Reserved for Winnov videum */ #define VID_HARDWARE_RTRACK2 13 #define VID_HARDWARE_PERMEDIA2 14 /* Reserved for Permedia2 */ #define VID_HARDWARE_RIVA128 15 /* Reserved for RIVA 128 */ #define VID_HARDWARE_PLANB 16 /* PowerMac motherboard video-in */ #define VID_HARDWARE_BROADWAY 17 /* Broadway project */ #define VID_HARDWARE_GEMTEK 18 #define VID_HARDWARE_TYPHOON 19 #define VID_HARDWARE_VINO 20 /* Reserved for SGI Indy Vino */ /* * Initialiser list */ struct video_init { char *name; int (*init)(struct video_init *); }; #endif
chriskmanx/qmole
QMOLEDEV/vnc-4_1_3-unixsrc/unix/xc/programs/Xserver/hw/xfree86/drivers/v4l/videodev.h
C
gpl-3.0
8,115
// XDwgDirectReader.cpp: implementation of the XDwgDirectReader class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include "atlbase.h" #include "XDwgDirectReader.h" #include "db.h" #include "DwgEntityDumper.h" #include "ExSystemServices.h" #include "ExHostAppServices.h" #include "RxDynamicModule.h" ////////////////////////////////////////////////////////////////////////// /////////////DwgReaderServices////////////////////////////////////////////// class DwgReaderServices : public ExSystemServices, public ExHostAppServices { protected: ODRX_USING_HEAP_OPERATORS(ExSystemServices); }; OdRxObjectImpl<DwgReaderServices> svcs; ExProtocolExtension theProtocolExtensions; const CString g_szEntityType = "ENTITY_TYPE"; //gisÊý¾Ý¸ñÍø´óС const double DEFAULT_GIS_GRID_SIZE = 120.0; ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// XDWGReader::XDWGReader() { //³õʼ»¯DwgDirect¿â odInitialize(&svcs); theProtocolExtensions.initialize(); //ĬÈ϶ÁÈ¡CAD²ÎÊýÉèÖà m_IsReadPolygon = FALSE; m_IsLine2Polygon = FALSE; m_IsBreakBlock = FALSE; m_IsReadInvisible = FALSE; m_IsJoinXDataAttrs = FALSE; m_IsReadBlockPoint = TRUE; m_IsCreateAnnotation = TRUE; m_iUnbreakBlockMode = 0; m_pSpRef = NULL; m_dAnnoScale = 1; m_bConvertAngle = TRUE; m_pProgressBar = NULL; m_pLogRec = NULL; InitAOPointers(); m_Regapps.RemoveAll(); m_unExplodeBlocks.RemoveAll(); m_bFinishedCreateFtCls = FALSE; m_StepNum = 5000; } XDWGReader::~XDWGReader() { m_unExplodeBlocks.RemoveAll(); theProtocolExtensions.uninitialize(); odUninitialize(); if (m_pLogRec != NULL) { delete m_pLogRec; } } ////////////////////////////////////////////////////////////////////////// //¼òÒªÃèÊö : ɾ³ýÒÑ´æÔÚµÄÒªËØÀà //ÊäÈë²ÎÊý : //·µ »Ø Öµ : //ÐÞ¸ÄÈÕÖ¾ : ////////////////////////////////////////////////////////////////////////// void XDWGReader::CheckDeleteFtCls(IFeatureWorkspace* pFtWS, CString sFtClsName) { if (pFtWS == NULL) return; IFeatureClass* pFtCls = NULL; pFtWS->OpenFeatureClass(CComBSTR(sFtClsName), &pFtCls); if (pFtCls != NULL) { IDatasetPtr pDs = pFtCls; if (pDs != NULL) { pDs->Delete(); } } } /******************************************************************** ¼òÒªÃèÊö : ÅúÁ¿¶ÁȡǰµÄ×¼±¸¹¤×÷ ÊäÈë²ÎÊý : ·µ »Ø Öµ : ÐÞ¸ÄÈÕÖ¾ : *********************************************************************/ BOOL XDWGReader::PrepareReadDwg(IWorkspace* pTargetWS, IDataset* pTargetDataset, ISpatialReference* pSpRef) { try { m_pTargetWS = pTargetWS; //³õʼ»¯Ö¸Õë //InitAOPointers(); //ÎÞ·¨¶ÁÈ¡µÄʵÌå¸öÊý m_lUnReadEntityNum = 0; ////////////////////////////////////////////////////////////////////////// IFeatureDatasetPtr pFeatDataset(pTargetDataset); if (pSpRef == NULL) { ISpatialReferencePtr pUnknownSpRef(CLSID_UnknownCoordinateSystem); m_pSpRef = pUnknownSpRef.Detach(); m_pSpRef->SetDomain(0.0, 1000000000, 0.0, 1000000000); } else { m_pSpRef = pSpRef; } ////////////////////////////////////////////////////////////////////////// //ÉèÖÃΪ¸ß¾«¶È£¬·ñÔòÎÞ·¨´´½¨±í»òFEATURECLASS IControlPrecision2Ptr pControlPrecision(m_pSpRef); if (pControlPrecision != NULL) { pControlPrecision->put_IsHighPrecision(VARIANT_TRUE); } //ÉèÖÿռä²Î¿¼¾«¶ÈÖµ ISpatialReferenceResolutionPtr spatialReferenceResolution = m_pSpRef; spatialReferenceResolution->SetDefaultMResolution(); spatialReferenceResolution->SetDefaultZResolution(); spatialReferenceResolution->SetDefaultXYResolution(); //ÉèÖÿռä×ø±êÎó²îÖµ ISpatialReferenceTolerancePtr spatialReferenceTolerance = m_pSpRef; spatialReferenceTolerance->SetDefaultMTolerance(); spatialReferenceTolerance->SetDefaultZTolerance(); spatialReferenceTolerance->SetDefaultXYTolerance(); m_bFinishedCreateFtCls = FALSE; return TRUE; } catch (...) { WriteLog("³õʼ»¯Òì³£,Çë¼ì²é¹¤×÷¿Õ¼äºÍ¿Õ¼ä²Î¿¼ÊÇ·ñÕýÈ·."); return FALSE; } } ////////////////////////////////////////////////////////////////////////// //¼òÒªÃèÊö : ´´½¨Ä¿±êÒªËØÀà //ÊäÈë²ÎÊý : //·µ »Ø Öµ : //ÐÞ¸ÄÈÕÖ¾ : ////////////////////////////////////////////////////////////////////////// BOOL XDWGReader::CreateTargetAllFeatureClass() { try { IFeatureWorkspacePtr pFtWS(m_pTargetWS); if (pFtWS == NULL) return FALSE; HRESULT hr; CString sInfoText; //´´½¨ÏµÍ³±í½á¹¹ IFieldsPtr ipFieldsPoint = 0; IFieldsPtr ipFieldsLine = 0; IFieldsPtr ipFieldsPolygon = 0; IFieldsPtr ipFieldsText = 0; IFieldsPtr ipFieldsAnnotation = 0; //Éú³ÉÆÕͨµãÀà×Ö¶Î CreateDwgPointFields(m_pSpRef, &ipFieldsPoint); //Éú³É×¢¼ÇµãÀà×Ö¶Î CreateDwgTextPointFields(m_pSpRef, &ipFieldsText); //Éú³ÉÏßÒªËØÀà×Ö¶Î CreateDwgLineFields(m_pSpRef, &ipFieldsLine); //Éú³ÉÃæÒªËØÀà×Ö¶Î CreateDwgPolygonFields(m_pSpRef, &ipFieldsPolygon); //Éú³É×¢¼Çͼ²ã×Ö¶Î CreateDwgAnnotationFields(m_pSpRef, &ipFieldsAnnotation); ////////////////////////////////////////////////////////////////////////// //Ôö¼ÓÀ©Õ¹ÊôÐÔ×Ö¶Î if (m_IsJoinXDataAttrs && m_Regapps.GetCount() > 0) { IFieldsEditPtr ipEditFieldsPoint = ipFieldsPoint; IFieldsEditPtr ipEditFieldsLine = ipFieldsLine; IFieldsEditPtr ipEditFieldsPolygon = ipFieldsPolygon; IFieldsEditPtr ipEditFieldsText = ipFieldsText; IFieldsEditPtr ipEditFieldsAnnotation = ipFieldsAnnotation; CString sRegappName; for (int i = 0; i < m_Regapps.GetCount(); i++) { //´´½¨À©Õ¹ÊôÐÔ×Ö¶Î IFieldPtr ipField(CLSID_Field); IFieldEditPtr ipFieldEdit = ipField; sRegappName = m_Regapps.GetAt(m_Regapps.FindIndex(i)); CComBSTR bsStr = sRegappName; ipFieldEdit->put_Name(bsStr); ipFieldEdit->put_AliasName(bsStr); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(2000); long lFldIndex = 0; ipEditFieldsPoint->FindField(bsStr, &lFldIndex); if (lFldIndex == -1) { ipEditFieldsPoint->AddField(ipField); } ipEditFieldsLine->FindField(bsStr, &lFldIndex); if (lFldIndex == -1) { ipEditFieldsLine->AddField(ipField); } ipEditFieldsPolygon->FindField(bsStr, &lFldIndex); if (lFldIndex == -1) { ipEditFieldsPolygon->AddField(ipField); } ipEditFieldsText->FindField(bsStr, &lFldIndex); if (lFldIndex == -1) { ipEditFieldsText->AddField(ipField); } ipEditFieldsAnnotation->FindField(bsStr, &lFldIndex); if (lFldIndex == -1) { ipEditFieldsAnnotation->AddField(ipField); } } } //Èç¹ûÓÐͼ²ãÏÈɾ³ý CheckDeleteFtCls(pFtWS, "Point"); CheckDeleteFtCls(pFtWS, "TextPoint"); CheckDeleteFtCls(pFtWS, "Line"); CheckDeleteFtCls(pFtWS, "Polygon"); CheckDeleteFtCls(pFtWS, "Annotation"); CheckDeleteFtCls(pFtWS, "ExtendTable"); //´´½¨µãͼ²ã hr = CreateDatasetFeatureClass(pFtWS, NULL, ipFieldsPoint, CComBSTR("Point"), esriFTSimple, m_pFeatClassPoint); if (m_pFeatClassPoint != NULL) { hr = m_pFeatClassPoint->Insert(VARIANT_TRUE, &m_pPointFeatureCursor); if (FAILED(hr)) { sInfoText.Format("´´½¨µãFeatureCursorʧ°Ü:%s", CatchErrorInfo()); WriteLog(sInfoText); } hr = m_pFeatClassPoint->CreateFeatureBuffer(&m_pPointFeatureBuffer); if (FAILED(hr)) { sInfoText.Format("´´½¨µãFeautureBufferʧ°Ü:%s", CatchErrorInfo()); WriteLog(sInfoText); } } else { sInfoText.Format("´´½¨PointÒªËØÀàʧ°Ü:%s", CatchErrorInfo()); WriteLog(sInfoText); return FALSE; } //´´½¨ÏßÒªËØÀà hr = CreateDatasetFeatureClass(pFtWS, NULL, ipFieldsLine, CComBSTR("Line"), esriFTSimple, m_pFeatClassLine); if (m_pFeatClassLine != NULL) { hr = m_pFeatClassLine->Insert(VARIANT_TRUE, &m_pLineFeatureCursor); if (FAILED(hr)) { sInfoText.Format("´´½¨ÏßFeatureCursorʧ°Ü:%s", CatchErrorInfo()); WriteLog(sInfoText); } hr = m_pFeatClassLine->CreateFeatureBuffer(&m_pLineFeatureBuffer); if (FAILED(hr)) { sInfoText.Format("´´½¨ÏßFeautureBufferʧ°Ü:%s", CatchErrorInfo()); WriteLog(sInfoText); } } else { sInfoText.Format("´´½¨LineÒªËØÀàʧ°Ü:%s", CatchErrorInfo()); WriteLog(sInfoText); return FALSE; } if (m_IsReadPolygon || m_IsLine2Polygon) { //´´½¨ÃæÒªËØÀà hr = CreateDatasetFeatureClass(pFtWS, NULL, ipFieldsPolygon, CComBSTR("Polygon"), esriFTSimple, m_pFeatClassPolygon); if (m_pFeatClassPolygon != NULL) { hr = m_pFeatClassPolygon->Insert(VARIANT_TRUE, &m_pPolygonFeatureCursor); if (FAILED(hr)) { sInfoText.Format("´´½¨ÃæFeatureCursorʧ°Ü:%s", CatchErrorInfo()); WriteLog(sInfoText); } hr = m_pFeatClassPolygon->CreateFeatureBuffer(&m_pPolygonFeatureBuffer); if (FAILED(hr)) { sInfoText.Format("´´½¨ÃæFeautureBufferʧ°Ü:%s", CatchErrorInfo()); WriteLog(sInfoText); } } else { sInfoText.Format("´´½¨PolygonÒªËØÀàʧ°Ü:%s", CatchErrorInfo()); WriteLog(sInfoText); return FALSE; } } //arcgis ×¢¼Çͼ²ã if (m_IsCreateAnnotation) { m_pAnnoFtCls = CreateAnnoFtCls(m_pTargetWS, "Annotation", ipFieldsAnnotation); if (m_pAnnoFtCls != NULL) { //ÉèÖÃÏÖʵ±ÈÀý³ß IUnknownPtr pUnk; m_pAnnoFtCls->get_Extension(&pUnk); IAnnoClassAdminPtr pAnnoClassAdmin = pUnk; if (pAnnoClassAdmin != NULL) { hr = pAnnoClassAdmin->put_ReferenceScale(m_dAnnoScale); hr = pAnnoClassAdmin->UpdateProperties(); } hr = m_pAnnoFtCls->Insert(VARIANT_TRUE, &m_pAnnoFeatureCursor); if (FAILED(hr)) { sInfoText.Format("´´½¨×¢¼ÇFeatureCursorʧ°Ü:%s", CatchErrorInfo()); WriteLog(sInfoText); } hr = m_pAnnoFtCls->CreateFeatureBuffer(&m_pAnnoFeatureBuffer); if (FAILED(hr)) { sInfoText.Format("´´½¨×¢¼ÇFeautureBufferʧ°Ü:%s", CatchErrorInfo()); WriteLog(sInfoText); } } else { sInfoText.Format("´´½¨AnnotationÒªËØÀàʧ°Ü:%s", CatchErrorInfo()); WriteLog(sInfoText); return FALSE; } //´´½¨×¢¼Çͼ²ã×ÖÌå IFontDispPtr pFont(CLSID_StdFont); IFontPtr fnt = pFont; fnt->put_Name(CComBSTR("ËÎÌå")); CY cy; cy.int64 = 9; fnt->put_Size(cy); m_pAnnoTextFont = pFont.Detach(); } else { //Îı¾µã hr = CreateDatasetFeatureClass(pFtWS, NULL, ipFieldsText, CComBSTR("TextPoint"), esriFTSimple, m_pFeatClassText); if (m_pFeatClassText != NULL) { hr = m_pFeatClassText->Insert(VARIANT_TRUE, &m_pTextFeatureCursor); if (FAILED(hr)) { sInfoText.Format("´´½¨Îı¾µãFeatureCursorʧ°Ü:%s", CatchErrorInfo()); WriteLog(sInfoText); } hr = m_pFeatClassText->CreateFeatureBuffer(&m_pTextFeatureBuffer); if (FAILED(hr)) { sInfoText.Format("´´½¨Îı¾FeautureBufferʧ°Ü:%s", CatchErrorInfo()); WriteLog(sInfoText); } } else { sInfoText.Format("´´½¨TextÒªËØÀàʧ°Ü:%s", CatchErrorInfo()); WriteLog(sInfoText); return FALSE; } } //À©Õ¹ÊôÐÔ±í hr = CreateExtendTable(pFtWS, CComBSTR("ExtendTable"), &m_pExtendTable); if (m_pExtendTable != NULL) { hr = m_pExtendTable->Insert(VARIANT_TRUE, &m_pExtentTableRowCursor); if (FAILED(hr)) { sInfoText.Format("´´½¨TableBufferʧ°Ü:%s", CatchErrorInfo()); WriteLog(sInfoText); } hr = m_pExtendTable->CreateRowBuffer(&m_pExtentTableRowBuffer); if (FAILED(hr)) { sInfoText.Format("´´½¨TableCursorʧ°Ü:%s", CatchErrorInfo()); WriteLog(sInfoText); } } else { sInfoText.Format("´´½¨ExtendTableʧ°Ü:%s", CatchErrorInfo()); WriteLog(sInfoText); return FALSE; } m_bFinishedCreateFtCls = TRUE; return TRUE; } catch (...) { return FALSE; } } ////////////////////////////////////////////////////////////////////////// //¼òÒªÃèÊö : Öð¸ö¶ÁÈ¡CADÎļþ //ÊäÈë²ÎÊý : //·µ »Ø Öµ : //ÐÞ¸ÄÈÕÖ¾ : ////////////////////////////////////////////////////////////////////////// BOOL XDWGReader::ReadFile(LPCTSTR lpdwgFilename) { try { //Éú³ÉÄ¿±êGDBͼ²ã if (!m_bFinishedCreateFtCls) { if (!CreateTargetAllFeatureClass()) { WriteLog("´´½¨Ä¿±êÒªËØÀà³öÏÖÒì³££¬ÎÞ·¨½øÐиñʽת»»¡£"); return FALSE; } } //Çå³ý²»¶ÁµÄͼ²ãÁбí m_UnReadLayers.RemoveAll(); //´ò¿ªCADÎļþ²¢¶ÁÈ¡ //µÃµ½DWGͼÃûºÍÈÕÖ¾ÎļþÃû CString szDatasetName ; CString szLogFileName; int index; CString sFileName = lpdwgFilename; sFileName = sFileName.Mid(sFileName.ReverseFind('\\') + 1); index = ((CString) lpdwgFilename).ReverseFind('\\'); int ilength = ((CString) lpdwgFilename).GetLength(); szDatasetName = CString(lpdwgFilename).Right(ilength - 1 - index); index = szDatasetName.ReverseFind('.'); szDatasetName = szDatasetName.Left(index); m_strDwgName = szDatasetName; // ¼Ç¼¿ªÊ¼´¦Àíʱ¼ä CTime tStartTime = CTime::GetCurrentTime(); CString sInfoText; sInfoText.Format("¿ªÊ¼¶Á %s Îļþ.", lpdwgFilename); WriteLog(sInfoText); if (m_pProgressBar != NULL) { m_pProgressBar->SetPos(0); CString sProgressText; sProgressText.Format("ÕýÔÚ¶ÁÈ¡%s, ÇëÉÔºò...", lpdwgFilename); m_pProgressBar->SetWindowText(sProgressText); } OdDbDatabasePtr pDb; pDb = svcs.readFile(lpdwgFilename, false, false, Oda::kShareDenyReadWrite); if (pDb.isNull()) { WriteLog("DWGÎļþΪ¿Õ!"); } // ´ÓdwgÎļþ»ñµÃ·¶Î§ sInfoText.Format("ͼ·ù·¶Î§: ×îСX×ø±ê:%f, ×î´óX×ø±ê:%f, ×îСY×ø±ê:%f, ×î´óY×ø±ê:%f \n", 0.9 * pDb->getEXTMIN().x, 1.1 * pDb->getEXTMAX().x, 0.9 * pDb->getEXTMIN().y, 1.1 * pDb->getEXTMAX().y); WriteLog(sInfoText); //¶ÁCADÎļþ ReadBlock(pDb); pDb.release(); //¼Ç¼Íê³Éʱ¼ä CTime tEndTime = CTime::GetCurrentTime(); CTimeSpan span = tEndTime - tStartTime; sInfoText.Format("%sÎļþת»»Íê³É!¹²ºÄʱ%dʱ%d·Ö%dÃë.", lpdwgFilename, span.GetHours(), span.GetMinutes(), span.GetSeconds()); WriteLog(sInfoText); WriteLog("=============================================================="); return TRUE; } catch (...) { CString sErr; sErr.Format("%sÎļþ²»´æÔÚ»òÕý´¦ÓÚ´ò¿ª×´Ì¬£¬ÎÞ·¨½øÐÐÊý¾Ý¶ÁÈ¡£¬Çë¼ì²é¡£", lpdwgFilename); WriteLog(sErr); return FALSE; } } /******************************************************************** ¼òÒªÃèÊö : ÉèÖÃÈÕÖ¾´æ·Å·¾¶ ÊäÈë²ÎÊý : ·µ »Ø Öµ : ÈÕ ÆÚ : 2008/09/27,BeiJing. ×÷ Õß : ×ÚÁÁ <[email protected]> ÐÞ¸ÄÈÕÖ¾ : *********************************************************************/ void XDWGReader::PutLogFilePath(CString sLogFile) { m_pLogRec = new CLogRecorder(sLogFile); m_sLogFilePath = sLogFile; } //дÈÕÖ¾Îļþ void XDWGReader::WriteLog(CString sLog) { if (m_pLogRec == NULL) { return; } if (!sLog.IsEmpty()) { m_pLogRec->WriteLog(sLog); } } //½áÊøDWGµÄ¶ÁÈ¡¹¤×÷ BOOL XDWGReader::CommitReadDwg() { //ÊÍ·ÅÓõ½µÄ¶ÔÏó ReleaseAOs(); if (m_pLogRec != NULL) { m_pLogRec->CloseFile(); } return TRUE; } void XDWGReader::ReadHeader(OdDbDatabase* pDb) { OdString sName = pDb->getFilename(); CString sInfoText; sInfoText.Format("Database was loaded from:%s", sName.c_str()); WriteLog(sInfoText); OdDb::DwgVersion vVer = pDb->originalFileVersion(); sInfoText.Format("File version is: %s", OdDb::DwgVersionToStr(vVer)); WriteLog(sInfoText); sInfoText.Format("Header Variables: %f,%f", pDb->getLTSCALE(), pDb->getATTMODE()); WriteLog(sInfoText); OdDbDate d = pDb->getTDCREATE(); short month, day, year, hour, min, sec, msec; d.getDate(month, day, year); d.getTime(hour, min, sec, msec); sInfoText.Format(" TDCREATE: %d-%d-%d,%d:%d:%d", month, day, year, hour, min, sec); WriteLog(sInfoText); d = pDb->getTDUPDATE(); d.getDate(month, day, year); d.getTime(hour, min, sec, msec); sInfoText.Format(" TDCREATE: %d-%d-%d,%d:%d:%d", month, day, year, hour, min, sec); WriteLog(sInfoText); } void XDWGReader::ReadSymbolTable(OdDbObjectId tableId) { OdDbSymbolTablePtr pTable = tableId.safeOpenObject(); CString sInfoText; sInfoText.Format("±íÃû:%s", pTable->isA()->name()); WriteLog(sInfoText); OdDbSymbolTableIteratorPtr pIter = pTable->newIterator(); for (pIter->start(); !pIter->done(); pIter->step()) { OdDbSymbolTableRecordPtr pTableRec = pIter->getRecordId().safeOpenObject(); CString TableRecName; TableRecName.Format("%s", pTableRec->getName().c_str()); TableRecName.MakeUpper(); sInfoText.Format(" %s<%s>", TableRecName, pTableRec->isA()->name()); WriteLog(sInfoText); } } void XDWGReader::ReadLayers(OdDbDatabase* pDb) { OdDbLayerTablePtr pLayers = pDb->getLayerTableId().safeOpenObject(); CString sInfoText; sInfoText.Format("²ãÃû:%s", pLayers->desc()->name()); WriteLog(sInfoText); OdDbSymbolTableIteratorPtr pIter = pLayers->newIterator(); for (pIter->start(); !pIter->done(); pIter->step()) { OdDbLayerTableRecordPtr pLayer = pIter->getRecordId().safeOpenObject(); CString LayerName; LayerName.Format("%s", pLayer->desc()->name()); LayerName.MakeUpper(); sInfoText.Format(" %s<%s>,layercolor:%d,%s,%s,%s,%s", pLayer->getName().c_str(), LayerName, pLayer->colorIndex(), pLayer->isOff() ? "Off" : "On", pLayer->isLocked() ? "Locked" : "Unlocked", pLayer->isFrozen() ? "Frozen" : "UnFrozen", pLayer->isDependent() ? "Dep. on XRef" : "Not dep. on XRef"); WriteLog(sInfoText); } } /************************************************************************ ¼òÒªÃèÊö : ¶ÁDWGÀ©Õ¹ÊôÐÔ,²¢Ð´Èëµ½À©Õ¹ÊôÐÔ±íÖÐ ÊäÈë²ÎÊý : ·µ »Ø Öµ : ÐÞ¸ÄÈÕÖ¾ : ************************************************************************/ void XDWGReader::ReadExtendAttribs(OdResBuf* xIter, CString sEntityHandle) { if (xIter == 0 || m_pExtendTable == NULL) return; CMapStringToPtr mapExtraRes; //±£´æËùÓÐÓ¦Óü°À©Õ¹ÊôÐÔ (Ó¦ÓÃÃû+CStringList*) //Registered Application Name CString sAppName; CString sExtendValue; //CStringList lstExtendValues;//ËùÓÐÀ©Õ¹ÊôÐÔ,ÓÃ[]ºÅ·Ö¸ô OdResBuf* xIterLoop = xIter; for (; xIterLoop != 0; xIterLoop = xIterLoop->next()) { int code = xIterLoop->restype(); switch (OdDxfCode::_getType(code)) { case OdDxfCode::Name: case OdDxfCode::String: sExtendValue.Format("%s", xIterLoop->getString().c_str()); break; case OdDxfCode::Bool: sExtendValue.Format("%d", xIterLoop->getBool()); break; case OdDxfCode::Integer8: sExtendValue.Format("%d", xIterLoop->getInt8()); break; case OdDxfCode::Integer16: sExtendValue.Format("%d", xIterLoop->getInt16()); break; case OdDxfCode::Integer32: sExtendValue.Format("%d", xIterLoop->getInt32()); break; case OdDxfCode::Double: sExtendValue.Format("%f", xIterLoop->getDouble()); break; case OdDxfCode::Angle: sExtendValue.Format("%f", xIterLoop->getDouble()); break; case OdDxfCode::Point: { OdGePoint3d p = xIterLoop->getPoint3d(); sExtendValue.Format("%f,%f,%f", p.x, p.y, p.z); } break; case OdDxfCode::BinaryChunk: sExtendValue = "<Binary Data>"; break; case OdDxfCode::Handle: case OdDxfCode::LayerName: sExtendValue.Format("%s", xIterLoop->getString().c_str()); break; case OdDxfCode::ObjectId: case OdDxfCode::SoftPointerId: case OdDxfCode::HardPointerId: case OdDxfCode::SoftOwnershipId: case OdDxfCode::HardOwnershipId: { OdDbHandle h = xIterLoop->getHandle(); sExtendValue.Format("%s", h.ascii()); } break; case OdDxfCode::Unknown: default: sExtendValue = "Unknown"; break; } //Registered Application Name if (code == OdResBuf::kDxfRegAppName) { sAppName = sExtendValue; //Éú³É¶ÔÓ¦ÓÚ¸ÃÓ¦ÓõÄStringList CStringList* pLstExtra = new CStringList(); mapExtraRes.SetAt(sAppName, pLstExtra); } else if (code == OdResBuf::kDxfXdAsciiString || code == OdResBuf::kDxfXdReal) { void* rValue; if (mapExtraRes.Lookup(sAppName, rValue)) { CStringList* pLstExtra = (CStringList*)rValue; //±£´æµ½¶ÔÓ¦ÓÚ¸ÃAPPNameµÄListÖÐ pLstExtra->AddTail(sExtendValue); } } } POSITION mapPos = mapExtraRes.GetStartPosition(); while (mapPos) { CString sAppName; void* rValue; mapExtraRes.GetNextAssoc(mapPos, sAppName, rValue); CStringList* pList = (CStringList*) rValue; HRESULT hr; long lFieldIndex; CComBSTR bsStr; CComVariant vtVal; //Éú³ÉÀ©Õ¹ÊôÐÔ×Ö·û´® POSITION pos = pList->GetHeadPosition(); if (pos != NULL) { CString sAllValues = "[" + pList->GetNext(pos) + "]"; while (pos != NULL) { sAllValues = sAllValues + "[" + pList->GetNext(pos) + "]"; } //Add Extend data to Extend Table bsStr = "Handle"; m_pExtendTable->FindField(bsStr, &lFieldIndex); vtVal = sEntityHandle; m_pExtentTableRowBuffer->put_Value(lFieldIndex, vtVal); bsStr = "BaseName"; m_pExtendTable->FindField(bsStr, &lFieldIndex); vtVal = m_strDwgName; m_pExtentTableRowBuffer->put_Value(lFieldIndex, vtVal); bsStr = "XDataName"; m_pExtendTable->FindField(bsStr, &lFieldIndex); sAppName.MakeUpper(); vtVal = sAppName; m_pExtentTableRowBuffer->put_Value(lFieldIndex, vtVal); bsStr = "XDataValue"; m_pExtendTable->FindField(bsStr, &lFieldIndex); vtVal = sAllValues; m_pExtentTableRowBuffer->put_Value(lFieldIndex, vtVal); hr = m_pExtentTableRowCursor->InsertRow(m_pExtentTableRowBuffer, &m_TableId); if (FAILED(hr)) { WriteLog("À©Õ¹ÊôÐÔ¶Áȡʧ°Ü:" + CatchErrorInfo()); } } m_pExtentTableRowCursor->Flush(); vtVal.Clear(); bsStr.Empty(); pList->RemoveAll(); delete pList; } mapExtraRes.RemoveAll(); } /******************************************************************** ¼òÒªÃèÊö : ÖØÃüÃûͼ²ãÃû£¬Õë¶Ô¼ÃÄÏÏîÄ¿µãºÍÏßÔÚͬÒÔͼ²ãÏ£¬·ÖÀë³öÏßÒªËØµ½Ö¸¶¨Í¼²ãÏ ÊäÈë²ÎÊý : ·µ »Ø Öµ : ÐÞ¸ÄÈÕÖ¾ : *********************************************************************/ /*void XDWGReader::RenameEntityLayerName(CString sDwgOriLayerName, IFeatureBuffer*& pFeatBuffer) { if (m_lstRenameLayers.GetCount() <= 0) { return; } //ÖØÐÂÖ¸¶¨Í¼²ã£¬°ÑÏß²ã·Åµ½ÏàÓ¦µÄ¸¨ÖúÏßͼ²ãÖÐÈ¥ POSITION pos = m_lstRenameLayers.GetHeadPosition(); while (pos != NULL) { RenameLayerRecord* pRenameRec = m_lstRenameLayers.GetNext(pos); if (pRenameRec->sDWG_LAYERNAME_CONTAINS.IsEmpty()||pRenameRec->sNEW_DWG_LAYERNAME.IsEmpty()||pRenameRec->sNEW_LAYERTYPE.IsEmpty()) { continue; } if (pRenameRec->sNEW_LAYERTYPE.CompareNoCase("Line") == 0) { CStringList lstKeys; CString sKeyStr; CString sLayerNameContains = pRenameRec->sDWG_LAYERNAME_CONTAINS; int iPos = sLayerNameContains.Find(','); while (iPos != -1) { sKeyStr = sLayerNameContains.Mid(0, iPos); sLayerNameContains = sLayerNameContains.Mid(iPos + 1); iPos = sLayerNameContains.Find(','); lstKeys.AddTail(sKeyStr); } sKeyStr = sLayerNameContains; lstKeys.AddTail(sKeyStr); bool bFindKey = true; for (int ki=0; ki< lstKeys.GetCount(); ki++) { sKeyStr = lstKeys.GetAt(lstKeys.FindIndex(ki)); if (sDwgOriLayerName.Find(sKeyStr) == -1) { bFindKey = false; break; } } //Èç¹û°üº¬ËùÓÐÌØÕ÷Öµ£¬Ôò¸üÃû if (bFindKey) { AddAttributes("Layer", pRenameRec->sNEW_DWG_LAYERNAME, pFeatBuffer); break; } } } } */ /******************************************************************** ¼òÒªÃèÊö : ²åÈë×¢¼ÇÒªËØ ÊäÈë²ÎÊý : ·µ »Ø Öµ : ÐÞ¸ÄÈÕÖ¾ : *********************************************************************/ void XDWGReader::InsertAnnoFeature(OdRxObject* pEnt) { HRESULT hr; OdDbEntityPtr pOdDbEnt = pEnt; if (pOdDbEnt.isNull()) return; CString sEntType = pOdDbEnt->isA()->name(); if (sEntType.Compare("AcDbMText") == 0 || sEntType.Compare("AcDbText") == 0 || sEntType.Compare("AcDbAttribute") == 0) { // Ìí¼ÓÊôÐÔ AddBaseAttributes(pOdDbEnt, "Annotation", m_pAnnoFeatureBuffer); //CString sTempVal; CString sText = ""; double dHeight = 0; double dWeight = 0; double dAngle = 0; OdGePoint3d textPos; //¶ÔÆëµã OdGePoint3d alignPoint; esriTextHorizontalAlignment horizAlign = esriTHALeft; esriTextVerticalAlignment vertAlign = esriTVABaseline; CString sTextStyle = "STANDARD"; CString sHeight = "0"; CString sElevation = "0"; CString sThickness = "0"; CString sOblique = "0"; if (sEntType.Compare("AcDbMText") == 0) { OdDbMTextPtr pMText = OdDbMTextPtr(pEnt); //Îı¾ÄÚÈÝ sText = pMText->contents(); int iPos = sText.ReverseFind(';'); sText = sText.Mid(iPos + 1); sText.Replace("{", ""); sText.Replace("}", ""); //Îı¾·ç¸ñ OdDbSymbolTableRecordPtr symbolbRec = OdDbSymbolTableRecordPtr(pMText->textStyle().safeOpenObject()); if (!symbolbRec.isNull()) { sTextStyle.Format("%s", symbolbRec->getName()); } //¸ß¶È sHeight.Format("%f", pMText->textHeight()); //¸ß³ÌÖµ sElevation.Format("%f", pMText->location().z); ////Éú³É×¢¼ÇÐèÒªµÄ²ÎÊý//// //½Ç¶È dAngle = pMText->rotation(); //¸ßºÍ¿í dHeight = pMText->textHeight(); dWeight = pMText->width(); //λÖõã textPos = pMText->location(); //ÉèÖÃ¶ÔÆë·½Ê½ if (pMText->horizontalMode() == OdDb::kTextLeft) { horizAlign = esriTHALeft; } else if (pMText->horizontalMode() == OdDb::kTextCenter) { horizAlign = esriTHACenter; } else if (pMText->horizontalMode() == OdDb::kTextRight) { horizAlign = esriTHARight; } else if (pMText->horizontalMode() == OdDb::kTextFit) { horizAlign = esriTHAFull; } if (pMText->verticalMode() == OdDb::kTextBase) { vertAlign = esriTVABaseline; } else if (pMText->verticalMode() == OdDb::kTextBottom) { vertAlign = esriTVABottom; } else if (pMText->verticalMode() == OdDb::kTextTop) { vertAlign = esriTVATop; } else if (pMText->verticalMode() == OdDb::kTextVertMid) { vertAlign = esriTVACenter; } } else if (sEntType.Compare("AcDbText") == 0 || sEntType.Compare("AcDbAttribute") == 0) { OdDbTextPtr pText = OdDbTextPtr(pEnt); //Îı¾ÄÚÈÝ sText = pText->textString(); //Îı¾·ç¸ñ OdDbSymbolTableRecordPtr symbolbRec = OdDbSymbolTableRecordPtr(pText->textStyle().safeOpenObject()); if (!symbolbRec.isNull()) { sTextStyle.Format("%s", symbolbRec->getName()); } //¸ß³ÌÖµ sElevation.Format("%f", pText->position().z); //¸ß¶È sHeight.Format("%f", pText->height()); //ºñ¶È sThickness.Format("%.f", pText->thickness()); //Çã½Ç sOblique.Format("%f", pText->oblique()); ////Éú³É×¢¼ÇÐèÒªµÄ²ÎÊý//// //½Ç¶È dAngle = pText->rotation(); dHeight = pText->height(); dWeight = 0; textPos = pText->position(); alignPoint = pText->alignmentPoint(); //if (textPos.x <= 0.0001 && textPos.y <= 0.0001) //Èç¹ûûÓÐ¶ÔÆëµã£¬ÔòʹÓÃλÖõã //{ // textPos = pText->position(); //} CString tempstr; tempstr.Format("%f", alignPoint.x); AddAttributes("AlignPtX", tempstr, m_pAnnoFeatureBuffer); tempstr.Format("%f", alignPoint.y); AddAttributes("AlignPtY", tempstr, m_pAnnoFeatureBuffer); //OdGePoint3dArray boundingPoints; //pText->getBoundingPoints(boundingPoints); //OdGePoint3d topLeft = boundingPoints[0]; //OdGePoint3d topRight = boundingPoints[1]; //OdGePoint3d bottomLeft = boundingPoints[2]; //OdGePoint3d bottomRight = boundingPoints[3]; //ÉèÖÃ¶ÔÆë·½Ê½ if (pText->horizontalMode() == OdDb::kTextLeft) { horizAlign = esriTHALeft; } else if (pText->horizontalMode() == OdDb::kTextCenter) { horizAlign = esriTHACenter; } else if (pText->horizontalMode() == OdDb::kTextRight) { horizAlign = esriTHARight; } else if (pText->horizontalMode() == OdDb::kTextFit) { horizAlign = esriTHAFull; } if (pText->verticalMode() == OdDb::kTextBase) { vertAlign = esriTVABaseline; } else if (pText->verticalMode() == OdDb::kTextBottom) { vertAlign = esriTVABottom; } else if (pText->verticalMode() == OdDb::kTextTop) { vertAlign = esriTVATop; } else if (pText->verticalMode() == OdDb::kTextVertMid) { vertAlign = esriTVACenter; } } //ÉèÖÃ×¢¼ÇÎı¾·ç¸ñ AddAttributes("TextStyle", sTextStyle, m_pAnnoFeatureBuffer); AddAttributes("Height", sHeight, m_pAnnoFeatureBuffer); AddAttributes("Elevation", sElevation, m_pAnnoFeatureBuffer); AddAttributes("Thickness", sThickness, m_pAnnoFeatureBuffer); AddAttributes("Oblique", sOblique, m_pAnnoFeatureBuffer); //´´½¨ Element ITextElementPtr pTextElement = MakeTextElementByStyle(sText, dAngle, dHeight, textPos.x, textPos.y, m_dAnnoScale, horizAlign, vertAlign); IElementPtr pElement = pTextElement; IAnnotationFeaturePtr pTarAnnoFeat = m_pAnnoFeatureBuffer; hr = pTarAnnoFeat->put_Annotation(pElement); PutExtendAttribsValue(m_pAnnoFeatureBuffer, OdDbEntityPtr(pEnt)->xData()); CComVariant OID; hr = m_pAnnoFeatureCursor->InsertFeature(m_pAnnoFeatureBuffer, &OID); if (FAILED(hr)) { CString sInfoText; sInfoText = "Annotation¶ÔÏóдÈëµ½PGDBʧ°Ü." + CatchErrorInfo(); WriteLog(sInfoText); m_lUnReadEntityNum++; } } } ////////////////////////////////////////////////////////////////////////// //¼òÒªÃèÊö : ²åÈëCADÊôÐÔ¶ÔÏó //ÊäÈë²ÎÊý : //·µ »Ø Öµ : //ÐÞ¸ÄÈÕÖ¾ : ////////////////////////////////////////////////////////////////////////// void XDWGReader::InsertDwgAttribFeature(OdRxObject* pEnt) { HRESULT hr; OdDbEntityPtr pOdDbEnt = pEnt; if (pOdDbEnt.isNull()) return; CString sEntType = pOdDbEnt->isA()->name(); if (strcmp(sEntType, "AcDbAttributeDefinition") == 0) { // Ìí¼ÓÊôÐÔ AddBaseAttributes(pOdDbEnt, "Annotation", m_pAnnoFeatureBuffer); //CString sTempVal; CString sText = ""; double dHeight = 0; double dWeight = 0; double dAngle = 0; OdGePoint3d textPos; esriTextHorizontalAlignment horizAlign = esriTHALeft; esriTextVerticalAlignment vertAlign = esriTVABaseline; CString sTextStyle = "STANDARD"; CString sHeight = "0"; CString sElevation = "0"; CString sThickness = "0"; CString sOblique = "0"; OdDbAttributeDefinitionPtr pText = OdDbAttributeDefinitionPtr(pEnt); //Îı¾ÄÚÈÝ CString sTag = pText->tag(); CString sPrompt = pText->prompt(); sText = sTag; //Îı¾·ç¸ñ OdDbSymbolTableRecordPtr symbolbRec = OdDbSymbolTableRecordPtr(pText->textStyle().safeOpenObject()); if (!symbolbRec.isNull()) { sTextStyle.Format("%s", symbolbRec->getName()); } //¸ß³ÌÖµ sElevation.Format("%f", pText->position().z); //¸ß¶È sHeight.Format("%f", pText->height()); //ºñ¶È sThickness.Format("%.f", pText->thickness()); //Çã½Ç sOblique.Format("%f", pText->oblique()); ////Éú³É×¢¼ÇÐèÒªµÄ²ÎÊý//// //½Ç¶È dAngle = pText->rotation(); dHeight = pText->height(); dWeight = 0; textPos = pText->alignmentPoint(); if (textPos.x <= 0.0001 && textPos.y <= 0.0001) //Èç¹ûûÓÐ¶ÔÆëµã£¬ÔòʹÓÃλÖõã { textPos = pText->position(); } //ÉèÖÃ¶ÔÆë·½Ê½ if (pText->horizontalMode() == OdDb::kTextLeft) { horizAlign = esriTHALeft; } else if (pText->horizontalMode() == OdDb::kTextCenter) { horizAlign = esriTHACenter; } else if (pText->horizontalMode() == OdDb::kTextRight) { horizAlign = esriTHARight; } else if (pText->horizontalMode() == OdDb::kTextFit) { horizAlign = esriTHAFull; } if (pText->verticalMode() == OdDb::kTextBase) { vertAlign = esriTVABaseline; } else if (pText->verticalMode() == OdDb::kTextBottom) { vertAlign = esriTVABottom; } else if (pText->verticalMode() == OdDb::kTextTop) { vertAlign = esriTVATop; } else if (pText->verticalMode() == OdDb::kTextVertMid) { vertAlign = esriTVACenter; } //ÉèÖÃ×¢¼ÇÎı¾·ç¸ñ AddAttributes("TextStyle", sTextStyle, m_pAnnoFeatureBuffer); AddAttributes("Height", sHeight, m_pAnnoFeatureBuffer); AddAttributes("Elevation", sElevation, m_pAnnoFeatureBuffer); AddAttributes("Thickness", sThickness, m_pAnnoFeatureBuffer); AddAttributes("Oblique", sOblique, m_pAnnoFeatureBuffer); //´´½¨ Element ITextElementPtr pTextElement = MakeTextElementByStyle(sText, dAngle, dHeight, textPos.x, textPos.y, m_dAnnoScale, horizAlign, vertAlign); IElementPtr pElement = pTextElement; IAnnotationFeaturePtr pTarAnnoFeat = m_pAnnoFeatureBuffer; hr = pTarAnnoFeat->put_Annotation(pElement); PutExtendAttribsValue(m_pAnnoFeatureBuffer, OdDbEntityPtr(pEnt)->xData()); CComVariant OID; hr = m_pAnnoFeatureCursor->InsertFeature(m_pAnnoFeatureBuffer, &OID); if (FAILED(hr)) { CString sInfoText; sInfoText = "Annotation¶ÔÏóдÈëµ½PGDBʧ°Ü." + CatchErrorInfo(); WriteLog(sInfoText); m_lUnReadEntityNum++; } } } /******************************************************************** ¼òÒªÃèÊö : Ìí¼ÓÀ©Õ¹ÊôÐÔÖµ ÊäÈë²ÎÊý : ·µ »Ø Öµ : ÐÞ¸ÄÈÕÖ¾ : *********************************************************************/ BOOL XDWGReader::PutExtendAttribsValue(IFeatureBuffer*& pFtBuf, OdResBuf* xIter) { if (m_IsJoinXDataAttrs == FALSE || m_Regapps.GetCount() <= 0 || xIter == NULL) { return FALSE; } CMapStringToPtr mapExtraRes; //±£´æËùÓÐÓ¦Óü°À©Õ¹ÊôÐÔ (Ó¦ÓÃÃû+CStringList*) //Registered Application Name CString sAppName; CString sExtendValue; //CStringList lstExtendValues;//ËùÓÐÀ©Õ¹ÊôÐÔ,ÓÃ,ºÅ·Ö¸ô OdResBuf* xIterLoop = xIter; for (; xIterLoop != 0; xIterLoop = xIterLoop->next()) { int code = xIterLoop->restype(); switch (OdDxfCode::_getType(code)) { case OdDxfCode::Name: case OdDxfCode::String: sExtendValue.Format("%s", xIterLoop->getString().c_str()); break; case OdDxfCode::Bool: sExtendValue.Format("%d", xIterLoop->getBool()); break; case OdDxfCode::Integer8: sExtendValue.Format("%d", xIterLoop->getInt8()); break; case OdDxfCode::Integer16: sExtendValue.Format("%d", xIterLoop->getInt16()); break; case OdDxfCode::Integer32: sExtendValue.Format("%d", xIterLoop->getInt32()); break; case OdDxfCode::Double: sExtendValue.Format("%f", xIterLoop->getDouble()); break; case OdDxfCode::Angle: sExtendValue.Format("%f", xIterLoop->getDouble()); break; case OdDxfCode::Point: { OdGePoint3d p = xIterLoop->getPoint3d(); sExtendValue.Format("%f,%f,%f", p.x, p.y, p.z); } break; case OdDxfCode::BinaryChunk: sExtendValue = "<Binary Data>"; break; case OdDxfCode::Handle: case OdDxfCode::LayerName: sExtendValue.Format("%s", xIterLoop->getString().c_str()); break; case OdDxfCode::ObjectId: case OdDxfCode::SoftPointerId: case OdDxfCode::HardPointerId: case OdDxfCode::SoftOwnershipId: case OdDxfCode::HardOwnershipId: { OdDbHandle h = xIterLoop->getHandle(); sExtendValue.Format("%s", h.ascii()); } break; case OdDxfCode::Unknown: default: sExtendValue = "Unknown"; break; } //Registered Application Name if (code == OdResBuf::kDxfRegAppName) { sAppName = sExtendValue; //Éú³É¶ÔÓ¦ÓÚ¸ÃÓ¦ÓõÄStringList CStringList* pLstExtra = new CStringList(); mapExtraRes.SetAt(sAppName, pLstExtra); } else if (code == OdResBuf::kDxfXdAsciiString || code == OdResBuf::kDxfXdReal) { void* rValue; if (mapExtraRes.Lookup(sAppName, rValue)) { CStringList* pLstExtra = (CStringList*) rValue; //±£´æµ½¶ÔÓ¦ÓÚ¸ÃAPPNameµÄListÖÐ pLstExtra->AddTail(sExtendValue); } } } //µÃµ½×Ö¶Î IFieldsPtr pFields; pFtBuf->get_Fields(&pFields); POSITION mapPos = mapExtraRes.GetStartPosition(); while (mapPos) { CString sAppName; void* rValue; mapExtraRes.GetNextAssoc(mapPos, sAppName, rValue); CStringList* pList = (CStringList*) rValue; long lIdx = 0; pFields->FindField(CComBSTR(sAppName), &lIdx); if (lIdx != -1) { CString sAllValues = ""; //Éú³ÉÀ©Õ¹ÊôÐÔ×Ö·û´® POSITION pos = pList->GetHeadPosition(); if (pos != NULL) { sAllValues = pList->GetNext(pos); while (pos != NULL) { sAllValues = sAllValues + "," + pList->GetNext(pos) ; } pFtBuf->put_Value(lIdx, CComVariant(sAllValues)); } } pList->RemoveAll(); delete pList; } mapExtraRes.RemoveAll(); return TRUE; } ////////////////////////////////////////////////////////////////////////// //¼òÒªÃèÊö : ¶ÁCADµÄÿ¸öʵÌåÒªËØ //ÊäÈë²ÎÊý : //·µ »Ø Öµ : //ÐÞ¸ÄÈÕÖ¾ : ////////////////////////////////////////////////////////////////////////// void XDWGReader::ReadEntity(OdDbObjectId id) { OdDbEntityPtr pEnt = id.safeOpenObject(); OdDbLayerTableRecordPtr pLayerTableRecord = pEnt->layerId().safeOpenObject(); CString sInfoText; if ((pLayerTableRecord->isOff() || pLayerTableRecord->isLocked() || pLayerTableRecord->isFrozen()) && (m_IsReadInvisible == FALSE)) { //±ÜÃâÈÕÖ¾ÖØ¸´ÄÚÈÝ CString sUnReadLayer = pEnt->layer().c_str(); POSITION pos = m_UnReadLayers.Find(sUnReadLayer); if (pos == NULL) { m_UnReadLayers.AddTail(sUnReadLayer); sInfoText.Format("<%s>²ãÒªËØ²»¿ÉÊÓ²»´¦Àí!", sUnReadLayer); WriteLog(sInfoText); } m_lUnReadEntityNum++; } else { OdDbHandle hTmp; char szEntityHandle[50] = {0}; hTmp = pEnt->getDbHandle(); hTmp.getIntoAsciiBuffer(szEntityHandle); //¼Ç¼µ±Ç°handleÖµ m_sEntityHandle = szEntityHandle; //Çå¿ÕFeatureBuffer CleanAllFeatureBuffers(); OdSmartPtr<OdDbEntity_Dumper> pEntDumper = pEnt; IGeometryPtr pShape; HRESULT hr; CComVariant OID; pEntDumper->m_DwgReader = this; // »ñµÃ¼¸ºÎÊý¾Ý pShape = pEntDumper->dump(pEnt); if (pShape == NULL) { m_lUnReadEntityNum++; return ; } //ÐÞÕý¿Õ¼ä²Î¿¼ hr = pShape->Project(m_pSpRef); // Îı¾ CString sEntType = OdDbEntityPtr(pEnt)->isA()->name(); if ((strcmp(sEntType, "AcDbMText") == 0) || (strcmp(sEntType, "AcDbText") == 0) || (strcmp(sEntType, "AcDbShape") == 0)) { if (m_IsCreateAnnotation) { //²åÈë×¢¼Ç¶ÔÏó InsertAnnoFeature(pEnt); } else { hr = m_pTextFeatureBuffer->putref_Shape(pShape); if (SUCCEEDED(hr)) { AddBaseAttributes(pEnt, "Annotation", m_pTextFeatureBuffer); //±àÂë¶ÔÕÕ if (CompareCodes(m_pTextFeatureBuffer)) { PutExtendAttribsValue(m_pTextFeatureBuffer, pEnt->xData()); hr = m_pTextFeatureCursor->InsertFeature(m_pTextFeatureBuffer, &OID); if (FAILED(hr)) { sInfoText = "Text¶ÔÏóдÈëµ½PGDBʧ°Ü¡£" + CatchErrorInfo(); WriteLog(sInfoText); m_lUnReadEntityNum++; } } } else { sInfoText = "Text¶ÔÏó×ø±ê²»ÕýÈ·¡£" + CatchErrorInfo(); WriteLog(sInfoText); m_lUnReadEntityNum++; } } } else { esriGeometryType shapeType; pShape->get_GeometryType(&shapeType); if (shapeType == esriGeometryPoint) //µã { hr = m_pPointFeatureBuffer->putref_Shape(pShape); if (SUCCEEDED(hr)) { AddBaseAttributes(pEnt, "Point", m_pPointFeatureBuffer); //±àÂë¶ÔÕÕ if (CompareCodes(m_pPointFeatureBuffer)) { PutExtendAttribsValue(m_pPointFeatureBuffer, pEnt->xData()); hr = m_pPointFeatureCursor->InsertFeature(m_pPointFeatureBuffer, &OID); if (FAILED(hr)) { sInfoText = "Point¶ÔÏóдÈëµ½PGDBʧ°Ü." + CatchErrorInfo(); WriteLog(sInfoText); m_lUnReadEntityNum++; } } } else { sInfoText = "Point¶ÔÏó×ø±ê²»ÕýÈ·." + CatchErrorInfo(); WriteLog(sInfoText); m_lUnReadEntityNum++; } if (strcmp(pEnt->isA()->name(), "AcDbBlockReference") == 0) m_lBlockNum++; } else if (shapeType == esriGeometryPolyline) //Ïß { hr = m_pLineFeatureBuffer->putref_Shape(pShape); if (SUCCEEDED(hr)) { AddBaseAttributes(pEnt, "Line", m_pLineFeatureBuffer); CString sDwgLayer; sDwgLayer.Format("%s", pEnt->layer().c_str()); if (CompareCodes(m_pLineFeatureBuffer)) { PutExtendAttribsValue(m_pLineFeatureBuffer, pEnt->xData()); hr = m_pLineFeatureCursor->InsertFeature(m_pLineFeatureBuffer, &OID); if (FAILED(hr)) { IFieldsPtr pFlds; m_pLineFeatureBuffer->get_Fields(&pFlds); long numFields; pFlds->get_FieldCount(&numFields); for (int t = 0; t < numFields; t++) { CComVariant tVal; IFieldPtr pFld; pFlds->get_Field(t, &pFld); CComBSTR bsName; pFld->get_Name(&bsName); m_pLineFeatureBuffer->get_Value(t, &tVal); } sInfoText = "Line¶ÔÏóдÈëµ½PGDBʧ°Ü." + CatchErrorInfo(); WriteLog(sInfoText); m_lUnReadEntityNum++; } } } else { sInfoText = "Line¶ÔÏó×ø±ê²»ÕýÈ·." + CatchErrorInfo(); WriteLog(sInfoText); m_lUnReadEntityNum++; } // Èç¹û±ÕºÏ¾ÍÔÙÉú³ÉÃæ VARIANT_BOOL isclosed; IPolylinePtr pPolyline(CLSID_Polyline); pPolyline = pShape; pPolyline->get_IsClosed(&isclosed); if (isclosed && m_IsLine2Polygon) { IPolygonPtr pPolygon(CLSID_Polygon); ((ISegmentCollectionPtr) pPolygon)->AddSegmentCollection((ISegmentCollectionPtr) pPolyline); IAreaPtr pArea = (IAreaPtr)pPolygon; double dArea = 0.0; pArea->get_Area(&dArea); if (dArea < 0.0) { pPolygon->ReverseOrientation(); } hr = m_pPolygonFeatureBuffer->putref_Shape((IGeometryPtr)pPolygon); if (SUCCEEDED(hr)) { AddBaseAttributes(pEnt, "Polygon", m_pPolygonFeatureBuffer); //±àÂë¶ÔÕÕ if (CompareCodes(m_pPolygonFeatureBuffer)) { //¹Ò½ÓÀ©Õ¹ÊôÐÔ PutExtendAttribsValue(m_pPolygonFeatureBuffer, pEnt->xData()); hr = m_pPolygonFeatureCursor->InsertFeature(m_pPolygonFeatureBuffer, &OID); if (FAILED(hr)) { sInfoText = "Polygon¶ÔÏóдÈëµ½PGDBʧ°Ü." + CatchErrorInfo(); WriteLog(sInfoText); } } } else { sInfoText = "Polyline¶ÔÏó×ø±ê²»ÕýÈ·." + CatchErrorInfo(); WriteLog(sInfoText); } } } else if (shapeType == esriGeometryPolygon) //Ãæ¡¢Ìî³ä { if(m_IsReadPolygon) { IPolygonPtr pPolygon(CLSID_Polygon); pPolygon = pShape; IAreaPtr pArea = (IAreaPtr)pPolygon; double dArea = 0.0; pArea->get_Area(&dArea); if (dArea < 0.0) { pPolygon->ReverseOrientation(); } hr = m_pPolygonFeatureBuffer->putref_Shape((IGeometryPtr)pPolygon); if (SUCCEEDED(hr)) { AddBaseAttributes(pEnt, "Polygon", m_pPolygonFeatureBuffer); PutExtendAttribsValue(m_pPolygonFeatureBuffer, pEnt->xData()); hr = m_pPolygonFeatureCursor->InsertFeature(m_pPolygonFeatureBuffer, &OID); if (FAILED(hr)) { sInfoText = "Polygon¶ÔÏóдÈëµ½PGDBʧ°Ü." + CatchErrorInfo(); WriteLog(sInfoText); m_lUnReadEntityNum++; } } else { sInfoText = "Polygon¶ÔÏó×ø±ê²»ÕýÈ·." + CatchErrorInfo(); WriteLog(sInfoText); m_lUnReadEntityNum++; } } } else { sInfoText.Format("%sͼ²ãÖÐHandleֵΪ:%s µÄÒªËØÎÞ·¨´¦Àí.", pEnt->layer().c_str(), szEntityHandle); WriteLog(sInfoText); //ÎÞ·¨Ê¶±ð¼ÆÊý¼Ó1 m_lUnReadEntityNum++; } } //¶ÁÈ¡À©Õ¹ÊôÐÔµ½À©Õ¹ÊôÐÔ±í ReadExtendAttribs(pEnt->xData(), szEntityHandle); } } //¶ÁCADÎļþ void XDWGReader::ReadBlock(OdDbDatabase* pDb) { // Open ModelSpace OdDbBlockTableRecordPtr pBlock = pDb->getModelSpaceId().safeOpenObject(); // ³õʼ»¯ m_lBlockNum = 0; m_bn = -1; m_lEntityNum = 0; //ÎÞ·¨¶ÁÈ¡µÄʵÌå¸öÊý m_lUnReadEntityNum = 0; m_vID = 0; if (m_StepNum < 0) m_StepNum = 5000; // Get an entity iterator OdDbObjectIteratorPtr pEntIter = pBlock->newIterator(); for (; !pEntIter->done(); pEntIter->step()) { m_lEntityNum++; } //É趨½ø¶ÈÌõ·¶Î§ if (m_pProgressBar) { m_pProgressBar->SetRange(0, m_lEntityNum); m_pProgressBar->SetPos(0); } pEntIter.release(); // For each entity in the block pEntIter = pBlock->newIterator(); int iReadCount = 0; for (; !pEntIter->done(); pEntIter->step()) { try { ReadEntity(pEntIter->objectId()); } catch (...) { char szEntityHandle[50] = {0}; pEntIter->objectId().getHandle().getIntoAsciiBuffer(szEntityHandle); CString sErr; sErr.Format("¶ÁÈ¡HandleΪ%sµÄʵÌå³öÏÖÒì³£.", szEntityHandle); WriteLog(sErr); } //É趨½ø¶ÈÌõ²½³¤ if (m_pProgressBar) { m_pProgressBar->StepIt(); } if (++iReadCount % m_StepNum == 0) { if (m_pPointFeatureCursor) m_pPointFeatureCursor->Flush(); if (m_pTextFeatureCursor) m_pTextFeatureCursor->Flush(); if (m_pLineFeatureCursor) m_pLineFeatureCursor->Flush(); if (m_pAnnoFeatureCursor) m_pAnnoFeatureCursor->Flush(); if (m_pPolygonFeatureCursor) m_pPolygonFeatureCursor->Flush(); if (m_pExtentTableRowCursor) m_pExtentTableRowCursor->Flush(); } } if (m_pPointFeatureCursor) m_pPointFeatureCursor->Flush(); if (m_pTextFeatureCursor) m_pTextFeatureCursor->Flush(); if (m_pLineFeatureCursor) m_pLineFeatureCursor->Flush(); if (m_pAnnoFeatureCursor) m_pAnnoFeatureCursor->Flush(); if (m_pPolygonFeatureCursor) m_pPolygonFeatureCursor->Flush(); if (m_pExtentTableRowCursor) m_pExtentTableRowCursor->Flush(); pEntIter.release(); CString sResult; sResult.Format("´¦ÀíÒªËØ×ÜÊý:%d", m_lEntityNum - m_lUnReadEntityNum); WriteLog(sResult); } // arcgis Ïà¹Øº¯Êý HRESULT XDWGReader::AddBaseAttributes(OdDbEntity* pEnt, LPCTSTR strEnType, IFeatureBuffer*& pFeatureBuffer) { long lindex; int ival ; CString strval; IFieldsPtr ipFields; char buff[20]; OdDbHandle hTmp; hTmp = pEnt->getDbHandle(); hTmp.getIntoAsciiBuffer(buff); if (pFeatureBuffer == NULL) return S_FALSE; pFeatureBuffer->get_Fields(&ipFields); //µÃµ½esri¼¸ºÎÀàÐÍ CComBSTR bsStr; CComVariant vtVal; bsStr = g_szEntityType; ipFields->FindField(bsStr, &lindex); vtVal = strEnType; pFeatureBuffer->put_Value(lindex, vtVal); //µÃµ½dwg¼¸ºÎÀàÐÍ bsStr = "DwgGeometry"; ipFields->FindField(bsStr, &lindex); vtVal = pEnt->isA()->name(); pFeatureBuffer->put_Value(lindex, vtVal); // µÃµ½dwgʵÌå±àºÅ bsStr = "Handle"; ipFields->FindField(bsStr, &lindex); vtVal = buff; pFeatureBuffer->put_Value(lindex, vtVal); // µÃµ½dwgͼÃû£¬¼´dwgÎļþÃû¡£ÒÔÈ·±£handleΨһ bsStr = "BaseName"; ipFields->FindField(bsStr, &lindex); vtVal = m_strDwgName; pFeatureBuffer->put_Value(lindex, vtVal); // µÃµ½dwg²ãÃû bsStr = "Layer"; ipFields->FindField(bsStr, &lindex); strval.Format("%s", pEnt->layer().c_str()); strval.MakeUpper(); vtVal = strval; pFeatureBuffer->put_Value(lindex, vtVal); // TRACE("Put Layer(AddBaseAttributes): "+ strval+" \r\n"); // µÃµ½dwg·ûºÅÑÕÉ«,Ö»Äܵõ½²ãµÄÑÕÉ«£¬Ó¦¸ÃÊÇÿ¸öÒªËØµÄ bsStr = "Color"; ipFields->FindField(bsStr, &lindex); if (pEnt->colorIndex() > 255 || pEnt->colorIndex() < 1) { OdDbLayerTableRecordPtr pLayer = pEnt->layerId().safeOpenObject(); ival = pLayer->colorIndex(); } else ival = pEnt->colorIndex(); vtVal = ival; pFeatureBuffer->put_Value(lindex, vtVal); // µÃµ½ Linetype £¬¼Ç¼ÏßÐÍ bsStr = "Linetype"; ipFields->FindField(bsStr, &lindex); strval.Format("%s", pEnt->linetype().c_str()); strval.MakeUpper(); vtVal = strval; pFeatureBuffer->put_Value(lindex, vtVal); //¶ÔÏó¿É¼ûÐÔ£¨¿ÉÑ¡£©£º0 = ¿É¼û£»1 = ²»¿É¼û // kInvisible 1 kVisible 0 bsStr = "Visible"; ipFields->FindField(bsStr, &lindex); if (pEnt->visibility() == 1) { ival = 0; } else { ival = 1; } vtVal = ival; pFeatureBuffer->put_Value(lindex, vtVal); //À©Õ¹ÊôÐÔFeatureUID //bsStr = "FEATURE_UID"; //ipFields->FindField(bsStr, &lindex); //if (lindex != -1) //{ // CString sFeatureUID = ReadFeatureUID(pEnt->xData()); // vtVal = sFeatureUID; // pFeatureBuffer->put_Value(lindex, vtVal); //} vtVal.Clear(); bsStr.Empty(); return 0; } void XDWGReader::AddAttributes(LPCTSTR csFieldName, LPCTSTR csFieldValue, IFeatureBuffer*& pFeatureBuffer) { try { long lindex; IFieldsPtr ipFields; CString strval; if (pFeatureBuffer == NULL) return; pFeatureBuffer->get_Fields(&ipFields); CComBSTR bsStr = csFieldName; ipFields->FindField(bsStr, &lindex); if (lindex != -1) { CComVariant vtVal; //°Ñ»¡¶Èֵת»»Îª½Ç¶ÈÖµ if (m_bConvertAngle && (strcmp("Angle", csFieldName) == 0)) { double dRadian = atof(csFieldValue); double dAngle = dRadian * g_dAngleParam; vtVal = dAngle; } else { vtVal = csFieldValue; } HRESULT hr = pFeatureBuffer->put_Value(lindex, vtVal); vtVal.Clear(); } bsStr.Empty(); } catch (...) { CString sError; sError.Format("%s×Ö¶ÎдÈë%sֵʱ³ö´í.", csFieldName, csFieldValue); WriteLog(sError); } } void XDWGReader::CleanAllFeatureBuffers() { if (m_pAnnoFeatureBuffer) CleanFeatureBuffer(m_pAnnoFeatureBuffer); if (m_pTextFeatureBuffer) CleanFeatureBuffer(m_pTextFeatureBuffer); if (m_pLineFeatureBuffer) CleanFeatureBuffer(m_pLineFeatureBuffer); if (m_pPointFeatureBuffer) CleanFeatureBuffer(m_pPointFeatureBuffer); if (m_pPolygonFeatureBuffer) CleanFeatureBuffer(m_pPolygonFeatureBuffer); } //void XDWGReader::BlockIniAttributes() //{ // if (m_pTextFeatureBuffer) // IniBlockAttributes(m_pTextFeatureBuffer); // if (m_pLineFeatureBuffer) // IniBlockAttributes(m_pLineFeatureBuffer); // if (m_pPointFeatureBuffer) // IniBlockAttributes(m_pPointFeatureBuffer); // if (m_pPolygonFeatureBuffer) // IniBlockAttributes(m_pPolygonFeatureBuffer); //} ////////////////////////////////////////////////////////////////////////// //ÕÒ³ö²¢½â¾öÄÚ´æÐ¹Â©ÎÊÌâ by zl void XDWGReader::CleanFeatureBuffer(IFeatureBuffer* pFeatureBuffer) { if (pFeatureBuffer == NULL) return; //ÊÍ·ÅÄÚ´æ IGeometryPtr pShape; HRESULT hr = pFeatureBuffer->get_Shape(&pShape); if (SUCCEEDED(hr)) { if (pShape != NULL) { pShape->SetEmpty(); } } IFieldsPtr ipFields; long iFieldCount; VARIANT_BOOL isEditable; esriFieldType fieldType; VARIANT emptyVal; ::VariantInit(&emptyVal); CComVariant emptyStr = ""; pFeatureBuffer->get_Fields(&ipFields); ipFields->get_FieldCount(&iFieldCount); for (int i = 0; i < iFieldCount; i++) { IFieldPtr pFld; ipFields->get_Field(i, &pFld); pFld->get_Editable(&isEditable); pFld->get_Type(&fieldType); if (isEditable == VARIANT_TRUE && fieldType != esriFieldTypeGeometry) { if (fieldType == esriFieldTypeString) { pFeatureBuffer->put_Value(i, emptyStr); } else { pFeatureBuffer->put_Value(i, emptyVal); } } } } //void XDWGReader::IniBlockAttributes(IFeatureBuffer* pFeatureBuffer) //{ // long lindex; // // double dbval; // CString strval; // IFieldsPtr ipFields; // if (pFeatureBuffer == NULL) // return; // // //ÊÍ·ÅÄÚ´æ // IGeometry* pShape; // HRESULT hr = pFeatureBuffer->get_Shape(&pShape); // if (SUCCEEDED(hr)) // { // if (pShape != NULL) // { // pShape->SetEmpty(); // } // } // // // Çå¿Õ£¬·ñÔò»á±£Áôǰһ¸öµÄÊôÐÔ // pFeatureBuffer->get_Fields(&ipFields); // CComBSTR bsStr; // CComVariant vtVal; // bsStr = "Thickness"; // ipFields->FindField(bsStr, &lindex); // if (lindex != -1) // { // vtVal = 0; // pFeatureBuffer->put_Value(lindex, vtVal); // } // // bsStr = "Scale"; // ipFields->FindField(bsStr, &lindex); // if (lindex != -1) // { // vtVal = 0; // pFeatureBuffer->put_Value(lindex, vtVal); // } // // bsStr = "Angle"; // ipFields->FindField(bsStr, &lindex); // if (lindex != -1) // { // vtVal = 0; // pFeatureBuffer->put_Value(lindex, vtVal); // } // // bsStr = "Elevation"; // ipFields->FindField(bsStr, &lindex); // if (lindex != -1) // { // vtVal = 0; // pFeatureBuffer->put_Value(lindex, vtVal); // } // // bsStr = "Width"; // ipFields->FindField(bsStr, &lindex); // if (lindex != -1) // { // vtVal = 0; // pFeatureBuffer->put_Value(lindex, vtVal); // } // // bsStr.Empty(); // // //IniExtraAttributes(pFeatureBuffer, ipFields); // // return; //} //void XDWGReader::OpenLogFile() //{ // //if (m_pLogRec != NULL) // //{ // // WinExec("Notepad.exe " + m_sLogFilePath, SW_SHOW); // //} // // //if (m_LogList.GetCount() > 0) // //{ // // COleDateTime dtCur = COleDateTime::GetCurrentTime(); // // CString sName = dtCur.Format("%y%m%d_%H%M%S"); // // CString sLogFileName; // // sLogFileName.Format("%sDwgת»»ÈÕÖ¾_%s.log", GetLogPath(), sName); // // // CStdioFile f3(sLogFileName, CFile::modeCreate | CFile::modeWrite | CFile::typeText); // // for (POSITION pos = m_LogList.GetHeadPosition(); pos != NULL;) // // { // // f3.WriteString(m_LogList.GetNext(pos) + "\n"); // // } // // f3.Close(); // // WinExec("Notepad.exe " + sLogFileName, SW_SHOW); // // m_LogList.RemoveAll(); // //} //} CString XDWGReader::CatchErrorInfo() { IErrorInfoPtr ipError; CComBSTR bsStr; CString sError; ::GetErrorInfo(0, &ipError); if (ipError) { ipError->GetDescription(&bsStr); sError = bsStr; } CString sRetErr; sRetErr.Format("¶ÁÈ¡HandleֵΪ:%s µÄ¶ÔÏóʱ³ö´í.´íÎóÔ­Òò:%s", m_sEntityHandle, sError); return sRetErr; } HRESULT XDWGReader::CreateDwgPointFields(ISpatialReference* ipSRef, IFields** ppfields) { IFieldsPtr ipFields; ipFields.CreateInstance(CLSID_Fields); IFieldsEditPtr ipFieldsEdit(ipFields); IFieldPtr ipField; ipField.CreateInstance(CLSID_Field); IFieldEditPtr ipFieldEdit(ipField); // create the geometry field IGeometryDefPtr ipGeomDef(CLSID_GeometryDef); IGeometryDefEditPtr ipGeomDefEdit(ipGeomDef); // assign the geometry definiton properties. ipGeomDefEdit->put_GeometryType(esriGeometryPoint); ipGeomDefEdit->put_GridCount(1); //double dGridSize = 1000; //VARIANT_BOOL bhasXY; //ipSRef->HasXYPrecision(&bhasXY); //if (bhasXY) //{ // double xmin, ymin, xmax, ymax, dArea; // ipSRef->GetDomain(&xmin, &xmax, &ymin, &ymax); // dArea = (xmax - xmin) * (ymax - ymin); // dGridSize = sqrt(dArea / 100); //} //if (dGridSize <= 0) // dGridSize = 1000; ipGeomDefEdit->put_GridSize(0, DEFAULT_GIS_GRID_SIZE); ipGeomDefEdit->put_AvgNumPoints(2); ipGeomDefEdit->put_HasM(VARIANT_FALSE); ipGeomDefEdit->put_HasZ(VARIANT_FALSE); ipGeomDefEdit->putref_SpatialReference(ipSRef); ipFieldEdit->put_Name(CComBSTR(L"SHAPE")); ipFieldEdit->put_AliasName(CComBSTR(L"SHAPE")); ipFieldEdit->put_Type(esriFieldTypeGeometry); ipFieldEdit->putref_GeometryDef(ipGeomDef); ipFieldsEdit->AddField(ipField); // create the object id field ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"OBJECTID")); ipFieldEdit->put_AliasName(CComBSTR(L"OBJECT ID")); ipFieldEdit->put_Type(esriFieldTypeOID); ipFieldsEdit->AddField(ipField); // ´´½¨ Entity £¬¼Ç¼esriʵÌåÀàÐÍ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(g_szEntityType)); ipFieldEdit->put_AliasName(CComBSTR(g_szEntityType)); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldsEdit->AddField(ipField); // ´´½¨ DwgGeometry £¬¼Ç¼DWGʵÌåÀàÐÍ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"DwgGeometry")); ipFieldEdit->put_AliasName(CComBSTR(L"DwgGeometry")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldsEdit->AddField(ipField); // ´´½¨ Handle £¬¼Ç¼DWGʵÌå±àºÅ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Handle")); ipFieldEdit->put_AliasName(CComBSTR(L"Handle")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ BaseName £¬¼Ç¼DWGʵÌå²ãÃû¼´DWGÎļþÃû ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"BaseName")); ipFieldEdit->put_AliasName(CComBSTR(L"BaseName")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(250); ipFieldsEdit->AddField(ipField); // ´´½¨ Layer £¬¼Ç¼DWGʵÌå²ãÃû ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Layer")); ipFieldEdit->put_AliasName(CComBSTR(L"Layer")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(250); ipFieldsEdit->AddField(ipField); // ´´½¨ Color £¬¼Ç¼DWGʵÌå·ûºÅÑÕÉ« ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Color")); ipFieldEdit->put_AliasName(CComBSTR(L"Color")); ipFieldEdit->put_Type(esriFieldTypeInteger); ipFieldsEdit->AddField(ipField); // ´´½¨ Linetype £¬¼Ç¼ÏßÐÍ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Linetype")); ipFieldEdit->put_AliasName(CComBSTR(L"Linetype")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ Thickness £¬¼Ç¼DWGʵÌåºñ¶È ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Thickness")); ipFieldEdit->put_AliasName(CComBSTR(L"Thickness")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ Scale £¬¼Ç¼DWGʵÌå·ûºÅ±ÈÀý´óС ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Scale")); ipFieldEdit->put_AliasName(CComBSTR(L"Scale")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ Elevation £¬¼Ç¼DWGʵÌå¸ß³ÌÖµ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Elevation")); ipFieldEdit->put_AliasName(CComBSTR(L"Elevation")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ Blockname £¬¼Ç¼BlockÃû×Ö ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Blockname")); ipFieldEdit->put_AliasName(CComBSTR(L"Blockname")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ Blocknumber £¬¼Ç¼ÿ¸öBlock±àºÅ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Blocknumber")); ipFieldEdit->put_AliasName(CComBSTR(L"Blocknumber")); ipFieldEdit->put_Type(esriFieldTypeInteger); ipFieldsEdit->AddField(ipField); // ´´½¨ Angle £¬¼Ç¼DWGʵÌåÐýת½Ç¶È ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Angle")); ipFieldEdit->put_AliasName(CComBSTR(L"Angle")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ Visible £¬¼Ç¼DWGʵÌåÊÇ·ñ¿É¼û£¬0²»¿É¼û£¬1¿É¼û ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Visible")); ipFieldEdit->put_AliasName(CComBSTR(L"Visible")); ipFieldEdit->put_Type(esriFieldTypeInteger); ipFieldsEdit->AddField(ipField); *ppfields = ipFields.Detach(); return 0; } HRESULT XDWGReader::CreateDwgLineFields(ISpatialReference* ipSRef, IFields** ppfields) { IFieldsPtr ipFields; ipFields.CreateInstance(CLSID_Fields); IFieldsEditPtr ipFieldsEdit(ipFields); IFieldPtr ipField; ipField.CreateInstance(CLSID_Field); IFieldEditPtr ipFieldEdit(ipField); // create the geometry field IGeometryDefPtr ipGeomDef(CLSID_GeometryDef); IGeometryDefEditPtr ipGeomDefEdit(ipGeomDef); // assign the geometry definiton properties. ipGeomDefEdit->put_GeometryType(esriGeometryPolyline); ipGeomDefEdit->put_GridCount(1); //double dGridSize = 1000; //VARIANT_BOOL bhasXY; //ipSRef->HasXYPrecision(&bhasXY); //if (bhasXY) //{ // double xmin, ymin, xmax, ymax, dArea; // ipSRef->GetDomain(&xmin, &xmax, &ymin, &ymax); // dArea = (xmax - xmin) * (ymax - ymin); // dGridSize = sqrt(dArea / 100); //} //if (dGridSize <= 0) // dGridSize = 1000; ipGeomDefEdit->put_GridSize(0, DEFAULT_GIS_GRID_SIZE); ipGeomDefEdit->put_AvgNumPoints(2); ipGeomDefEdit->put_HasM(VARIANT_FALSE); ipGeomDefEdit->put_HasZ(VARIANT_FALSE); ipGeomDefEdit->putref_SpatialReference(ipSRef); ipFieldEdit->put_Name(CComBSTR(L"SHAPE")); ipFieldEdit->put_AliasName(CComBSTR(L"SHAPE")); ipFieldEdit->put_Type(esriFieldTypeGeometry); ipFieldEdit->putref_GeometryDef(ipGeomDef); ipFieldsEdit->AddField(ipField); // create the object id field ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"OBJECTID")); ipFieldEdit->put_AliasName(CComBSTR(L"OBJECT ID")); ipFieldEdit->put_Type(esriFieldTypeOID); ipFieldsEdit->AddField(ipField); // ´´½¨ Entity £¬¼Ç¼esriʵÌåÀàÐÍ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(g_szEntityType)); ipFieldEdit->put_AliasName(CComBSTR(g_szEntityType)); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldsEdit->AddField(ipField); // ´´½¨ DwgGeometry £¬¼Ç¼DWGʵÌåÀàÐÍ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"DwgGeometry")); ipFieldEdit->put_AliasName(CComBSTR(L"DwgGeometry")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldsEdit->AddField(ipField); // ´´½¨ Handle £¬¼Ç¼DWGʵÌå±àºÅ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Handle")); ipFieldEdit->put_AliasName(CComBSTR(L"Handle")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ BaseName £¬¼Ç¼DWGʵÌå²ãÃû¼´DWGÎļþÃû ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"BaseName")); ipFieldEdit->put_AliasName(CComBSTR(L"BaseName")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(250); ipFieldsEdit->AddField(ipField); // ´´½¨ Layer £¬¼Ç¼DWGʵÌå²ãÃû ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Layer")); ipFieldEdit->put_AliasName(CComBSTR(L"Layer")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(250); ipFieldsEdit->AddField(ipField); // ´´½¨ Color £¬¼Ç¼DWGÏßʵÌåÑÕÉ« ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Color")); ipFieldEdit->put_AliasName(CComBSTR(L"Color")); ipFieldEdit->put_Type(esriFieldTypeInteger); ipFieldsEdit->AddField(ipField); // ´´½¨ Linetype £¬¼Ç¼DWGÏßʵÌåÏßÐÍÃû ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Linetype")); ipFieldEdit->put_AliasName(CComBSTR(L"Linetype")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ Elevation £¬¼Ç¼DWGʵÌå¸ß³ÌÖµ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Elevation")); ipFieldEdit->put_AliasName(CComBSTR(L"Elevation")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ Thickness £¬¼Ç¼DWGʵÌåºñ¶È ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Thickness")); ipFieldEdit->put_AliasName(CComBSTR(L"Thickness")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ Width £¬¼Ç¼DWGʵÌåÏß¿í ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Width")); ipFieldEdit->put_AliasName(CComBSTR(L"Width")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ Blockname £¬¼Ç¼BlockÃû×Ö ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Blockname")); ipFieldEdit->put_AliasName(CComBSTR(L"Blockname")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ Blocknumber £¬¼Ç¼ÿ¸öBlock±àºÅ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Blocknumber")); ipFieldEdit->put_AliasName(CComBSTR(L"Blocknumber")); ipFieldEdit->put_Type(esriFieldTypeInteger); ipFieldsEdit->AddField(ipField); // ´´½¨ Visible £¬¼Ç¼DWGʵÌåÊÇ·ñ¿É¼û£¬0²»¿É¼û£¬1¿É¼û ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Visible")); ipFieldEdit->put_AliasName(CComBSTR(L"Visible")); ipFieldEdit->put_Type(esriFieldTypeInteger); ipFieldsEdit->AddField(ipField); *ppfields = ipFields.Detach(); return 0; } HRESULT XDWGReader::CreateDwgPolygonFields(ISpatialReference* ipSRef, IFields** ppfields) { IFieldsPtr ipFields; ipFields.CreateInstance(CLSID_Fields); IFieldsEditPtr ipFieldsEdit(ipFields); IFieldPtr ipField; ipField.CreateInstance(CLSID_Field); IFieldEditPtr ipFieldEdit(ipField); ipFieldEdit->put_Name(CComBSTR(L"SHAPE")); ipFieldEdit->put_Type(esriFieldTypeGeometry); // create the geometry field IGeometryDefPtr ipGeomDef(CLSID_GeometryDef); IGeometryDefEditPtr ipGeomDefEdit; ipGeomDefEdit = ipGeomDef; // assign the geometry definiton properties. ipGeomDefEdit->put_GeometryType(esriGeometryPolygon); ipGeomDefEdit->put_GridCount(1); ipGeomDefEdit->put_AvgNumPoints(2); ipGeomDefEdit->put_HasM(VARIANT_FALSE); ipGeomDefEdit->put_HasZ(VARIANT_FALSE); //double dGridSize = 1000; //VARIANT_BOOL bhasXY; //ipSRef->HasXYPrecision(&bhasXY); //if (bhasXY) //{ // double xmin, ymin, xmax, ymax, dArea; // ipSRef->GetDomain(&xmin, &xmax, &ymin, &ymax); // dArea = (xmax - xmin) * (ymax - ymin); // dGridSize = sqrt(dArea / 100); //} //if (dGridSize <= 0) // dGridSize = 1000; ipGeomDefEdit->put_GridSize(0, DEFAULT_GIS_GRID_SIZE); ipGeomDefEdit->putref_SpatialReference(ipSRef); ipFieldEdit->putref_GeometryDef(ipGeomDef); ipFieldsEdit->AddField(ipField); // create the object id field ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"OBJECTID")); ipFieldEdit->put_AliasName(CComBSTR(L"OBJECT ID")); ipFieldEdit->put_Type(esriFieldTypeOID); ipFieldsEdit->AddField(ipField); // ´´½¨ Entity £¬¼Ç¼esriʵÌåÀàÐÍ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(g_szEntityType)); ipFieldEdit->put_AliasName(CComBSTR(g_szEntityType)); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldsEdit->AddField(ipField); // ´´½¨ DwgGeometry £¬¼Ç¼DWGʵÌåÀàÐÍ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"DwgGeometry")); ipFieldEdit->put_AliasName(CComBSTR(L"DwgGeometry")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldsEdit->AddField(ipField); // ´´½¨ Handle £¬¼Ç¼DWGʵÌå±àºÅ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Handle")); ipFieldEdit->put_AliasName(CComBSTR(L"Handle")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ BaseName £¬¼Ç¼DWGʵÌå²ãÃû¼´DWGÎļþÃû ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"BaseName")); ipFieldEdit->put_AliasName(CComBSTR(L"BaseName")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(250); ipFieldsEdit->AddField(ipField); // ´´½¨ Layer £¬¼Ç¼DWGʵÌå²ãÃû ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Layer")); ipFieldEdit->put_AliasName(CComBSTR(L"Layer")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(250); ipFieldsEdit->AddField(ipField); // ´´½¨ Color £¬¼Ç¼DWGÏßʵÌåÑÕÉ« ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Color")); ipFieldEdit->put_AliasName(CComBSTR(L"Color")); ipFieldEdit->put_Type(esriFieldTypeInteger); ipFieldsEdit->AddField(ipField); // ´´½¨ Linetype £¬¼Ç¼DWGÏßʵÌåÏßÐÍÃû ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Linetype")); ipFieldEdit->put_AliasName(CComBSTR(L"Linetype")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ Elevation £¬¼Ç¼DWGʵÌå¸ß³ÌÖµ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Elevation")); ipFieldEdit->put_AliasName(CComBSTR(L"Elevation")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ Thickness £¬¼Ç¼DWGʵÌåºñ¶È ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Thickness")); ipFieldEdit->put_AliasName(CComBSTR(L"Thickness")); //ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ Width £¬¼Ç¼DWGʵÌåÏß¿í ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Width")); ipFieldEdit->put_AliasName(CComBSTR(L"Width")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ Blockname £¬¼Ç¼BlockÃû×Ö ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Blockname")); ipFieldEdit->put_AliasName(CComBSTR(L"Blockname")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ Blocknumber £¬¼Ç¼ÿ¸öBlock±àºÅ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Blocknumber")); ipFieldEdit->put_AliasName(CComBSTR(L"Blocknumber")); ipFieldEdit->put_Type(esriFieldTypeInteger); ipFieldsEdit->AddField(ipField); // ´´½¨ Visible £¬¼Ç¼DWGʵÌåÊÇ·ñ¿É¼û£¬0²»¿É¼û£¬1¿É¼û ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Visible")); ipFieldEdit->put_AliasName(CComBSTR(L"Visible")); ipFieldEdit->put_Type(esriFieldTypeInteger); ipFieldsEdit->AddField(ipField); *ppfields = ipFields.Detach(); return 0; } HRESULT XDWGReader::CreateDwgTextPointFields(ISpatialReference* ipSRef, IFields** ppfields) { IFieldsPtr ipFields; ipFields.CreateInstance(CLSID_Fields); IFieldsEditPtr ipFieldsEdit(ipFields); IFieldPtr ipField; ipField.CreateInstance(CLSID_Field); IFieldEditPtr ipFieldEdit(ipField); // create the geometry field IGeometryDefPtr ipGeomDef(CLSID_GeometryDef); IGeometryDefEditPtr ipGeomDefEdit(ipGeomDef); // assign the geometry definiton properties. ipGeomDefEdit->put_GeometryType(esriGeometryPoint); ipGeomDefEdit->put_GridCount(1); //double dGridSize = 1000; //VARIANT_BOOL bhasXY; //ipSRef->HasXYPrecision(&bhasXY); //if (bhasXY) //{ // double xmin, ymin, xmax, ymax, dArea; // ipSRef->GetDomain(&xmin, &xmax, &ymin, &ymax); // dArea = (xmax - xmin) * (ymax - ymin); // dGridSize = sqrt(dArea / 100); //} //if (dGridSize <= 0) // dGridSize = 1000; ipGeomDefEdit->put_GridSize(0, DEFAULT_GIS_GRID_SIZE); ipGeomDefEdit->put_AvgNumPoints(2); ipGeomDefEdit->put_HasM(VARIANT_FALSE); ipGeomDefEdit->put_HasZ(VARIANT_FALSE); ipGeomDefEdit->putref_SpatialReference(ipSRef); ipFieldEdit->put_Name(CComBSTR(L"SHAPE")); ipFieldEdit->put_AliasName(CComBSTR(L"SHAPE")); ipFieldEdit->put_Type(esriFieldTypeGeometry); ipFieldEdit->putref_GeometryDef(ipGeomDef); ipFieldsEdit->AddField(ipField); // create the object id field ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"OBJECTID")); ipFieldEdit->put_AliasName(CComBSTR(L"OBJECT ID")); ipFieldEdit->put_Type(esriFieldTypeOID); ipFieldsEdit->AddField(ipField); // ´´½¨ Entity £¬¼Ç¼esriʵÌåÀàÐÍ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(g_szEntityType)); ipFieldEdit->put_AliasName(CComBSTR(g_szEntityType)); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldsEdit->AddField(ipField); // ´´½¨ DwgGeometry £¬¼Ç¼DWGʵÌåÀàÐÍ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"DwgGeometry")); ipFieldEdit->put_AliasName(CComBSTR(L"DwgGeometry")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldsEdit->AddField(ipField); // ´´½¨ Handle £¬¼Ç¼DWGʵÌå±àºÅ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Handle")); ipFieldEdit->put_AliasName(CComBSTR(L"Handle")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ BaseName £¬¼Ç¼DWGʵÌå²ãÃû¼´DWGÎļþÃû ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"BaseName")); ipFieldEdit->put_AliasName(CComBSTR(L"BaseName")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(250); ipFieldsEdit->AddField(ipField); // ´´½¨ Layer £¬¼Ç¼DWGʵÌå²ãÃû ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Layer")); ipFieldEdit->put_AliasName(CComBSTR(L"Layer")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(250); ipFieldsEdit->AddField(ipField); // ´´½¨ Color £¬¼Ç¼DWGÏßʵÌåÑÕÉ« ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Color")); ipFieldEdit->put_AliasName(CComBSTR(L"Color")); ipFieldEdit->put_Type(esriFieldTypeInteger); ipFieldsEdit->AddField(ipField); // ´´½¨ Linetype £¬¼Ç¼DWGÏßʵÌåÏßÐÍÃû ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Linetype")); ipFieldEdit->put_AliasName(CComBSTR(L"Linetype")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ Thickness £¬¼Ç¼DWGʵÌåºñ¶È ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Thickness")); ipFieldEdit->put_AliasName(CComBSTR(L"Thickness")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ Blockname £¬¼Ç¼BlockÃû×Ö ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Blockname")); ipFieldEdit->put_AliasName(CComBSTR(L"Blockname")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ Blocknumber £¬¼Ç¼ÿ¸öBlock±àºÅ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Blocknumber")); ipFieldEdit->put_AliasName(CComBSTR(L"Blocknumber")); ipFieldEdit->put_Type(esriFieldTypeInteger); ipFieldsEdit->AddField(ipField); // ´´½¨ Angle £¬¼Ç¼DWGÎÄ×ÖʵÌåÐýת½Ç¶È ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Angle")); ipFieldEdit->put_AliasName(CComBSTR(L"Angle")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ TextString £¬¼Ç¼ DWGÎÄ×ÖʵÌå×ÖÄÚÈÝ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"TextString")); ipFieldEdit->put_AliasName(CComBSTR(L"TextString")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(255); ipFieldsEdit->AddField(ipField); // ´´½¨ Height £¬¼Ç¼DWGÎÄ×ÖʵÌå×Ö¸ß ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Height")); ipFieldEdit->put_AliasName(CComBSTR(L"Height")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ WidthFactor £¬ // is an additional scaling applied in the x direction which makes the text either fatter or thinner. ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"WidthFactor")); ipFieldEdit->put_AliasName(CComBSTR(L"WidthFactor")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ Oblique £¬Çãб½Ç¶È // is an obliquing angle to be applied to the text, which causes it to "lean" either to the right or left. ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Oblique")); ipFieldEdit->put_AliasName(CComBSTR(L"Oblique")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ VerticalMode £¬¼Ç¼DWGÎÄ×ÖʵÌå×Ö¶ÔÆë·½Ê½ // kTextBase 0 kTextBottom 1 kTextVertMid 2 kTextTop 3 ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"VtMode")); ipFieldEdit->put_AliasName(CComBSTR(L"VtMode")); ipFieldEdit->put_Type(esriFieldTypeInteger); ipFieldsEdit->AddField(ipField); // ´´½¨ HorizontalMode £¬¼Ç¼DWGÎÄ×ÖʵÌå×Ö¶ÔÆë·½Ê½ //kTextLeft 0 kTextCenter 1 kTextRight 2 kTextAlign 3 // kTextMid 4 kTextFit 5 ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"HzMode")); ipFieldEdit->put_AliasName(CComBSTR(L"HzMode")); ipFieldEdit->put_Type(esriFieldTypeInteger); ipFieldsEdit->AddField(ipField); // ´´½¨ AlignmentPointX ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"AlignPtX")); ipFieldEdit->put_AliasName(CComBSTR(L"AlignPtX")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ AlignmentPointY ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"AlignPtY")); ipFieldEdit->put_AliasName(CComBSTR(L"AlignPtY")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ BoundingPointMinX ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"PtMinX")); ipFieldEdit->put_AliasName(CComBSTR(L"PtMinX")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ BoundingPointMinY ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"PtMinY")); ipFieldEdit->put_AliasName(CComBSTR(L"PtMinY")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ BoundingPointMaxX ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"PtMaxX")); ipFieldEdit->put_AliasName(CComBSTR(L"PtMaxX")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ BoundingPointMaxY ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"PtMaxY")); ipFieldEdit->put_AliasName(CComBSTR(L"PtMaxY")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ BigFontname £¬¼Ç¼ DWGÎÄ×ÖʵÌå×ÖÌå ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"BigFontname")); ipFieldEdit->put_AliasName(CComBSTR(L"BigFontname")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ ShapeFilename £¬¼Ç¼ DWGÎÄ×ÖʵÌå×ÖÌå ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"ShapeFilename")); ipFieldEdit->put_AliasName(CComBSTR(L"ShapeFilename")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ ShapeName £¬¼Ç¼ DWGÎÄ×ÖʵÌå×ÖÌå ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"ShapeName")); ipFieldEdit->put_AliasName(CComBSTR(L"ShapeName")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ Visible £¬¼Ç¼DWGʵÌåÊÇ·ñ¿É¼û£¬0²»¿É¼û£¬1¿É¼û ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Visible")); ipFieldEdit->put_AliasName(CComBSTR(L"Visible")); ipFieldEdit->put_Type(esriFieldTypeInteger); ipFieldsEdit->AddField(ipField); *ppfields = ipFields.Detach(); return 0; } ////////////////////////////////////////////////////////////////////////// //¼òÒªÃèÊö : ´´½¨×¢¼Çͼ²ã×Ö¶Î //ÊäÈë²ÎÊý : //·µ »Ø Öµ : //ÐÞ¸ÄÈÕÖ¾ : ////////////////////////////////////////////////////////////////////////// HRESULT XDWGReader::CreateDwgAnnotationFields(ISpatialReference* ipSRef, IFields** ppfields) { HRESULT hr; IObjectClassDescriptionPtr pOCDesc(CLSID_AnnotationFeatureClassDescription); IFieldsPtr pReqFields; pOCDesc->get_RequiredFields(&pReqFields); //ÉèÖÿռä²Î¿¼ if (ipSRef != NULL) { long numFields; pReqFields->get_FieldCount(&numFields); for (int i = 0; i < numFields; i++) { IFieldPtr pField; pReqFields->get_Field(i, &pField); esriFieldType fldType; pField->get_Type(&fldType); if (fldType == esriFieldTypeGeometry) { IFieldEditPtr pEdtField = pField; IGeometryDefPtr pGeoDef; hr = pEdtField->get_GeometryDef(&pGeoDef); IGeometryDefEditPtr pEdtGeoDef = pGeoDef; hr = pEdtGeoDef->putref_SpatialReference(ipSRef); hr = pEdtField->putref_GeometryDef(pGeoDef); break; } } } IFieldsEditPtr ipFieldsEdit = pReqFields; //´´½¨CADÎļþÖÐ×¢¼Çͼ²ã×Ö¶Î IFieldEditPtr ipFieldEdit; IFieldPtr ipField; // ´´½¨ Entity £¬¼Ç¼esriʵÌåÀàÐÍ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR("Entity_Type")); ipFieldEdit->put_AliasName(CComBSTR("Entity_Type")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldsEdit->AddField(ipField); // ´´½¨ Handle £¬¼Ç¼DWGʵÌå±àºÅ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Handle")); ipFieldEdit->put_AliasName(CComBSTR(L"Handle")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ BaseName £¬¼Ç¼DWGʵÌå²ãÃû¼´DWGÎļþÃû ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"BaseName")); ipFieldEdit->put_AliasName(CComBSTR(L"BaseName")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(250); ipFieldsEdit->AddField(ipField); // ´´½¨ Layer £¬¼Ç¼DWGʵÌå²ãÃû ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Layer")); ipFieldEdit->put_AliasName(CComBSTR(L"Layer")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(250); ipFieldsEdit->AddField(ipField); // ´´½¨ Color £¬¼Ç¼DWGʵÌå·ûºÅÑÕÉ« ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Color")); ipFieldEdit->put_AliasName(CComBSTR(L"Color")); ipFieldEdit->put_Type(esriFieldTypeInteger); ipFieldsEdit->AddField(ipField); // ´´½¨ Thickness £¬¼Ç¼DWGʵÌåºñ¶È ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Thickness")); ipFieldEdit->put_AliasName(CComBSTR(L"Thickness")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ Elevation £¬¼Ç¼DWGʵÌå¸ß³ÌÖµ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Elevation")); ipFieldEdit->put_AliasName(CComBSTR(L"Elevation")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ Height £¬¼Ç¼¸ß¶È ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Height")); ipFieldEdit->put_AliasName(CComBSTR(L"Height")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ TextStyle £¬¼Ç¼ÎÄ×ÖÑùʽ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"TextStyle")); ipFieldEdit->put_AliasName(CComBSTR(L"TextStyle")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ Oblique £¬¼Ç¼Çã½Ç ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Oblique")); ipFieldEdit->put_AliasName(CComBSTR(L"Oblique")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ AlignmentPointX ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"AlignPtX")); ipFieldEdit->put_AliasName(CComBSTR(L"AlignPtX")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ AlignmentPointY ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"AlignPtY")); ipFieldEdit->put_AliasName(CComBSTR(L"AlignPtY")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); *ppfields = ipFieldsEdit.Detach(); return 0; } /************************************************************************ ¼òÒªÃèÊö : ´´½¨À©Õ¹ÊôÐÔ±í ÊäÈë²ÎÊý : ·µ »Ø Öµ : ÐÞ¸ÄÈÕÖ¾ : ************************************************************************/ HRESULT XDWGReader::CreateExtendTable(IFeatureWorkspace* pFeatWorkspace, BSTR bstrName, ITable** pTable) { HRESULT hr; if (pFeatWorkspace == NULL) return E_FAIL; // Ö»´´½¨£ºBaseName--ͼÃû£»Handle--ÒªËØID;XDataName--À©Õ¹ÊôÐÔÃû³Æ;XDataNum--À©Õ¹ÊôÐÔ±àºÅ;XDataValue--À©Õ¹ËµÃ÷Öµ hr = pFeatWorkspace->OpenTable(bstrName, pTable); // Èç¹û´ò²»¿ªtable¾ÍÈÏΪ²»´æÔÚ¾ÍÖØ½¨table if (*pTable == NULL) { IFieldsPtr ipFields; ipFields.CreateInstance(CLSID_Fields); IFieldsEditPtr ipIndexFields; ipIndexFields.CreateInstance(CLSID_Fields); IFieldsEditPtr ipFieldsEdit = ipFields; if (ipFieldsEdit == NULL) return E_FAIL; // Add a field for the user name IFieldEditPtr ipField; hr = ipField.CreateInstance(CLSID_Field); if (FAILED(hr)) return hr; hr = ipField->put_Name(CComBSTR(L"Handle")); if (FAILED(hr)) return hr; hr = ipField->put_Type(esriFieldTypeString); if (FAILED(hr)) return hr; hr = ipField->put_Length(150); if (FAILED(hr)) return hr; hr = ipField->put_Required(VARIANT_TRUE); if (FAILED(hr)) return hr; hr = ipFieldsEdit->AddField(ipField); if (FAILED(hr)) return hr; //Ìí¼ÓË÷Òý×Ö¶Î1 hr = ipIndexFields->AddField(ipField); if (FAILED(hr)) return hr; hr = ipField.CreateInstance(CLSID_Field); if (FAILED(hr)) return hr; hr = ipField->put_Name(CComBSTR(L"BaseName")); if (FAILED(hr)) return hr; hr = ipField->put_Type(esriFieldTypeString); if (FAILED(hr)) return hr; hr = ipField->put_Length(250); if (FAILED(hr)) return hr; hr = ipField->put_Required(VARIANT_TRUE); if (FAILED(hr)) return hr; hr = ipFieldsEdit->AddField(ipField); if (FAILED(hr)) return hr; //Ìí¼ÓË÷Òý×Ö¶Î2 hr = ipIndexFields->AddField(ipField); if (FAILED(hr)) return hr; hr = ipField.CreateInstance(CLSID_Field); if (FAILED(hr)) return hr; hr = ipField->put_Name(CComBSTR(L"XDataName")); if (FAILED(hr)) return hr; hr = ipField->put_Type(esriFieldTypeString); if (FAILED(hr)) return hr; hr = ipField->put_Length(250); if (FAILED(hr)) return hr; hr = ipFieldsEdit->AddField(ipField); if (FAILED(hr)) return hr; // 2050 Ϊ×î´óÈÝÁ¿ hr = ipField.CreateInstance(CLSID_Field); if (FAILED(hr)) return hr; hr = ipField->put_Name(CComBSTR(L"XDataValue")); if (FAILED(hr)) return hr; hr = ipField->put_Type(esriFieldTypeString); if (FAILED(hr)) return hr; hr = ipField->put_Length(65535); if (FAILED(hr)) return hr; hr = ipFieldsEdit->AddField(ipField); if (FAILED(hr)) return hr; // Try to Create the table hr = pFeatWorkspace->CreateTable(bstrName, ipFields, NULL, NULL, NULL, pTable); if (FAILED(hr)) return hr; IIndexEditPtr ipIndexEdit; ipIndexEdit.CreateInstance(CLSID_Index); ipIndexEdit->putref_Fields(ipIndexFields); hr = (*pTable)->AddIndex(ipIndexEdit); if (FAILED(hr)) return hr; } return S_OK; } HRESULT XDWGReader::CreateDatasetFeatureClass(IFeatureWorkspace* pFWorkspace, IFeatureDataset* pFDS, IFields* pFields, BSTR bstrName, esriFeatureType featType, IFeatureClass*& ppFeatureClass) { if (!pFDS && !pFWorkspace) return S_FALSE; BSTR bstrConfigWord = L""; IFieldPtr ipField; CComBSTR bstrShapeFld; esriFieldType fieldType; long lNumFields; pFields->get_FieldCount(&lNumFields); for (int i = 0; i < lNumFields; i++) { pFields->get_Field(i, &ipField); ipField->get_Type(&fieldType); if (esriFieldTypeGeometry == fieldType) { ipField->get_Name(&bstrShapeFld); break; } } HRESULT hr; if (pFDS) { hr = pFDS->CreateFeatureClass(bstrName, pFields, 0, 0, featType, bstrShapeFld, 0, &ppFeatureClass); } else { // Ö±½Ó´ò¿ªFeatureClass,Èç¹û²»³É¹¦¾ÍÔÙ´´½¨ hr = pFWorkspace->OpenFeatureClass(bstrName, &ppFeatureClass); if (ppFeatureClass == NULL) hr = pFWorkspace->CreateFeatureClass(bstrName, pFields, 0, 0, featType, bstrShapeFld, 0, &ppFeatureClass); } return hr; } void XDWGReader::GetGeometryDef(IFeatureClass* pClass, IGeometryDef** pDef) { try { BSTR shapeName; pClass->get_ShapeFieldName(&shapeName); IFieldsPtr pFields; pClass->get_Fields(&pFields); long lGeomIndex; pFields->FindField(shapeName, &lGeomIndex); IFieldPtr pField; pFields->get_Field(lGeomIndex, &pField); pField->get_GeometryDef(pDef); } catch (...) { } } BOOL XDWGReader::IsResetDomain(IFeatureWorkspace* pFWorkspace, CString szFCName) { IWorkspace2Ptr iws2(pFWorkspace); VARIANT_BOOL isexist = FALSE; if (iws2) { iws2->get_NameExists(esriDTFeatureClass, CComBSTR(szFCName), &isexist); } return isexist; } void XDWGReader::ResetDomain(IFeatureWorkspace* pFWorkspace, CString szFCName, ISpatialReference* ipSRef) { IGeometryDefPtr ipGeomDef; ISpatialReferencePtr ipOldSRef; double mOldMinX, mOldMinY, mOldMaxY, mOldMaxX; double mMinX, mMinY, mMaxY, mMaxX; double mNewMinX, mNewMinY, mNewMaxY, mNewMaxX, dFX, dFY, mNewXYScale ; HRESULT hr; pFWorkspace->OpenFeatureClass(CComBSTR(szFCName), &m_pFeatClassPolygon); GetGeometryDef(m_pFeatClassPolygon, &ipGeomDef); pFWorkspace->OpenFeatureClass(CComBSTR(szFCName), &m_pFeatClassPoint); GetGeometryDef(m_pFeatClassPoint, &ipGeomDef); pFWorkspace->OpenFeatureClass(CComBSTR(szFCName), &m_pFeatClassLine); GetGeometryDef(m_pFeatClassLine, &ipGeomDef); //pFWorkspace->OpenFeatureClass(CComBSTR(szFCName), &m_pFeatClassText); //GetGeometryDef(m_pFeatClassText, &ipGeomDef); ipGeomDef->get_SpatialReference(&ipOldSRef); ipOldSRef->GetDomain(&mOldMinX, &mOldMaxX, &mOldMinY, &mOldMaxY); ipSRef->GetDomain(&mMinX, &mMaxX, &mMinY, &mMaxY); if (mMinX < mOldMinX) mNewMinX = mMinX; else mNewMinX = mOldMinX; if (mMinY < mOldMinY) mNewMinY = mMinY; else mNewMinY = mOldMinY; if (mMaxX > mOldMaxX) mNewMaxX = mMaxX; else mNewMaxX = mOldMaxX; if (mMaxY > mOldMaxY) mNewMaxY = mMaxY; else mNewMaxY = mOldMaxY; ipOldSRef->SetDomain(mNewMinX, mNewMaxX, mNewMinY, mNewMaxY); ipOldSRef->GetFalseOriginAndUnits(&dFX, &dFY, &mNewXYScale); ipOldSRef->GetDomain(&mNewMinX, &mNewMaxX, &mNewMinY, &mNewMaxY); IGeometryDefEditPtr ipGeomDefEdit(ipGeomDef); hr = ipGeomDefEdit->putref_SpatialReference(ipOldSRef); if (FAILED(hr)) { WriteLog(CatchErrorInfo()); } } // bsplineËã·¨ /********************************************************************* ²Î¿¼: n - ¿ØÖƵãÊý - 1 t - the polynomialµÈ¼¶ + 1 control - ¿ØÖƵã×ø±ê¼¯ output - Êä³öÄâºÏµã×ø±ê¼¯ num_output - Êä³öµãÊý Ìõ¼þ: n+2>t (·ñÔòÎÞÇúÏß) ¿ØÖƵã×ø±ê¼¯ºÍµãÊýÒ»Ö ·ÖÅäÊä³öµã¼¯µãÊýºÍ num_outputÒ»Ö **********************************************************************/ void XDWGReader::Bspline(int n, int t, DwgPoint* control, DwgPoint* output, int num_output) { int* u; double increment, interval; DwgPoint calcxyz; int output_index; u = new int[n + t + 1]; ComputeIntervals(u, n, t); increment = (double) (n - t + 2) / (num_output - 1); // how much parameter goes up each time interval = 0; for (output_index = 0; output_index < num_output - 1; output_index++) { ComputePoint(u, n, t, interval, control, &calcxyz); output[output_index].x = calcxyz.x; output[output_index].y = calcxyz.y; output[output_index].z = calcxyz.z; interval = interval + increment; // increment our parameter } output[num_output - 1].x = control[n].x; // put in the last DwgPoint output[num_output - 1].y = control[n].y; output[num_output - 1].z = control[n].z; delete u; } double XDWGReader::Blend(int k, int t, int* u, double v) // calculate the blending value { double value; if (t == 1) // base case for the recursion { if ((u[k] <= v) && (v < u[k + 1])) value = 1; else value = 0; } else { if ((u[k + t - 1] == u[k]) && (u[k + t] == u[k + 1])) // check for divide by zero { value = 0; } else if (u[k + t - 1] == u[k]) // if a term's denominator is zero,use just the other { value = (u[k + t] - v) / (u[k + t] - u[k + 1]) * Blend(k + 1, t - 1, u, v); } else if (u[k + t] == u[k + 1]) { value = (v - u[k]) / (u[k + t - 1] - u[k]) * Blend(k, t - 1, u, v); } else { value = (v - u[k]) / (u[k + t - 1] - u[k]) * Blend(k, t - 1, u, v) + (u[k + t] - v) / (u[k + t] - u[k + 1]) * Blend(k + 1, t - 1, u, v); } } return value; } void XDWGReader::ComputeIntervals(int* u, int n, int t) // figure out the knots { int j; for (j = 0; j <= n + t; j++) { if (j < t) u[j] = 0; else if ((t <= j) && (j <= n)) u[j] = j - t + 1; else if (j > n) u[j] = n - t + 2; // if n-t=-2 then we're screwed, everything goes to 0 } } void XDWGReader::ComputePoint(int* u, int n, int t, double v, DwgPoint* control, DwgPoint* output) { int k; double temp; // initialize the variables that will hold our outputted DwgPoint output->x = 0; output->y = 0; output->z = 0; for (k = 0; k <= n; k++) { temp = Blend(k, t, u, v); // same blend is used for each dimension coordinate output->x = output->x + (control[k]).x * temp; output->y = output->y + (control[k]).y * temp; output->z = output->z + (control[k]).z * temp; } } /************************************************************************ ¼òÒªÃèÊö : Ìí¼ÓÀ©Õ¹ÊôÐÔ×Ö¶Î ÊäÈë²ÎÊý : ·µ »Ø Öµ : ÐÞ¸ÄÈÕÖ¾ : ************************************************************************/ void XDWGReader::AddExtraFields(CStringList* pRegapps) { if (pRegapps == NULL) return; if (m_IsJoinXDataAttrs == FALSE || pRegapps->GetCount() <= 0) { return; } m_Regapps.AddTail(pRegapps); } /************************************************************************ ¼òÒªÃèÊö : ³õʼ»¯±àÂë¶ÔÕÕ±í ÊäÈë²ÎÊý : ·µ »Ø Öµ : ÐÞ¸ÄÈÕÖ¾ : ************************************************************************/ //void XDWGReader::InitCompareCodes(ITable* pCompareTable) //{ //if (pCompareTable==NULL) return; // CleanCompareCodes(); // //IFeatureWorkspacePtr ipFeatureWorkspace = API_GetSysWorkspace(); // //if (ipFeatureWorkspace == NULL) // //{ // // AfxMessageBox("´ò¿ªÏµÍ³±í³ö´í£¡", MB_ICONERROR); // // return; // //} // //ITablePtr pCompareTable; // //ipFeatureWorkspace->OpenTable(CComBSTR("CAD2GDB"), &pCompareTable); // //if (pCompareTable == NULL) // //{ // // AfxMessageBox("±àÂë¶ÔÕÕ±í²»´æÔÚ£¬ÎÞ·¨½øÐбàÂë¶ÔÕÕ¡£", MB_ICONERROR); // // return; // //} // CComBSTR bsStr; // IEsriCursorPtr ipCursor; // pCompareTable->Search(NULL, VARIANT_FALSE, &ipCursor); // if (ipCursor != NULL) // { // long lFieldIndex = -1; // IEsriRowPtr ipRow; // IFieldsPtr pFields = NULL; // ipCursor->NextRow(&ipRow); // while (ipRow != NULL) // { // CComVariant vt; // XDwg2GdbRecord* pTbRow = new XDwg2GdbRecord(); // lFieldIndex = -1; // ipRow->get_Fields(&pFields); // bsStr = "DWG_LAYER"; // pFields->FindField(bsStr, &lFieldIndex); // if (lFieldIndex != -1) // { // ipRow->get_Value(lFieldIndex, &vt); // if (vt.vt != VT_EMPTY && vt.vt != VT_NULL) // { // pTbRow->DWG_LAYER = (CString) vt.bstrVal; // } // } // bsStr = "DWG_BLOCKNAME"; // pFields->FindField(bsStr, &lFieldIndex); // if (lFieldIndex != -1) // { // ipRow->get_Value(lFieldIndex, &vt); // if (vt.vt != VT_EMPTY && vt.vt != VT_NULL) // { // pTbRow->DWG_BLOCKNAME = (CString) vt.bstrVal; // } // } // bsStr = "GDB_LAYER"; // pFields->FindField(bsStr, &lFieldIndex); // if (lFieldIndex != -1) // { // ipRow->get_Value(lFieldIndex, &vt); // if (vt.vt != VT_EMPTY && vt.vt != VT_NULL) // { // pTbRow->GDB_LAYER = (CString) vt.bstrVal; // } // } // bsStr = "YSDM"; // pFields->FindField(bsStr, &lFieldIndex); // if (lFieldIndex != -1) // { // ipRow->get_Value(lFieldIndex, &vt); // if (vt.vt != VT_EMPTY && vt.vt != VT_NULL) // { // pTbRow->YSDM = (CString) vt.bstrVal; // } // } // bsStr = "YSMC"; // pFields->FindField(bsStr, &lFieldIndex); // if (lFieldIndex != -1) // { // ipRow->get_Value(lFieldIndex, &vt); // if (vt.vt != VT_EMPTY && vt.vt != VT_NULL) // { // pTbRow->YSMC = (CString) vt.bstrVal; // } // } // ipCursor->NextRow(&ipRow); // //¼ÓÈë¶ÔÕÕÖµ // m_aryCodes.Add(pTbRow); // } // } // bsStr.Empty(); //} /************************************************************************ ¼òÒªÃèÊö : ´ÓFeatureBufferÖеõ½¸ø¶¨×Ö¶ÎÃûµÄÖµ ÊäÈë²ÎÊý : pFeatureBuffer£ºÔ´pFeatureBuffer, sFieldName£ºÐèҪȡֵµÄ×Ö¶ÎÃû ·µ »Ø Öµ : ¸Ã×Ö¶ÎÔÚFeatureBufferÖеÄÖµ ÐÞ¸ÄÈÕÖ¾ : ************************************************************************/ CString XDWGReader::GetFeatureBufferFieldValue(IFeatureBuffer*& pFeatureBuffer, CString sFieldName) { CComVariant vtFieldValue; CString sFieldValue; long lIndex; IFieldsPtr pFields; pFeatureBuffer->get_Fields(&pFields); CComBSTR bsStr = sFieldName; pFields->FindField(bsStr, &lIndex); bsStr.Empty(); if (lIndex == -1) { sFieldValue = ""; } else { pFeatureBuffer->get_Value(lIndex, &vtFieldValue); switch (vtFieldValue.vt) { case VT_EMPTY: case VT_NULL: sFieldValue = ""; break; case VT_BOOL: sFieldValue = vtFieldValue.boolVal == TRUE ? "1" : "0"; break; case VT_UI1: sFieldValue.Format("%d", vtFieldValue.bVal); break; case VT_I2: sFieldValue.Format("%d", vtFieldValue.iVal); break; case VT_I4: sFieldValue.Format("%d", vtFieldValue.lVal); break; case VT_R4: { long lVal = vtFieldValue.fltVal; sFieldValue.Format("%d", lVal); } break; case VT_R8: { long lVal = vtFieldValue.dblVal; sFieldValue.Format("%d", lVal); } break; case VT_BSTR: sFieldValue = vtFieldValue.bstrVal; break; default: sFieldValue = ""; break; } } return sFieldValue; } /************************************************************************ ¼òÒªÃèÊö : ÊäÈë²ÎÊý : ·µ »Ø Öµ : ÐÞ¸ÄÈÕÖ¾ : ************************************************************************/ //void XDWGReader::PutExtraAttributes(IFeatureBuffer*& pFeatureBuffer, XDwg2GdbRecord* pCode) //{ // HRESULT hr; // LONG lFieldIndex; // // IFieldsPtr ipFields; // pFeatureBuffer->get_Fields(&ipFields); // // // CComBSTR bsStr; // CComVariant vtVal; // // bsStr = "GDB_LAYER"; // ipFields->FindField(bsStr, &lFieldIndex); // if (lFieldIndex != -1) // { // vtVal = pCode->GDB_LAYER; // hr = pFeatureBuffer->put_Value(lFieldIndex, vtVal); // } // // bsStr = "YSDM"; // ipFields->FindField(bsStr, &lFieldIndex); // if (lFieldIndex != -1) // { // vtVal = pCode->YSDM; // hr = pFeatureBuffer->put_Value(lFieldIndex, vtVal); // } // // bsStr = "YSMC"; // ipFields->FindField(bsStr, &lFieldIndex); // if (lFieldIndex != -1) // { // vtVal = pCode->YSMC; // hr = pFeatureBuffer->put_Value(lFieldIndex, vtVal); // } // // //bsStr = "SymbolCode"; // //ipFields->FindField(bsStr, &lFieldIndex); // //if (lFieldIndex != -1) // //{ // // vtVal = pCode->SymbolCode; // // hr = pFeatureBuffer->put_Value(lFieldIndex, vtVal); // //} // // bsStr.Empty(); //} //supported by feature classes in ArcSDE and feature classes and tables in File Geodatabase. It improves performance of data loading. HRESULT XDWGReader::BeginLoadOnlyMode(IFeatureClass*& pTargetClass) { //if (pTargetClass == NULL) //{ // return S_FALSE; //} //IFeatureClassLoadPtr pClassLoad(pTargetClass); //if (pClassLoad) //{ // ISchemaLockPtr pSchemaLock(pTargetClass); // if (pSchemaLock) // { // if (SUCCEEDED(pSchemaLock->ChangeSchemaLock(esriExclusiveSchemaLock))) // { // VARIANT_BOOL bLoadOnly; // pClassLoad->get_LoadOnlyMode(&bLoadOnly); // if (!bLoadOnly) // return pClassLoad->put_LoadOnlyMode(VARIANT_TRUE); // else // return S_OK; // } // } //} //return S_FALSE; return S_OK; } HRESULT XDWGReader::EndLoadOnlyMode(IFeatureClass*& pTargetClass) { //if (pTargetClass == NULL) //{ // return S_FALSE; //} //IFeatureClassLoadPtr pClassLoad(pTargetClass); //if (pClassLoad) //{ // ISchemaLockPtr pSchemaLock(pTargetClass); // if (pSchemaLock) // { // if (SUCCEEDED(pSchemaLock->ChangeSchemaLock(esriSharedSchemaLock))) // { // VARIANT_BOOL bLoadOnly; // pClassLoad->get_LoadOnlyMode(&bLoadOnly); // if (bLoadOnly) // return pClassLoad->put_LoadOnlyMode(VARIANT_FALSE); // else // return S_OK; // } // } //} //return S_FALSE; return S_OK; } void XDWGReader::ReleaseFeatureBuffer(IFeatureBufferPtr& pFeatureBuffer) { if (pFeatureBuffer == NULL) { return; } //ÊÍ·ÅÄÚ´æ IGeometry* pShape; HRESULT hr = pFeatureBuffer->get_Shape(&pShape); if (SUCCEEDED(hr)) { if (pShape != NULL) { pShape->SetEmpty(); } } } /************************************************************************ ¼òÒªÃèÊö : ±àÂë¶ÔÕÕ ÊäÈë²ÎÊý : ·µ »Ø Öµ : ÐÞ¸ÄÈÕÖ¾ : ************************************************************************/ BOOL XDWGReader::CompareCodes(IFeatureBuffer*& pFeatureBuffer) { return TRUE; //try //{ // if (pFeatureBuffer == NULL) // return FALSE; // int iCompareCodes = m_aryCodes.GetSize(); // if (iCompareCodes <= 0) // { // return TRUE; // } // //CString sThickness = GetFeatureBufferFieldValue(pFeatureBuffer, "Thickness"); // CString sBlockname = GetFeatureBufferFieldValue(pFeatureBuffer, "Blockname"); // CString sLayer = GetFeatureBufferFieldValue(pFeatureBuffer, "Layer"); // CString sEntityType = GetFeatureBufferFieldValue(pFeatureBuffer, g_szEntityType); // //µã£±Blockname->DWG_BLOCKNAME // //µã£²Layer->DWG_LAYER // //Ïߣ¬Layer->DWG_LAYER // XDwg2GdbRecord* pDwg2GdbRecord = NULL; // IGeometryPtr pGeometry; // pFeatureBuffer->get_Shape(&pGeometry); // if (pGeometry == NULL) // { // return FALSE; // } // esriFeatureType featType; // IFeaturePtr pFeat; // pFeat = pFeatureBuffer; // if (pFeat != NULL) // { // pFeat->get_FeatureType(&featType); // } // else // { // featType = esriFTSimple; // } // //×¢¼Çͼ²ã // if (featType == esriFTAnnotation) // { // if (!sLayer.IsEmpty()) // { // for (int i = 0; i < iCompareCodes; i++) // { // pDwg2GdbRecord = m_aryCodes.GetAt(i); // if (pDwg2GdbRecord->DWG_LAYER.CompareNoCase(sLayer) == 0) // { // PutExtraAttributes(pFeatureBuffer, pDwg2GdbRecord); // return TRUE; // } // } // } // return FALSE; // } // else if (featType == esriFTSimple) //Ò»°ãͼ²ã // { // //HRESULT hr; // CComVariant OID; // esriGeometryType shapeType; // pGeometry->get_GeometryType(&shapeType); // if (shapeType == esriGeometryPoint) // { // //µã£±Blockname->DWG_BLOCKNAME // //µã£²Layer->DWG_LAYER // if (!sBlockname.IsEmpty()) // { // for (int i = 0; i < iCompareCodes; i++) // { // pDwg2GdbRecord = m_aryCodes.GetAt(i); // if (pDwg2GdbRecord->DWG_BLOCKNAME.CompareNoCase(sBlockname) == 0) // { // PutExtraAttributes(pFeatureBuffer, pDwg2GdbRecord); // return TRUE; // } // } // } // else // { // if (!sLayer.IsEmpty()) // { // for (int i = 0; i < iCompareCodes; i++) // { // pDwg2GdbRecord = m_aryCodes.GetAt(i); // if (pDwg2GdbRecord->DWG_LAYER.CompareNoCase(sLayer) == 0) // { // PutExtraAttributes(pFeatureBuffer, pDwg2GdbRecord); // return TRUE; // } // } // } // } // return FALSE; // } // else //if(shapeType == esriGeometryPolyline) // { // //Ïߣ¬Layer->DWG_LAYER // if (!sLayer.IsEmpty()) // { // for (int i = 0; i < iCompareCodes; i++) // { // pDwg2GdbRecord = m_aryCodes.GetAt(i); // if (pDwg2GdbRecord->DWG_LAYER.CompareNoCase(sLayer) == 0) // { // PutExtraAttributes(pFeatureBuffer, pDwg2GdbRecord); // return TRUE; // } // } // } // return FALSE; // } // } //} //catch (...) //{ // CString sError; // sError.Format("±àÂëת»»³ö´í¡£"); // WriteLog(sError); // return FALSE; //} //return FALSE; } /************************************************************************ ¼òÒªÃèÊö : ´´½¨×¢¼ÇÀàÐ͵ÄÒªËØÀà ÊäÈë²ÎÊý : ·µ »Ø Öµ : ÐÞ¸ÄÈÕÖ¾ : ************************************************************************/ IFeatureClass* XDWGReader::CreateAnnoFtCls(IWorkspace* pWS, CString sAnnoName, IFields* pFields) { HRESULT hr; IFeatureWorkspaceAnnoPtr PFWSAnno = pWS; IGraphicsLayerScalePtr pGLS(CLSID_GraphicsLayerScale); pGLS->put_Units(esriMeters); pGLS->put_ReferenceScale(m_dAnnoScale); //' set up symbol collection ISymbolCollectionPtr pSymbolColl(CLSID_SymbolCollection); ITextSymbolPtr myTxtSym(CLSID_TextSymbol); //Set the font for myTxtSym IFontDispPtr myFont(CLSID_StdFont); IFontPtr pFt = myFont; pFt->put_Name(CComBSTR("Courier New")); CY cy; cy.Hi = 0; cy.Lo = 9; pFt->put_Size(cy); myTxtSym->put_Font(myFont); // Set the Color for myTxtSym to be Dark Red IRgbColorPtr myColor(CLSID_RgbColor); myColor->put_Red(150); myColor->put_Green(0); myColor->put_Blue (0); myTxtSym->put_Color(myColor); // Set other properties for myTxtSym myTxtSym->put_Angle(0); myTxtSym->put_RightToLeft(VARIANT_FALSE); myTxtSym->put_VerticalAlignment(esriTVABaseline); myTxtSym->put_HorizontalAlignment(esriTHAFull); myTxtSym->put_Size(200); //myTxtSym->put_Case(esriTCNormal); ISymbolPtr pSymbol = myTxtSym; pSymbolColl->putref_Symbol(0, pSymbol); //set up the annotation labeling properties including the expression IAnnotateLayerPropertiesPtr pAnnoProps(CLSID_LabelEngineLayerProperties); pAnnoProps->put_FeatureLinked(VARIANT_TRUE); pAnnoProps->put_AddUnplacedToGraphicsContainer(VARIANT_FALSE); pAnnoProps->put_CreateUnplacedElements(VARIANT_TRUE); pAnnoProps->put_DisplayAnnotation(VARIANT_TRUE); pAnnoProps->put_UseOutput(VARIANT_TRUE); ILabelEngineLayerPropertiesPtr pLELayerProps = pAnnoProps; IAnnotationExpressionEnginePtr aAnnoVBScriptEngine(CLSID_AnnotationVBScriptEngine); pLELayerProps->putref_ExpressionParser(aAnnoVBScriptEngine); pLELayerProps->put_Expression(CComBSTR("[DESCRIPTION]")); pLELayerProps->put_IsExpressionSimple(VARIANT_TRUE); pLELayerProps->put_Offset(0); pLELayerProps->put_SymbolID(0); pLELayerProps->putref_Symbol(myTxtSym); IAnnotateLayerTransformationPropertiesPtr pATP = pAnnoProps; double dRefScale; pGLS->get_ReferenceScale(&dRefScale); pATP->put_ReferenceScale(dRefScale); pATP->put_Units(esriMeters); pATP->put_ScaleRatio(1); IAnnotateLayerPropertiesCollectionPtr pAnnoPropsColl(CLSID_AnnotateLayerPropertiesCollection); pAnnoPropsColl->Add(pAnnoProps); //' use the AnnotationFeatureClassDescription co - class to get the list of required fields and the default name of the shape field IObjectClassDescriptionPtr pOCDesc(CLSID_AnnotationFeatureClassDescription); IFeatureClassDescriptionPtr pFDesc = pOCDesc; IUIDPtr pInstCLSID; IUIDPtr pExtCLSID; CComBSTR bsShapeFieldName; pOCDesc->get_InstanceCLSID(&pInstCLSID); pOCDesc->get_ClassExtensionCLSID(&pExtCLSID); pFDesc->get_ShapeFieldName(&bsShapeFieldName); /*IFieldsPtr pReqFields; pOCDesc->get_RequiredFields(&pReqFields); //ÉèÖÿռä²Î¿¼ if (m_pSpRef != NULL) { long numFields; pReqFields->get_FieldCount(&numFields); for (int i = 0; i < numFields; i++) { IFieldPtr pField; pReqFields->get_Field(i, &pField); esriFieldType fldType; pField->get_Type(&fldType); if (fldType == esriFieldTypeGeometry) { IFieldEditPtr pEdtField = pField; IGeometryDefPtr pGeoDef; hr = pEdtField->get_GeometryDef(&pGeoDef); IGeometryDefEditPtr pEdtGeoDef = pGeoDef; hr = pEdtGeoDef->putref_SpatialReference(m_pSpRef); hr = pEdtField->putref_GeometryDef(pGeoDef); break; } } } IFieldsEditPtr ipFieldsEdit = pReqFields; //´´½¨CADÎļþÖÐ×¢¼Çͼ²ã×Ö¶Î IFieldEditPtr ipFieldEdit; IFieldPtr ipField; // ´´½¨ Entity £¬¼Ç¼esriʵÌåÀàÐÍ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR("Entity_Type")); ipFieldEdit->put_AliasName(CComBSTR("Entity_Type")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldsEdit->AddField(ipField); // ´´½¨ Handle £¬¼Ç¼DWGʵÌå±àºÅ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Handle")); ipFieldEdit->put_AliasName(CComBSTR(L"Handle")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ BaseName £¬¼Ç¼DWGʵÌå²ãÃû¼´DWGÎļþÃû ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"BaseName")); ipFieldEdit->put_AliasName(CComBSTR(L"BaseName")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(250); ipFieldsEdit->AddField(ipField); // ´´½¨ Layer £¬¼Ç¼DWGʵÌå²ãÃû ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Layer")); ipFieldEdit->put_AliasName(CComBSTR(L"Layer")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(250); ipFieldsEdit->AddField(ipField); // ´´½¨ Color £¬¼Ç¼DWGʵÌå·ûºÅÑÕÉ« ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Color")); ipFieldEdit->put_AliasName(CComBSTR(L"Color")); ipFieldEdit->put_Type(esriFieldTypeInteger); ipFieldsEdit->AddField(ipField); // ´´½¨ Thickness £¬¼Ç¼DWGʵÌåºñ¶È ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Thickness")); ipFieldEdit->put_AliasName(CComBSTR(L"Thickness")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ Elevation £¬¼Ç¼DWGʵÌå¸ß³ÌÖµ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Elevation")); ipFieldEdit->put_AliasName(CComBSTR(L"Elevation")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ Height £¬¼Ç¼¸ß¶È ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Height")); ipFieldEdit->put_AliasName(CComBSTR(L"Height")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ TextStyle £¬¼Ç¼ÎÄ×ÖÑùʽ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"TextStyle")); ipFieldEdit->put_AliasName(CComBSTR(L"TextStyle")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ Oblique £¬¼Ç¼Çã½Ç ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Oblique")); ipFieldEdit->put_AliasName(CComBSTR(L"Oblique")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField);*/ IFeatureClass* pAnnoFtCls; //' create the new class hr = PFWSAnno->CreateAnnotationClass(CComBSTR(sAnnoName), pFields, pInstCLSID, pExtCLSID, bsShapeFieldName, CComBSTR(""), NULL, 0, pAnnoPropsColl, pGLS, pSymbolColl, VARIANT_TRUE, &pAnnoFtCls); return pAnnoFtCls; } /************************************************************************ ¼òÒªÃèÊö : Éú³É×¢¼ÇElement ÊäÈë²ÎÊý : ·µ »Ø Öµ : ÐÞ¸ÄÈÕÖ¾ : ************************************************************************/ ITextElement* XDWGReader::MakeTextElementByStyle(CString strText, double dblAngle, double dblHeight, double dblX, double dblY, double ReferenceScale, esriTextHorizontalAlignment horizAlign, esriTextVerticalAlignment vertAlign) { HRESULT hr; ITextElementPtr pTextElement; ISimpleTextSymbolPtr pTextSymbol; CString strHeight; pTextSymbol.CreateInstance(CLSID_TextSymbol); //'Set the text symbol font by getting the IFontDisp interface pTextSymbol->put_Font(m_pAnnoTextFont); double mapUnitsInches; IUnitConverterPtr pUnitConverter(CLSID_UnitConverter); pUnitConverter->ConvertUnits(dblHeight, esriMeters, esriInches, &mapUnitsInches); strHeight.Format("%f", (mapUnitsInches * 72) / ReferenceScale); double dSize = atof(strHeight); pTextSymbol->put_Size(dSize); pTextSymbol->put_HorizontalAlignment(horizAlign); pTextSymbol->put_VerticalAlignment(vertAlign); pTextElement.CreateInstance(CLSID_TextElement); hr = pTextElement->put_ScaleText(VARIANT_TRUE); hr = pTextElement->put_Text(CComBSTR(strText)); hr = pTextElement->put_Symbol(pTextSymbol); IElementPtr pElement = pTextElement; IPointPtr pPoint(CLSID_Point); hr = pPoint->PutCoords(dblX, dblY); hr = pElement->put_Geometry(pPoint); if (fabs(dblAngle) > 0) { ITransform2DPtr pTransform2D = pTextElement; pTransform2D->Rotate(pPoint, dblAngle); } return pTextElement.Detach(); } /******************************************************************** ¼òÒªÃèÊö : ÊͷŽӿÚÖ¸Õë ÊäÈë²ÎÊý : ·µ »Ø Öµ : ÐÞ¸ÄÈÕÖ¾ : *********************************************************************/ int XDWGReader::ReleasePointer(IUnknown*& pInterface) { int iRst = 0; if (pInterface != NULL) { try { iRst = pInterface->Release(); pInterface = NULL; } catch(...) { } } return iRst; } // ÊͷŽӿڶÔÏó void XDWGReader::ReleaseAOs(void) { int iRst = 0; iRst = ReleasePointer((IUnknown*&)m_pPointFeatureCursor); iRst = ReleasePointer((IUnknown*&)m_pTextFeatureCursor); iRst = ReleasePointer((IUnknown*&)m_pLineFeatureCursor); iRst = ReleasePointer((IUnknown*&)m_pAnnoFeatureCursor); iRst = ReleasePointer((IUnknown*&)m_pPolygonFeatureCursor); iRst = ReleasePointer((IUnknown*&)m_pExtentTableRowCursor); iRst = ReleasePointer((IUnknown*&)m_pPointFeatureBuffer); iRst = ReleasePointer((IUnknown*&)m_pTextFeatureBuffer); iRst = ReleasePointer((IUnknown*&)m_pLineFeatureBuffer); iRst = ReleasePointer((IUnknown*&)m_pAnnoFeatureBuffer); iRst = ReleasePointer((IUnknown*&)m_pPolygonFeatureBuffer); iRst = ReleasePointer((IUnknown*&)m_pExtentTableRowBuffer); iRst = ReleasePointer((IUnknown*&)m_pSpRef); iRst = ReleasePointer((IUnknown*&)m_pFeatClassPoint); iRst = ReleasePointer((IUnknown*&)m_pFeatClassText); iRst = ReleasePointer((IUnknown*&)m_pFeatClassLine); iRst = ReleasePointer((IUnknown*&)m_pFeatClassPolygon); iRst = ReleasePointer((IUnknown*&)m_pAnnoFtCls); iRst = ReleasePointer((IUnknown*&)m_pExtendTable); } /******************************************************************** ¼òÒªÃèÊö :³õʼ»¯¶ÔÏóÖ¸Õë ÊäÈë²ÎÊý : ·µ »Ø Öµ : ÐÞ¸ÄÈÕÖ¾ : *********************************************************************/ void XDWGReader::InitAOPointers(void) { m_pPointFeatureCursor = NULL; m_pTextFeatureCursor = NULL; m_pLineFeatureCursor = NULL; m_pAnnoFeatureCursor = NULL; m_pPolygonFeatureCursor = NULL; m_pExtentTableRowCursor = NULL; m_pPointFeatureBuffer = NULL; m_pTextFeatureBuffer = NULL; m_pLineFeatureBuffer = NULL; m_pAnnoFeatureBuffer = NULL; m_pPolygonFeatureBuffer = NULL; m_pExtentTableRowBuffer = NULL; m_pFeatClassPoint = NULL; m_pFeatClassLine = NULL; m_pFeatClassPolygon = NULL; m_pAnnoFtCls = NULL; m_pExtendTable = NULL; m_pFeatClassText = NULL; }
hy1314200/HyDM
DataExchange/DwgConvert/XDwgDirectReader.cpp
C++
gpl-3.0
132,005
# Copyright 2019 Virgil Dupras # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html import datetime from collections import defaultdict from core.util import dedupe, first as getfirst from core.trans import tr from ..model.date import DateFormat from .base import GUIObject from .import_table import ImportTable from .selectable_list import LinkedSelectableList DAY = 'day' MONTH = 'month' YEAR = 'year' class SwapType: DayMonth = 0 MonthYear = 1 DayYear = 2 DescriptionPayee = 3 InvertAmount = 4 def last_two_digits(year): return year - ((year // 100) * 100) def swapped_date(date, first, second): attrs = {DAY: date.day, MONTH: date.month, YEAR: last_two_digits(date.year)} newattrs = {first: attrs[second], second: attrs[first]} if YEAR in newattrs: newattrs[YEAR] += 2000 return date.replace(**newattrs) def swap_format_elements(format, first, second): # format is a DateFormat swapped = format.copy() elems = swapped.elements TYPE2CHAR = {DAY: 'd', MONTH: 'M', YEAR: 'y'} first_char = TYPE2CHAR[first] second_char = TYPE2CHAR[second] first_index = [i for i, x in enumerate(elems) if x.startswith(first_char)][0] second_index = [i for i, x in enumerate(elems) if x.startswith(second_char)][0] elems[first_index], elems[second_index] = elems[second_index], elems[first_index] return swapped class AccountPane: def __init__(self, iwin, account, target_account, parsing_date_format): self.iwin = iwin self.account = account self._selected_target = target_account self.name = account.name entries = iwin.loader.accounts.entries_for_account(account) self.count = len(entries) self.matches = [] # [[ref, imported]] self.parsing_date_format = parsing_date_format self.max_day = 31 self.max_month = 12 self.max_year = 99 # 2 digits self._match_entries() self._swap_possibilities = set() self._compute_swap_possibilities() def _compute_swap_possibilities(self): entries = list(self.iwin.loader.accounts.entries_for_account(self.account)) if not entries: return self._swap_possibilities = set([(DAY, MONTH), (MONTH, YEAR), (DAY, YEAR)]) for first, second in self._swap_possibilities.copy(): for entry in entries: try: swapped_date(entry.date, first, second) except ValueError: self._swap_possibilities.remove((first, second)) break def _match_entries(self): to_import = list(self.iwin.loader.accounts.entries_for_account(self.account)) reference2entry = {} for entry in (e for e in to_import if e.reference): reference2entry[entry.reference] = entry self.matches = [] if self.selected_target is not None: entries = self.iwin.document.accounts.entries_for_account(self.selected_target) for entry in entries: if entry.reference in reference2entry: other = reference2entry[entry.reference] if entry.reconciled: self.iwin.import_table.dont_import.add(other) to_import.remove(other) del reference2entry[entry.reference] else: other = None if other is not None or not entry.reconciled: self.matches.append([entry, other]) self.matches += [[None, entry] for entry in to_import] self._sort_matches() def _sort_matches(self): self.matches.sort(key=lambda t: t[0].date if t[0] is not None else t[1].date) def bind(self, existing, imported): [match1] = [m for m in self.matches if m[0] is existing] [match2] = [m for m in self.matches if m[1] is imported] assert match1[1] is None assert match2[0] is None match1[1] = match2[1] self.matches.remove(match2) def can_swap_date_fields(self, first, second): # 'day', 'month', 'year' return (first, second) in self._swap_possibilities or (second, first) in self._swap_possibilities def match_entries_by_date_and_amount(self, threshold): delta = datetime.timedelta(days=threshold) unmatched = ( to_import for ref, to_import in self.matches if ref is None) unmatched_refs = ( ref for ref, to_import in self.matches if to_import is None) amount2refs = defaultdict(list) for entry in unmatched_refs: amount2refs[entry.amount].append(entry) for entry in unmatched: if entry.amount not in amount2refs: continue potentials = amount2refs[entry.amount] for ref in potentials: if abs(ref.date - entry.date) <= delta: self.bind(ref, entry) potentials.remove(ref) self._sort_matches() def unbind(self, existing, imported): [match] = [m for m in self.matches if m[0] is existing and m[1] is imported] match[1] = None self.matches.append([None, imported]) self._sort_matches() @property def selected_target(self): return self._selected_target @selected_target.setter def selected_target(self, value): self._selected_target = value self._match_entries() # This is a modal window that is designed to be re-instantiated on each import # run. It is shown modally by the UI as soon as its created on the UI side. class ImportWindow(GUIObject): # --- View interface # close() # close_selected_tab() # set_swap_button_enabled(enabled: bool) # update_selected_pane() # show() # def __init__(self, mainwindow, target_account=None): super().__init__() if not hasattr(mainwindow, 'loader'): raise ValueError("Nothing to import!") self.mainwindow = mainwindow self.document = mainwindow.document self.app = self.document.app self._selected_pane_index = 0 self._selected_target_index = 0 def setfunc(index): self.view.set_swap_button_enabled(self.can_perform_swap()) self.swap_type_list = LinkedSelectableList(items=[ "<placeholder> Day <--> Month", "<placeholder> Month <--> Year", "<placeholder> Day <--> Year", tr("Description <--> Payee"), tr("Invert Amounts"), ], setfunc=setfunc) self.swap_type_list.selected_index = SwapType.DayMonth self.panes = [] self.import_table = ImportTable(self) self.loader = self.mainwindow.loader self.target_accounts = [ a for a in self.document.accounts if a.is_balance_sheet_account()] self.target_accounts.sort(key=lambda a: a.name.lower()) accounts = [] for account in self.loader.accounts: if account.is_balance_sheet_account(): entries = self.loader.accounts.entries_for_account(account) if len(entries): new_name = self.document.accounts.new_name(account.name) if new_name != account.name: self.loader.accounts.rename_account(account, new_name) accounts.append(account) parsing_date_format = DateFormat.from_sysformat(self.loader.parsing_date_format) for account in accounts: target = target_account if target is None and account.reference: target = getfirst( t for t in self.target_accounts if t.reference == account.reference ) self.panes.append( AccountPane(self, account, target, parsing_date_format)) # --- Private def _can_swap_date_fields(self, first, second): # 'day', 'month', 'year' pane = self.selected_pane if pane is None: return False return pane.can_swap_date_fields(first, second) def _invert_amounts(self, apply_to_all): if apply_to_all: panes = self.panes else: panes = [self.selected_pane] for pane in panes: entries = self.loader.accounts.entries_for_account(pane.account) txns = dedupe(e.transaction for e in entries) for txn in txns: for split in txn.splits: split.amount = -split.amount self.import_table.refresh() def _refresh_target_selection(self): if not self.panes: return target = self.selected_pane.selected_target self._selected_target_index = 0 if target is not None: try: self._selected_target_index = self.target_accounts.index(target) + 1 except ValueError: pass def _refresh_swap_list_items(self): if not self.panes: return items = [] basefmt = self.selected_pane.parsing_date_format for first, second in [(DAY, MONTH), (MONTH, YEAR), (DAY, YEAR)]: swapped = swap_format_elements(basefmt, first, second) items.append("{} --> {}".format(basefmt.iso_format, swapped.iso_format)) self.swap_type_list[:3] = items def _swap_date_fields(self, first, second, apply_to_all): # 'day', 'month', 'year' assert self._can_swap_date_fields(first, second) if apply_to_all: panes = [p for p in self.panes if p.can_swap_date_fields(first, second)] else: panes = [self.selected_pane] def switch_func(txn): txn.date = swapped_date(txn.date, first, second) self._swap_fields(panes, switch_func) # Now, lets' change the date format on these panes for pane in panes: basefmt = self.selected_pane.parsing_date_format swapped = swap_format_elements(basefmt, first, second) pane.parsing_date_format = swapped pane._sort_matches() self.import_table.refresh() self._refresh_swap_list_items() def _swap_description_payee(self, apply_to_all): if apply_to_all: panes = self.panes else: panes = [self.selected_pane] def switch_func(txn): txn.description, txn.payee = txn.payee, txn.description self._swap_fields(panes, switch_func) def _swap_fields(self, panes, switch_func): seen = set() for pane in panes: entries = self.loader.accounts.entries_for_account(pane.account) txns = dedupe(e.transaction for e in entries) for txn in txns: if txn.affected_accounts() & seen: # We've already swapped this txn in a previous pane. continue switch_func(txn) seen.add(pane.account) self.import_table.refresh() def _update_selected_pane(self): self.import_table.refresh() self._refresh_swap_list_items() self.view.update_selected_pane() self.view.set_swap_button_enabled(self.can_perform_swap()) # --- Override def _view_updated(self): if self.document.can_restore_from_prefs(): self.restore_view() # XXX Logically, we should call _update_selected_pane() but doing so # make tests fail. to investigate. self._refresh_target_selection() self.view.update_selected_pane() self._refresh_swap_list_items() self.import_table.refresh() # --- Public def can_perform_swap(self): index = self.swap_type_list.selected_index if index == SwapType.DayMonth: return self._can_swap_date_fields(DAY, MONTH) elif index == SwapType.MonthYear: return self._can_swap_date_fields(MONTH, YEAR) elif index == SwapType.DayYear: return self._can_swap_date_fields(DAY, YEAR) else: return True def close_pane(self, index): was_selected = index == self.selected_pane_index del self.panes[index] if not self.panes: self.view.close() return self._selected_pane_index = min(self._selected_pane_index, len(self.panes) - 1) if was_selected: self._update_selected_pane() def import_selected_pane(self): pane = self.selected_pane matches = pane.matches matches = [ (e, ref) for ref, e in matches if e is not None and e not in self.import_table.dont_import] if pane.selected_target is not None: # We import in an existing account, adjust all the transactions accordingly target_account = pane.selected_target else: target_account = None self.document.import_entries(target_account, pane.account, matches) self.mainwindow.revalidate() self.close_pane(self.selected_pane_index) self.view.close_selected_tab() def match_entries_by_date_and_amount(self, threshold): self.selected_pane.match_entries_by_date_and_amount(threshold) self.import_table.refresh() def perform_swap(self, apply_to_all=False): index = self.swap_type_list.selected_index if index == SwapType.DayMonth: self._swap_date_fields(DAY, MONTH, apply_to_all=apply_to_all) elif index == SwapType.MonthYear: self._swap_date_fields(MONTH, YEAR, apply_to_all=apply_to_all) elif index == SwapType.DayYear: self._swap_date_fields(DAY, YEAR, apply_to_all=apply_to_all) elif index == SwapType.DescriptionPayee: self._swap_description_payee(apply_to_all=apply_to_all) elif index == SwapType.InvertAmount: self._invert_amounts(apply_to_all=apply_to_all) def restore_view(self): self.import_table.columns.restore_columns() # --- Properties @property def selected_pane(self): return self.panes[self.selected_pane_index] if self.panes else None @property def selected_pane_index(self): return self._selected_pane_index @selected_pane_index.setter def selected_pane_index(self, value): if value >= len(self.panes): return self._selected_pane_index = value self._refresh_target_selection() self._update_selected_pane() @property def selected_target_account(self): return self.selected_pane.selected_target @property def selected_target_account_index(self): return self._selected_target_index @selected_target_account_index.setter def selected_target_account_index(self, value): target = self.target_accounts[value - 1] if value > 0 else None self.selected_pane.selected_target = target self._selected_target_index = value self.import_table.refresh() @property def target_account_names(self): return [tr('< New Account >')] + [a.name for a in self.target_accounts]
hsoft/moneyguru
core/gui/import_window.py
Python
gpl-3.0
15,326
/* * Copyright (C) 2006 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.content; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.res.AssetManager; import android.content.res.Configuration; import android.content.res.Resources; import android.database.DatabaseErrorHandler; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Looper; import android.os.UserHandle; import android.view.DisplayAdjustments; import android.view.Display; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; /** * Proxying implementation of Context that simply delegates all of its calls to * another Context. Can be subclassed to modify behavior without changing * the original Context. */ public class ContextWrapper extends Context { Context mBase; public ContextWrapper(Context base) { mBase = base; } /** * Set the base context for this ContextWrapper. All calls will then be * delegated to the base context. Throws * IllegalStateException if a base context has already been set. * * @param base The new base context for this wrapper. */ protected void attachBaseContext(Context base) { if (mBase != null) { throw new IllegalStateException("Base context already set"); } mBase = base; } /** * @return the base context as set by the constructor or setBaseContext */ public Context getBaseContext() { return mBase; } @Override public AssetManager getAssets() { return mBase.getAssets(); } @Override public Resources getResources() { return mBase.getResources(); } @Override public PackageManager getPackageManager() { return mBase.getPackageManager(); } @Override public ContentResolver getContentResolver() { return mBase.getContentResolver(); } @Override public Looper getMainLooper() { return mBase.getMainLooper(); } @Override public Context getApplicationContext() { return mBase.getApplicationContext(); } @Override public void setTheme(int resid) { mBase.setTheme(resid); } /** @hide */ @Override public int getThemeResId() { return mBase.getThemeResId(); } @Override public Resources.Theme getTheme() { return mBase.getTheme(); } @Override public ClassLoader getClassLoader() { return mBase.getClassLoader(); } @Override public String getPackageName() { return mBase.getPackageName(); } /** @hide */ @Override public String getBasePackageName() { return mBase.getBasePackageName(); } /** @hide */ @Override public String getOpPackageName() { return mBase.getOpPackageName(); } @Override public ApplicationInfo getApplicationInfo() { return mBase.getApplicationInfo(); } @Override public String getPackageResourcePath() { return mBase.getPackageResourcePath(); } @Override public String getPackageCodePath() { return mBase.getPackageCodePath(); } /** @hide */ @Override public File getSharedPrefsFile(String name) { return mBase.getSharedPrefsFile(name); } @Override public SharedPreferences getSharedPreferences(String name, int mode) { return mBase.getSharedPreferences(name, mode); } @Override public FileInputStream openFileInput(String name) throws FileNotFoundException { return mBase.openFileInput(name); } @Override public FileOutputStream openFileOutput(String name, int mode) throws FileNotFoundException { return mBase.openFileOutput(name, mode); } @Override public boolean deleteFile(String name) { return mBase.deleteFile(name); } @Override public File getFileStreamPath(String name) { return mBase.getFileStreamPath(name); } @Override public String[] fileList() { return mBase.fileList(); } @Override public File getFilesDir() { return mBase.getFilesDir(); } @Override public File getNoBackupFilesDir() { return mBase.getNoBackupFilesDir(); } @Override public File getExternalFilesDir(String type) { return mBase.getExternalFilesDir(type); } @Override public File[] getExternalFilesDirs(String type) { return mBase.getExternalFilesDirs(type); } @Override public File getObbDir() { return mBase.getObbDir(); } @Override public File[] getObbDirs() { return mBase.getObbDirs(); } @Override public File getCacheDir() { return mBase.getCacheDir(); } @Override public File getCodeCacheDir() { return mBase.getCodeCacheDir(); } @Override public File getExternalCacheDir() { return mBase.getExternalCacheDir(); } @Override public File[] getExternalCacheDirs() { return mBase.getExternalCacheDirs(); } @Override public File[] getExternalMediaDirs() { return mBase.getExternalMediaDirs(); } @Override public File getDir(String name, int mode) { return mBase.getDir(name, mode); } @Override public SQLiteDatabase openOrCreateDatabase(String name, int mode, CursorFactory factory) { return mBase.openOrCreateDatabase(name, mode, factory); } @Override public SQLiteDatabase openOrCreateDatabase(String name, int mode, CursorFactory factory, DatabaseErrorHandler errorHandler) { return mBase.openOrCreateDatabase(name, mode, factory, errorHandler); } @Override public boolean deleteDatabase(String name) { return mBase.deleteDatabase(name); } @Override public File getDatabasePath(String name) { return mBase.getDatabasePath(name); } @Override public String[] databaseList() { return mBase.databaseList(); } @Override public Drawable getWallpaper() { return mBase.getWallpaper(); } @Override public Drawable peekWallpaper() { return mBase.peekWallpaper(); } @Override public int getWallpaperDesiredMinimumWidth() { return mBase.getWallpaperDesiredMinimumWidth(); } @Override public int getWallpaperDesiredMinimumHeight() { return mBase.getWallpaperDesiredMinimumHeight(); } @Override public void setWallpaper(Bitmap bitmap) throws IOException { mBase.setWallpaper(bitmap); } @Override public void setWallpaper(InputStream data) throws IOException { mBase.setWallpaper(data); } @Override public void clearWallpaper() throws IOException { mBase.clearWallpaper(); } @Override public void startActivity(Intent intent) { mBase.startActivity(intent); } /** @hide */ @Override public void startActivityAsUser(Intent intent, UserHandle user) { mBase.startActivityAsUser(intent, user); } @Override public void startActivity(Intent intent, Bundle options) { mBase.startActivity(intent, options); } /** @hide */ @Override public void startActivityAsUser(Intent intent, Bundle options, UserHandle user) { mBase.startActivityAsUser(intent, options, user); } @Override public void startActivities(Intent[] intents) { mBase.startActivities(intents); } @Override public void startActivities(Intent[] intents, Bundle options) { mBase.startActivities(intents, options); } /** @hide */ @Override public void startActivitiesAsUser(Intent[] intents, Bundle options, UserHandle userHandle) { mBase.startActivitiesAsUser(intents, options, userHandle); } @Override public void startIntentSender(IntentSender intent, Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags) throws IntentSender.SendIntentException { mBase.startIntentSender(intent, fillInIntent, flagsMask, flagsValues, extraFlags); } @Override public void startIntentSender(IntentSender intent, Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags, Bundle options) throws IntentSender.SendIntentException { mBase.startIntentSender(intent, fillInIntent, flagsMask, flagsValues, extraFlags, options); } @Override public void sendBroadcast(Intent intent) { mBase.sendBroadcast(intent); } @Override public void sendBroadcast(Intent intent, String receiverPermission) { mBase.sendBroadcast(intent, receiverPermission); } /** @hide */ @Override public void sendBroadcast(Intent intent, String receiverPermission, int appOp) { mBase.sendBroadcast(intent, receiverPermission, appOp); } @Override public void sendOrderedBroadcast(Intent intent, String receiverPermission) { mBase.sendOrderedBroadcast(intent, receiverPermission); } @Override public void sendOrderedBroadcast( Intent intent, String receiverPermission, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras) { mBase.sendOrderedBroadcast(intent, receiverPermission, resultReceiver, scheduler, initialCode, initialData, initialExtras); } /** @hide */ @Override public void sendOrderedBroadcast( Intent intent, String receiverPermission, int appOp, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras) { mBase.sendOrderedBroadcast(intent, receiverPermission, appOp, resultReceiver, scheduler, initialCode, initialData, initialExtras); } @Override public void sendBroadcastAsUser(Intent intent, UserHandle user) { mBase.sendBroadcastAsUser(intent, user); } @Override public void sendBroadcastAsUser(Intent intent, UserHandle user, String receiverPermission) { mBase.sendBroadcastAsUser(intent, user, receiverPermission); } @Override public void sendOrderedBroadcastAsUser(Intent intent, UserHandle user, String receiverPermission, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras) { mBase.sendOrderedBroadcastAsUser(intent, user, receiverPermission, resultReceiver, scheduler, initialCode, initialData, initialExtras); } /** @hide */ @Override public void sendOrderedBroadcastAsUser(Intent intent, UserHandle user, String receiverPermission, int appOp, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras) { mBase.sendOrderedBroadcastAsUser(intent, user, receiverPermission, appOp, resultReceiver, scheduler, initialCode, initialData, initialExtras); } @Override public void sendStickyBroadcast(Intent intent) { mBase.sendStickyBroadcast(intent); } @Override public void sendStickyOrderedBroadcast( Intent intent, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras) { mBase.sendStickyOrderedBroadcast(intent, resultReceiver, scheduler, initialCode, initialData, initialExtras); } @Override public void removeStickyBroadcast(Intent intent) { mBase.removeStickyBroadcast(intent); } @Override public void sendStickyBroadcastAsUser(Intent intent, UserHandle user) { mBase.sendStickyBroadcastAsUser(intent, user); } @Override public void sendStickyOrderedBroadcastAsUser(Intent intent, UserHandle user, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras) { mBase.sendStickyOrderedBroadcastAsUser(intent, user, resultReceiver, scheduler, initialCode, initialData, initialExtras); } @Override public void removeStickyBroadcastAsUser(Intent intent, UserHandle user) { mBase.removeStickyBroadcastAsUser(intent, user); } @Override public Intent registerReceiver( BroadcastReceiver receiver, IntentFilter filter) { return mBase.registerReceiver(receiver, filter); } @Override public Intent registerReceiver( BroadcastReceiver receiver, IntentFilter filter, String broadcastPermission, Handler scheduler) { return mBase.registerReceiver(receiver, filter, broadcastPermission, scheduler); } /** @hide */ @Override public Intent registerReceiverAsUser( BroadcastReceiver receiver, UserHandle user, IntentFilter filter, String broadcastPermission, Handler scheduler) { return mBase.registerReceiverAsUser(receiver, user, filter, broadcastPermission, scheduler); } @Override public void unregisterReceiver(BroadcastReceiver receiver) { mBase.unregisterReceiver(receiver); } @Override public ComponentName startService(Intent service) { return mBase.startService(service); } @Override public boolean stopService(Intent name) { return mBase.stopService(name); } /** @hide */ @Override public ComponentName startServiceAsUser(Intent service, UserHandle user) { return mBase.startServiceAsUser(service, user); } /** @hide */ @Override public boolean stopServiceAsUser(Intent name, UserHandle user) { return mBase.stopServiceAsUser(name, user); } @Override public boolean bindService(Intent service, ServiceConnection conn, int flags) { return mBase.bindService(service, conn, flags); } /** @hide */ @Override public boolean bindServiceAsUser(Intent service, ServiceConnection conn, int flags, UserHandle user) { return mBase.bindServiceAsUser(service, conn, flags, user); } @Override public void unbindService(ServiceConnection conn) { mBase.unbindService(conn); } @Override public boolean startInstrumentation(ComponentName className, String profileFile, Bundle arguments) { return mBase.startInstrumentation(className, profileFile, arguments); } @Override public Object getSystemService(String name) { return mBase.getSystemService(name); } @Override public int checkPermission(String permission, int pid, int uid) { return mBase.checkPermission(permission, pid, uid); } /** @hide */ @Override public int checkPermission(String permission, int pid, int uid, IBinder callerToken) { return mBase.checkPermission(permission, pid, uid, callerToken); } @Override public int checkCallingPermission(String permission) { return mBase.checkCallingPermission(permission); } @Override public int checkCallingOrSelfPermission(String permission) { return mBase.checkCallingOrSelfPermission(permission); } @Override public void enforcePermission( String permission, int pid, int uid, String message) { mBase.enforcePermission(permission, pid, uid, message); } @Override public void enforceCallingPermission(String permission, String message) { mBase.enforceCallingPermission(permission, message); } @Override public void enforceCallingOrSelfPermission( String permission, String message) { mBase.enforceCallingOrSelfPermission(permission, message); } @Override public void grantUriPermission(String toPackage, Uri uri, int modeFlags) { mBase.grantUriPermission(toPackage, uri, modeFlags); } @Override public void revokeUriPermission(Uri uri, int modeFlags) { mBase.revokeUriPermission(uri, modeFlags); } @Override public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) { return mBase.checkUriPermission(uri, pid, uid, modeFlags); } /** @hide */ @Override public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags, IBinder callerToken) { return mBase.checkUriPermission(uri, pid, uid, modeFlags, callerToken); } @Override public int checkCallingUriPermission(Uri uri, int modeFlags) { return mBase.checkCallingUriPermission(uri, modeFlags); } @Override public int checkCallingOrSelfUriPermission(Uri uri, int modeFlags) { return mBase.checkCallingOrSelfUriPermission(uri, modeFlags); } @Override public int checkUriPermission(Uri uri, String readPermission, String writePermission, int pid, int uid, int modeFlags) { return mBase.checkUriPermission(uri, readPermission, writePermission, pid, uid, modeFlags); } @Override public void enforceUriPermission( Uri uri, int pid, int uid, int modeFlags, String message) { mBase.enforceUriPermission(uri, pid, uid, modeFlags, message); } @Override public void enforceCallingUriPermission( Uri uri, int modeFlags, String message) { mBase.enforceCallingUriPermission(uri, modeFlags, message); } @Override public void enforceCallingOrSelfUriPermission( Uri uri, int modeFlags, String message) { mBase.enforceCallingOrSelfUriPermission(uri, modeFlags, message); } @Override public void enforceUriPermission( Uri uri, String readPermission, String writePermission, int pid, int uid, int modeFlags, String message) { mBase.enforceUriPermission( uri, readPermission, writePermission, pid, uid, modeFlags, message); } @Override public Context createPackageContext(String packageName, int flags) throws PackageManager.NameNotFoundException { return mBase.createPackageContext(packageName, flags); } /** @hide */ @Override public Context createPackageContextAsUser(String packageName, int flags, UserHandle user) throws PackageManager.NameNotFoundException { return mBase.createPackageContextAsUser(packageName, flags, user); } /** @hide */ public Context createApplicationContext(ApplicationInfo application, int flags) throws PackageManager.NameNotFoundException { return mBase.createApplicationContext(application, flags); } /** @hide */ @Override public int getUserId() { return mBase.getUserId(); } @Override public Context createConfigurationContext(Configuration overrideConfiguration) { return mBase.createConfigurationContext(overrideConfiguration); } @Override public Context createDisplayContext(Display display) { return mBase.createDisplayContext(display); } @Override public boolean isRestricted() { return mBase.isRestricted(); } /** @hide */ @Override public DisplayAdjustments getDisplayAdjustments(int displayId) { return mBase.getDisplayAdjustments(displayId); } }
s20121035/rk3288_android5.1_repo
frameworks/base/core/java/android/content/ContextWrapper.java
Java
gpl-3.0
20,584
The C-BGP Routing Solver == C-BGP is an efficient solver for BGP, the de facto standard protocol used for exchanging routing information accross domains in the Internet. BGP was initially described in RFC1771 in 1995. It has since undergone several updates recently standardized in RFC4271 (2006). C-BGP is aimed at computing the outcome of the BGP decision process in networks composed of several routers. For this purpose, it takes into account the routers' configuration, the externally received BGP routes and the network topology. It supports the complete BGP decision process, versatile import and export filters, route-reflection, and experimental attributes such as redistribution communities. It is easily configurable through a CISCO-like command-line interface. C-BGP has been described in an IEEE Network magazine paper entitled "Modeling the Routing of an Autonomous System with C-BGP" (please refer to this paper when you cite C-BGP). C-BGP can be used as a research tool to experiment with modified decision processes and additional BGP route attributes. It can also be used by the operator of an ISP network to evaluate the impact of logical and topological changes on the routing tables computed in its routers. Topological changes include links and routers failures. Logical changes include changes in the configuration of the routers such as input/output routing policies or IGP link weights. Thanks to its efficiency, C-BGP can be used on large topologies with sizes of the same order of magnitude than the Internet. For the moment, we mainly use it to study interdomain traffic engineering techniques and to model the network of ISPs. The original version of C-BGP was written by Bruno Quoitin within the Computer Science and Engineering Department at Universite Catholique de Louvain (UCL), in Belgium. It has since been contributed by others (see the AUTHORS file for a complete list). C-BGP is written in C language. It is mainly used and tested on Linux and Mac OS X. It has also been used on other platforms such as FreeBSD, Solaris and even under Windows, using the cygwin API. It should compile on most POSIX compliant environment. C-BGP is Open-Source and provided under the GPL license for academic use. The text of the GPL license is available in the COPYING file included in this distribution. Commercial use of C-BGP is covered by a separate license since version 2.0.0. WHERE TO OBTAIN LIBGDS & CBGP == The main location is now sourceforge. http://sourceforge.net/projects/c-bgp/ http://sourceforge.net/projects/libgds Older version can be obtained from http://cbgp.info.ucl.ac.be http://libgds.info.ucl.ac.be REQUIRED LIBRARIES AND TOOLS == - a decent version of gcc and GNU make - the pcre library: perl compatible regular expressions - the readline library: this is optional, but it greatly enhances the cbgp experience :-) - libz and libbz2 - pkg-config Note that for libraries, you will need to install the actual library and the header files to be able to link against the library. These header files are usually available in a "-devel" package. HOW TO BUILD LIBGDS & CBGP == 1). build libgds tar xvzf libgdz-x.x.x.tar.gz cd libgds-x.x.x # at this stage you can specify an alternative installation directory # with --prefix=<path>, the default being /usr/local ./configure make clean make # before installing, please check the section below that talks about # testing make install Note: if you installed libgds in a non-standard directory, you will need to make sure that pkg-config is able to find libgds. This is usually done by adding the libgds install directory to pkg-config using the PKG_CONFIG_PATH environment variable. For example, if libgds was installed in /home/foo/local, you will need to add it to the PKG_CONFIG_PATH variable as follows: export PKG_CONFIG_PATH=$PKG_CONFIG_PATH:/home/foo/local/lib/pkgconfig you can then test that pkg-config is able to find libgds by issuing the following command: pkg-config libgds --modversion the above command should return the version of the installed libgds library 2). builds cbgp tar xvzf cbgp-x.x.x.tar.gz cd cbgp-x.x.x # at this stage, several options can be used (use --help to obtain # the complete list. important options are # --with-readline=<path> to specify where the readline library is located # --with-pcre=<path> to specify where the pcre library is located # --with-jni to allow the java native interface to compile ./configure make clean make # before installing, please check the section below that talks about # testing make install HOW TO TEST IF LIBGDS & CBGP ARE FUNCTIONNAL == 1). run internal unit tests libgds and cbgp source repository contains several unit test functions that can be run with a single line * libgds: make check * cbgp: make check most tests should succeed. A final line is provided that summarizes the number of tests and how many failed among them. At the time of this writing, the following numbers were reported: * libgds: FAILURES=0 / SKIPPED=2 / TESTS=153 * cbgp: FAILURES=1 / SKIPPED=5 / TESTS=188 if the numbers you obtain deviate significantly from the above numbers, you should become suspicious and look more carefully) 2). run external black-box tests cbgp comes with a (huge) perl script that runs several cbgp scripts and observe their behaviour and results. to run these tests, you should move to the "./valid" subdirectory in the cbgp main directory and run "./cbgp-validation.pl --no-cache". this can take some time depending on the platform. 3). run cbgp the final test consists in running cbgp. at this point it might be interesting to check if cbgp was correctly linked with the readline library. it should provide auto-completion for most cbgp commands as well as a history of all the commands typed in the cbgp console. a simple test is done as follows for the version just compiled (not yet installed) # assuming you are in the root cbgp directory ../src/cbgp C-BGP Routing Solver version 2.0.0-rc3 Copyright (C) 2002-2010 Bruno Quoitin Networking Lab Computer Science Institute University of Mons (UMONS) Mons, Belgium This software is free for personal and educational uses. See file COPYING for details. help is bound to '?' key cbgp> init. cbgp> here you can now type "sh" then press the "tabulation" key. it should complete with "show". press again the tabulation key twice and it should list the sub-commands of "show" cbgp> sh <tab> cbgp> show <tab><tab> comm-hash-content comm-hash-size comm-hash-stat commands mem-limit mrt path-hash-content path-hash-size path-hash-stat version in case auto-completion and/or history do not seem to work, check the results of the "./configure" script for warnings related to the version and features of the readline library that was detected. in case the wrong version of the readline library was chosen, you can specify where to find the correct version by using the "--with-readline==<path>" option with the "./configure" script. for example, on my machine, i need to run ./configure -with-readline=/opt/local
lvanbever/cbgp
README.md
Markdown
gpl-3.0
7,205
#### List of contents * [User guide](@ref axo_gui) * [Compiling from source](@ref compile) * [Getting started](@ref getting_started) </br> * [For developers] (@ref developers) * [Updating the firmware] (@ref updating_firmware) * [Directory structure] (@ref directory_structure) * [For PureData users] (@ref pd_user) </br> * [Roadmap] (@ref roadmap)
dkmorb/axoloti
doc/doxygen/main_page.md
Markdown
gpl-3.0
350
// Copyright (c) François Paradis // This file is part of Mox, a card game simulator. // // Mox 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. // // Mox 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 Mox. If not, see <http://www.gnu.org/licenses/>. using System; using Mox.Events; using Mox.Flow; namespace Mox.Database.Library { public abstract class ZoneChangeTriggeredAbility : TriggeredAbility, IEventHandler<ZoneChangeEvent> { #region Inner Types protected class ZoneChangeContext { public readonly Resolvable<Card> Card; public ZoneChangeContext(Card card) { Card = card; } } #endregion #region Methods /// <summary> /// Returns true if the card can trigger the ability. /// </summary> /// <remarks> /// By default, checks if the card is the source. /// </remarks> /// <param name="card"></param> /// <returns></returns> protected virtual bool IsValidCard(Card card) { return card == Source; } /// <summary> /// Returns true if this is the zone from which the card should come from. /// </summary> /// <param name="zone"></param> /// <returns></returns> protected virtual bool IsTriggeringSourceZone(Zone zone) { return true; } private bool IsTriggeringTargetZone(Game game, ZoneChangeContext zoneChangeContext) { return zoneChangeContext.Card.Resolve(game).Zone.ZoneId == TriggerZone; } public override bool CanPushOnStack(Game game, object zoneChangeContext) { return IsTriggeringTargetZone(game, (ZoneChangeContext) zoneChangeContext); } public override sealed void Play(Spell spell) { ZoneChangeContext zoneChangeContext = (ZoneChangeContext)spell.Context; Play(spell, zoneChangeContext.Card); } protected internal override void ResolveSpellEffect(Part.Context context, Spell spell) { if (IsTriggeringTargetZone(context.Game, (ZoneChangeContext)spell.Context)) { base.ResolveSpellEffect(context, spell); } } protected abstract void Play(Spell spell, Resolvable<Card> card); void IEventHandler<ZoneChangeEvent>.HandleEvent(Game game, ZoneChangeEvent e) { if (IsValidCard(e.Card) && IsTriggeringSourceZone(e.OldZone) && e.NewZone.ZoneId == TriggerZone) { Trigger(new ZoneChangeContext(e.Card)); } } #endregion } }
fparadis2/mox
Source/Mox.Engine/Project/Source/Database/CardFactory/Library/ZoneChangeTriggeredAbility.cs
C#
gpl-3.0
3,243
package com.thomasjensen.checkstyle.addons.checks; /* * Checkstyle-Addons - Additional Checkstyle checks * Copyright (c) 2015-2020, the Checkstyle Addons contributors * * 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/>. */ import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import javax.annotation.Nullable; import net.jcip.annotations.Immutable; /** * Represents a Java binary class name for reference types, in the form of its fragments. This is the only way to tell * the difference between a class called <code>A$B</code> and a class called <code>A</code> that has an inner class * <code>B</code>. */ @Immutable public final class BinaryName { private final String pkg; private final List<String> cls; /** * Constructor. * * @param pPkg package name * @param pOuterCls outer class simple name * @param pInnerCls inner class simple names in descending order of their nesting */ public BinaryName(@Nullable final String pPkg, @Nonnull final String pOuterCls, @Nullable final String... pInnerCls) { pkg = pPkg; List<String> nameList = new ArrayList<>(); if (pOuterCls != null) { nameList.add(pOuterCls); } else { throw new IllegalArgumentException("pOuterCls was null"); } if (pInnerCls != null) { for (final String inner : pInnerCls) { nameList.add(inner); } } cls = Collections.unmodifiableList(nameList); } /** * Constructor. * * @param pPkg package name * @param pClsNames class simple names in descending order of their nesting */ public BinaryName(@Nullable final String pPkg, @Nonnull final Collection<String> pClsNames) { pkg = pPkg; if (pClsNames.size() == 0) { throw new IllegalArgumentException("pClsNames is empty"); } cls = Collections.unmodifiableList(new ArrayList<>(pClsNames)); } @Override public String toString() { StringBuilder sb = new StringBuilder(); if (pkg != null) { sb.append(pkg); sb.append('.'); } for (final Iterator<String> iter = cls.iterator(); iter.hasNext();) { sb.append(iter.next()); if (iter.hasNext()) { sb.append('$'); } } return sb.toString(); } @Override public boolean equals(final Object pOther) { if (this == pOther) { return true; } if (pOther == null || getClass() != pOther.getClass()) { return false; } BinaryName other = (BinaryName) pOther; if (pkg != null ? !pkg.equals(other.pkg) : other.pkg != null) { return false; } if (!cls.equals(other.cls)) { return false; } return true; } @Override public int hashCode() { int result = pkg != null ? pkg.hashCode() : 0; result = 31 * result + cls.hashCode(); return result; } public String getPackage() { return pkg; } /** * Getter. * * @return the simple name of the outer class (even if this binary name represents an inner class) */ public String getOuterSimpleName() { return cls.get(0); } /** * Getter. * * @return the simple name of the inner class represented by this binary name. <code>null</code> if this binary name * does not represent an inner class */ public String getInnerSimpleName() { return cls.size() > 1 ? cls.get(cls.size() - 1) : null; } /** * The fully qualified name of the outer class. * * @return that, or <code>null</code> if the simple name of the outer class is unknown */ @CheckForNull public String getOuterFqcn() { return (pkg != null ? (pkg + ".") : "") + getOuterSimpleName(); } }
checkstyle-addons/checkstyle-addons
src/main/java/com/thomasjensen/checkstyle/addons/checks/BinaryName.java
Java
gpl-3.0
4,699
#include "Board.h" #include <iostream> using namespace std; void Board::enumExts( ) { if(ptester->hasUnboundedHorizAttacks()) { for( int i = 1; i <= nrows; i++ ) if( PiecesInRow[i] > 1 ) { cout << 0 << endl; return; } } _enumExts(); } void Board::_enumExts( ) { Place P(1,1); if( n() != 0 ) { P = top(); if( PiecesInOrBelowRow[P.row] == n() ) { P.row++; P.col = 1; } } while( P.col <= ncols ) { if( ! IsAttacked(P) ) { push(P); if( n() == npieces ) report( ); else _enumExts( ); pop(); } P.col++; } if( n() == 0 ) cout << sol_count << endl; } void Board::print( ) { int row, col; for( row = nrows; row > 0; row-- ) { for( col = 1; col <= ncols; col++) // if(in(row,col)) cout << '*'; else cout << '0'; if(in(row,col)) cout << '#'; else cout << 'O'; cout << endl; } cout << endl; } void Board::report( ) { sol_count++; if( show_boards ) { cout << "Board " << sol_count << ':' << endl; print( ); } } #include "AttackTester.h" static void useage() { cerr << "Options:\n\ --show-boards\n\ --pieces-per-row n1,n2,n3,...nr [default 1,1,1,...]\n\ --nrows m [default 4]\n\ --ncols n [default 4]\n\ --piece queen [default]\n\ --piece king\n\ --piece rook or others added" << endl; exit( 1 ); } int main(int argc, char *argv[]) { int nrows=4; int ncols=4; bool show_boards = false; int A[Board::Maxrows]; bool piecesPerRowGiven = false; AttackTester *ptester = getp("queen"); argc--; argv++; while( argc-- ) { if(!strcmp(*argv,"--show-boards")) { show_boards = true; argv++; continue; } if(!strcmp(*argv,"--pieces-per-row")) { char *p = *(++argv); int i; for(i = 0; (i < Board::Maxrows) && *p!='\0'; i++ ) { A[i] = strtol(p,&p,0); if( *p == ',' ) p++; else if( *p != '\0' ) useage(); } for( ; i < Board::Maxrows; i++ ) A[i] = 1; piecesPerRowGiven = true; argv++; argc--; continue; } if(!strcmp(*argv,"--nrows")) { argv++; argc--; nrows=strtol(*(argv++),NULL,0); continue; } if(!strcmp(*argv,"--ncols")) { argv++; argc--; ncols=strtol(*(argv++),NULL,0); continue; } if(!strcmp(*argv,"--piece")) { argv++; argc--; ptester = getp(*(argv++)); if( !ptester ) { cerr << "Unimplemented Piece:" << *(argv - 1) << endl; exit ( 1 ); } continue; } } if(piecesPerRowGiven) { Board myBoard(nrows, ncols, ptester, show_boards, A); myBoard.enumExts( ); } else { Board myBoard(nrows, ncols, ptester, show_boards, NULL ); myBoard.enumExts( ); } return 0; }
chaikens/MathResearchPrograms
Queens/Ver2/Board.cpp
C++
gpl-3.0
2,775
/* * $Id: LeftJoin.java,v 1.2 2006/04/09 12:13:12 laddi Exp $ * Created on 5.10.2004 * * Copyright (C) 2004 Idega Software hf. All Rights Reserved. * * This software is the proprietary information of Idega hf. * Use is subject to license terms. */ package com.idega.data.query; import java.util.HashSet; import java.util.Set; import com.idega.data.query.output.Output; import com.idega.data.query.output.Outputable; import com.idega.data.query.output.ToStringer; /** * * Last modified: $Date: 2006/04/09 12:13:12 $ by $Author: laddi $ * * @author <a href="mailto:[email protected]">Gudmundur Agust Saemundsson</a> * @version $Revision: 1.2 $ */ public class LeftJoin implements Outputable { private Column left, right; public LeftJoin(Column left, Column right) { this.left = left; this.right = right; } public Column getLeftColumn() { return this.left; } public Column getRightColumn() { return this.right; } @Override public void write(Output out) { out.print(this.left.getTable()) .print(" left join ") .print(this.right.getTable()) .print(" on ") .print(this.left) .print(" = ") .print(this.right); } public Set<Table> getTables(){ Set<Table> s = new HashSet<Table>(); s.add(this.left.getTable()); s.add(this.right.getTable()); return s; } @Override public String toString() { return ToStringer.toString(this); } }
idega/com.idega.core
src/java/com/idega/data/query/LeftJoin.java
Java
gpl-3.0
1,467
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Partial Class fAwards Inherits System.Windows.Forms.Form 'Form overrides dispose to clean up the component list. <System.Diagnostics.DebuggerNonUserCode()> _ Protected Overrides Sub Dispose(ByVal disposing As Boolean) Try If disposing AndAlso components IsNot Nothing Then components.Dispose() End If Finally MyBase.Dispose(disposing) End Try End Sub 'Required by the Windows Form Designer Private components As System.ComponentModel.IContainer 'NOTE: The following procedure is required by the Windows Form Designer 'It can be modified using the Windows Form Designer. 'Do not modify it using the code editor. <System.Diagnostics.DebuggerStepThrough()> _ Private Sub InitializeComponent() Me.components = New System.ComponentModel.Container() Me.Timer1 = New System.Windows.Forms.Timer(Me.components) Me.ListBox3 = New System.Windows.Forms.ListBox() Me.lst_Awards = New System.Windows.Forms.ListBox() Me.SlcTheme1 = New dsTycoon.SLCTheme() Me.GroupBox1 = New System.Windows.Forms.GroupBox() Me.Label1 = New System.Windows.Forms.Label() Me.Button2 = New dsTycoon.SLCbtn() Me.SlcTheme1.SuspendLayout() Me.GroupBox1.SuspendLayout() Me.SuspendLayout() ' 'Timer1 ' ' 'ListBox3 ' Me.ListBox3.FormattingEnabled = True Me.ListBox3.Location = New System.Drawing.Point(565, 430) Me.ListBox3.Name = "ListBox3" Me.ListBox3.Size = New System.Drawing.Size(97, 56) Me.ListBox3.TabIndex = 12 Me.ListBox3.Visible = False ' 'lst_Awards ' Me.lst_Awards.FormattingEnabled = True Me.lst_Awards.Location = New System.Drawing.Point(12, 430) Me.lst_Awards.Name = "lst_Awards" Me.lst_Awards.Size = New System.Drawing.Size(59, 30) Me.lst_Awards.TabIndex = 109 Me.lst_Awards.Visible = False ' 'SlcTheme1 ' Me.SlcTheme1.BackColor = System.Drawing.Color.FromArgb(CType(CType(0, Byte), Integer), CType(CType(57, Byte), Integer), CType(CType(72, Byte), Integer)) Me.SlcTheme1.BorderStyle = System.Windows.Forms.FormBorderStyle.None Me.SlcTheme1.Controls.Add(Me.GroupBox1) Me.SlcTheme1.Controls.Add(Me.Button2) Me.SlcTheme1.Controls.Add(Me.ListBox3) Me.SlcTheme1.Customization = "JRIV/zYjIP82IyD/JRIV/w==" Me.SlcTheme1.Dock = System.Windows.Forms.DockStyle.Fill Me.SlcTheme1.Font = New System.Drawing.Font("Verdana", 8.0!) Me.SlcTheme1.Image = Nothing Me.SlcTheme1.Location = New System.Drawing.Point(0, 0) Me.SlcTheme1.Movable = True Me.SlcTheme1.Name = "SlcTheme1" Me.SlcTheme1.NoRounding = False Me.SlcTheme1.Sizable = True Me.SlcTheme1.Size = New System.Drawing.Size(681, 472) Me.SlcTheme1.SmartBounds = True Me.SlcTheme1.StartPosition = System.Windows.Forms.FormStartPosition.WindowsDefaultLocation Me.SlcTheme1.TabIndex = 110 Me.SlcTheme1.TransparencyKey = System.Drawing.Color.Fuchsia Me.SlcTheme1.Transparent = False ' 'GroupBox1 ' Me.GroupBox1.BackColor = System.Drawing.Color.WhiteSmoke Me.GroupBox1.BackgroundImage = Global.dsTycoon.My.Resources.Resources.gameawards1 Me.GroupBox1.Controls.Add(Me.Label1) Me.GroupBox1.Location = New System.Drawing.Point(32, 24) Me.GroupBox1.Name = "GroupBox1" Me.GroupBox1.Size = New System.Drawing.Size(630, 400) Me.GroupBox1.TabIndex = 13 Me.GroupBox1.TabStop = False ' 'Label1 ' Me.Label1.Location = New System.Drawing.Point(6, 379) Me.Label1.Name = "Label1" Me.Label1.Size = New System.Drawing.Size(402, 357) Me.Label1.TabIndex = 0 Me.Label1.Text = "Label1" ' 'Button2 ' Me.Button2.Colors = New dsTycoon.Bloom(-1) {} Me.Button2.Customization = "" Me.Button2.Font = New System.Drawing.Font("Verdana", 8.0!) Me.Button2.Image = Nothing Me.Button2.Location = New System.Drawing.Point(313, 430) Me.Button2.Name = "Button2" Me.Button2.NoRounding = False Me.Button2.Size = New System.Drawing.Size(78, 22) Me.Button2.TabIndex = 10 Me.Button2.Text = " Accept" Me.Button2.Transparent = False ' 'fAwards ' Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!) Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.BackColor = System.Drawing.Color.FromArgb(CType(CType(0, Byte), Integer), CType(CType(57, Byte), Integer), CType(CType(72, Byte), Integer)) Me.ClientSize = New System.Drawing.Size(681, 472) Me.Controls.Add(Me.lst_Awards) Me.Controls.Add(Me.SlcTheme1) Me.DoubleBuffered = True Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None Me.MaximizeBox = False Me.Name = "fAwards" Me.Text = "Dev Studio Tycoon Awards" Me.TransparencyKey = System.Drawing.Color.Fuchsia Me.SlcTheme1.ResumeLayout(False) Me.GroupBox1.ResumeLayout(False) Me.ResumeLayout(False) End Sub Friend WithEvents Timer1 As System.Windows.Forms.Timer Friend WithEvents ListBox3 As System.Windows.Forms.ListBox Friend WithEvents lst_Awards As System.Windows.Forms.ListBox Friend WithEvents SlcTheme1 As dsTycoon.SLCTheme Friend WithEvents Button2 As dsTycoon.SLCbtn Friend WithEvents GroupBox1 As System.Windows.Forms.GroupBox Friend WithEvents Label1 As System.Windows.Forms.Label End Class
rkrehn/devstudiotycoon
fAwards.Designer.vb
Visual Basic
gpl-3.0
6,024
--- title: "मेरा इस्तीफा राफेल को लेकर हुआ है : तारिक अनवर" layout: item category: ["politics"] date: 2018-09-29T04:19:03.930Z image: 1538214543927tariq.jpg --- <p>नई दिल्ली: राष्ट्रवादी कांग्रेस पार्टी (एनसीपी) और लोकसभा सदस्यता से इस्तीफा दे चुके वरिष्ठ नेता तारिक अनवर का कहना है कि &#39;मेरी नाराजगी राफेल को लेकर पार्टी से है. देश में राफेल घोटाला हुआ, लेकिन जो पवार साहब (शरद पवार) का बयान आया वह ठीक नहीं था. मेरा इस्तीफा राफेल को लेकर हुआ है.&#39;</p> <p>तारिक अनवर से जब पूछा गया कि अब एनसीपी कह रही है कि पवार साहब का इंटरव्यू तोड़मरोड़ के दिखाया गया? तो अनवर ने कहा कि यह क्लेरिफिकेशन देने में एनसीपी ने बहुत देर कर दी है. अब मैं अपना फैसला ले चुका हूं.</p> <p>कयास लग रहे हैं कि आप कांग्रेस में जा रहे हैं? इस सवाल पर तारिक अनवर ने कहा कि अभी कुछ कहना जल्दबाज़ी होगी. मैं दिल्ली आया हूं, कार्यकर्ताओं से बात करूंगा. पर जो करूंगा वह बीजेपी के खिलाफ होगा.</p> <p>जब उनसे पूछा कि महागठबंधन में भी क्या आपकी कोई भूमिका रहेगी अब? तो तारिक अनवर ने कहा कि हां मेरी सारी लाइक माइंडेड पार्टियों को साथ लेने की कोशिश रहेगी. राफेल देश में बड़ा घोटाला है.</p>
InstantKhabar/_source
_source/news/2018-09-29-tariq.html
HTML
gpl-3.0
2,466
package it.emarolab.owloop.descriptor.utility.classDescriptor; import it.emarolab.amor.owlInterface.OWLReferences; import it.emarolab.owloop.descriptor.construction.descriptorEntitySet.Individuals; import it.emarolab.owloop.descriptor.construction.descriptorExpression.ClassExpression; import it.emarolab.owloop.descriptor.construction.descriptorGround.ClassGround; import it.emarolab.owloop.descriptor.utility.individualDescriptor.LinkIndividualDesc; import org.semanticweb.owlapi.model.OWLClass; import org.semanticweb.owlapi.model.OWLNamedIndividual; import java.util.List; /** * This is an example of a 'simple' Class Descriptor that implements 1 ClassExpression (aka {@link ClassExpression}) interface: * <ul> * <li><b>{@link ClassExpression.Instance}</b>: to describe an Individual of a Class.</li> * </ul> * * See {@link FullClassDesc} for an example of a 'compound' Class Descriptor that implements all ClassExpressions (aka {@link ClassExpression}). * <p> * <div style="text-align:center;"><small> * <b>File</b>: it.emarolab.owloop.core.Axiom <br> * <b>Licence</b>: GNU GENERAL PUBLIC LICENSE. Version 3, 29 June 2007 <br> * <b>Authors</b>: Buoncompagni Luca ([email protected]), Syed Yusha Kareem ([email protected]) <br> * <b>affiliation</b>: EMAROLab, DIBRIS, University of Genoa. <br> * <b>date</b>: 01/05/19 <br> * </small></div> */ public class InstanceClassDesc extends ClassGround implements ClassExpression.Instance<LinkIndividualDesc> { private Individuals individuals = new Individuals(); /* Constructors from class: ClassGround */ public InstanceClassDesc(OWLClass instance, OWLReferences onto) { super(instance, onto); } public InstanceClassDesc(String instanceName, OWLReferences onto) { super(instanceName, onto); } public InstanceClassDesc(OWLClass instance, String ontoName) { super(instance, ontoName); } public InstanceClassDesc(OWLClass instance, String ontoName, String filePath, String iriPath) { super(instance, ontoName, filePath, iriPath); } public InstanceClassDesc(OWLClass instance, String ontoName, String filePath, String iriPath, boolean bufferingChanges) { super(instance, ontoName, filePath, iriPath, bufferingChanges); } public InstanceClassDesc(String instanceName, String ontoName) { super(instanceName, ontoName); } public InstanceClassDesc(String instanceName, String ontoName, String filePath, String iriPath) { super(instanceName, ontoName, filePath, iriPath); } public InstanceClassDesc(String instanceName, String ontoName, String filePath, String iriPath, boolean bufferingChanges) { super(instanceName, ontoName, filePath, iriPath, bufferingChanges); } /* Overriding methods in class: ClassGround */ // To read axioms from an ontology @Override public List<MappingIntent> readAxioms() { return Instance.super.readAxioms(); } // To write axioms to an ontology @Override public List<MappingIntent> writeAxioms() { return Instance.super.writeAxioms(); } /* Overriding methods in classes: Class and ClassExpression */ // Is used by the descriptors's build() method. It's possible to change the return type based on need. @Override public LinkIndividualDesc getIndividualDescriptor(OWLNamedIndividual instance, OWLReferences ontology) { return new LinkIndividualDesc( instance, ontology); } // It returns Individuals from the EntitySet (after being read from the ontology) @Override public Individuals getIndividuals() { return individuals; } /* Overriding method in class: Object */ // To show internal state of the Descriptor @Override public String toString() { return getClass().getSimpleName() + "{" + "\n" + "\n" + "\t" + getGround() + ":" + "\n" + "\n" + "\t\t⇐ " + individuals + "\n" + "}" + "\n"; } }
EmaroLab/owloop
src/main/java/it/emarolab/owloop/descriptor/utility/classDescriptor/InstanceClassDesc.java
Java
gpl-3.0
4,115
// -*- Mode: Go; indent-tabs-mode: t -*- /* * Copyright (C) 2016 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 store import ( "io" "net/http" "net/url" "github.com/juju/ratelimit" "golang.org/x/net/context" "gopkg.in/retry.v1" "github.com/snapcore/snapd/overlord/auth" "github.com/snapcore/snapd/progress" "github.com/snapcore/snapd/snap" "github.com/snapcore/snapd/testutil" ) var ( HardLinkCount = hardLinkCount ApiURL = apiURL Download = download UseDeltas = useDeltas ApplyDelta = applyDelta AuthLocation = authLocation AuthURL = authURL StoreURL = storeURL StoreDeveloperURL = storeDeveloperURL MustBuy = mustBuy RequestStoreMacaroon = requestStoreMacaroon DischargeAuthCaveat = dischargeAuthCaveat RefreshDischargeMacaroon = refreshDischargeMacaroon RequestStoreDeviceNonce = requestStoreDeviceNonce RequestDeviceSession = requestDeviceSession LoginCaveatID = loginCaveatID JsonContentType = jsonContentType SnapActionFields = snapActionFields ) // MockDefaultRetryStrategy mocks the retry strategy used by several store requests func MockDefaultRetryStrategy(t *testutil.BaseTest, strategy retry.Strategy) { originalDefaultRetryStrategy := defaultRetryStrategy defaultRetryStrategy = strategy t.AddCleanup(func() { defaultRetryStrategy = originalDefaultRetryStrategy }) } func MockConnCheckStrategy(t *testutil.BaseTest, strategy retry.Strategy) { originalConnCheckStrategy := connCheckStrategy connCheckStrategy = strategy t.AddCleanup(func() { connCheckStrategy = originalConnCheckStrategy }) } func (cm *CacheManager) CacheDir() string { return cm.cacheDir } func (cm *CacheManager) Cleanup() error { return cm.cleanup() } func (cm *CacheManager) Count() int { return cm.count() } func MockOsRemove(f func(name string) error) func() { oldOsRemove := osRemove osRemove = f return func() { osRemove = oldOsRemove } } func MockDownload(f func(ctx context.Context, name, sha3_384, downloadURL string, user *auth.UserState, s *Store, w io.ReadWriteSeeker, resume int64, pbar progress.Meter, dlOpts *DownloadOptions) error) (restore func()) { origDownload := download download = f return func() { download = origDownload } } func MockApplyDelta(f func(name string, deltaPath string, deltaInfo *snap.DeltaInfo, targetPath string, targetSha3_384 string) error) (restore func()) { origApplyDelta := applyDelta applyDelta = f return func() { applyDelta = origApplyDelta } } func (sto *Store) MockCacher(obs downloadCache) (restore func()) { oldCacher := sto.cacher sto.cacher = obs return func() { sto.cacher = oldCacher } } func (sto *Store) SetDeltaFormat(dfmt string) { sto.deltaFormat = dfmt } func (sto *Store) DownloadDelta(deltaName string, downloadInfo *snap.DownloadInfo, w io.ReadWriteSeeker, pbar progress.Meter, user *auth.UserState) error { return sto.downloadDelta(deltaName, downloadInfo, w, pbar, user) } func (sto *Store) DoRequest(ctx context.Context, client *http.Client, reqOptions *requestOptions, user *auth.UserState) (*http.Response, error) { return sto.doRequest(ctx, client, reqOptions, user) } func (sto *Store) Client() *http.Client { return sto.client } func (sto *Store) DetailFields() []string { return sto.detailFields } func (sto *Store) DecorateOrders(snaps []*snap.Info, user *auth.UserState) error { return sto.decorateOrders(snaps, user) } func (cfg *Config) SetBaseURL(u *url.URL) error { return cfg.setBaseURL(u) } func NewHashError(name, sha3_384, targetSha3_384 string) HashError { return HashError{name, sha3_384, targetSha3_384} } func NewRequestOptions(mth string, url *url.URL) *requestOptions { return &requestOptions{ Method: mth, URL: url, } } func MockRatelimitReader(f func(r io.Reader, bucket *ratelimit.Bucket) io.Reader) (restore func()) { oldRatelimitReader := ratelimitReader ratelimitReader = f return func() { ratelimitReader = oldRatelimitReader } }
kenvandine/snapd
store/export_test.go
GO
gpl-3.0
4,569
using System; using System.Threading; using System.Windows.Input; namespace WpfAsyncPack.Internal { internal sealed class CancelAsyncCommand : ICommand { private CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource(); private bool _isCommandExecuting; public event EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } public CancellationToken Token => _cancellationTokenSource.Token; void ICommand.Execute(object parameter) { _cancellationTokenSource.Cancel(); RaiseCanExecuteChanged(); } bool ICommand.CanExecute(object parameter) { return _isCommandExecuting && !_cancellationTokenSource.IsCancellationRequested; } public void NotifyCommandStarting() { _isCommandExecuting = true; if (_cancellationTokenSource.IsCancellationRequested) { _cancellationTokenSource = new CancellationTokenSource(); RaiseCanExecuteChanged(); } } public void NotifyCommandFinished() { _isCommandExecuting = false; RaiseCanExecuteChanged(); } private static void RaiseCanExecuteChanged() { CommandManager.InvalidateRequerySuggested(); } } }
kirmir/WpfAsyncPack
WpfAsyncPack/Internal/CancelAsyncCommand.cs
C#
gpl-3.0
1,497
<template name="views_contracts"> <div class="dapp-container"> <h1>{{i18n "wallet.contracts.contractTitle"}}</h1> <a href="{{pathFor route='deployContract'}}" class="wallet-box create"> <div class="account-pattern"> + </div> <h3>{{i18n "wallet.contracts.deployNewContract"}}</h3> </a> <h2>{{i18n "wallet.contracts.customContracts"}}</h2> <p>{{i18n "wallet.contracts.description" }}</p> <div class="dapp-clear-fix"></div> <div class="wallet-box-list"> {{#each customContracts}} {{> elements_account account=_id isContract=true}} {{/each}} </div> <button class="wallet-box create add-contract"> <div class="account-pattern"> + </div> <h3>{{i18n "wallet.contracts.addCustomContract"}}</h3> </button> <div class="dapp-clear-fix"></div> <br><br> <h2>{{{i18n "wallet.tokens.title"}}}</h2> <p> {{{i18n "wallet.tokens.description"}}} </p> <div class="dapp-clear-fix"></div> <div class="wallet-box-list"> {{#each tokens}} {{> elements_tokenBox}} {{/each}} </div> <button class="wallet-box create add-token"> <div class="account-pattern"> + </div> <h3>{{i18n "wallet.app.buttons.addToken"}}</h3> </button> </div> </template>
Davidyuk/Hackathon2017
app/client/templates/views/contracts.html
HTML
gpl-3.0
1,528
<?php /** * The file that defines the core plugin class * * A class definition that includes attributes and functions used across both the * public-facing side of the site and the admin area. * * @link http://stephanetauziede.com * @since 1.0.0 * * @package Wp_Startup_Press_Room * @subpackage Wp_Startup_Press_Room/includes */ /** * The core plugin class. * * This is used to define internationalization, admin-specific hooks, and * public-facing site hooks. * * Also maintains the unique identifier of this plugin as well as the current * version of the plugin. * * @since 1.0.0 * @package Wp_Startup_Press_Room * @subpackage Wp_Startup_Press_Room/includes * @author Stephane Tauziede <[email protected]> */ class Wp_Startup_Press_Room { /** * The loader that's responsible for maintaining and registering all hooks that power * the plugin. * * @since 1.0.0 * @access protected * @var Wp_Startup_Press_Room_Loader $loader Maintains and registers all hooks for the plugin. */ protected $loader; /** * The unique identifier of this plugin. * * @since 1.0.0 * @access protected * @var string $plugin_name The string used to uniquely identify this plugin. */ protected $plugin_name; /** * The current version of the plugin. * * @since 1.0.0 * @access protected * @var string $version The current version of the plugin. */ protected $version; /** * Define the core functionality of the plugin. * * Set the plugin name and the plugin version that can be used throughout the plugin. * Load the dependencies, define the locale, and set the hooks for the admin area and * the public-facing side of the site. * * @since 1.0.0 */ public function __construct() { $this->plugin_name = 'wp-startup-press-room'; $this->version = '1.0.0'; $this->load_dependencies(); $this->set_locale(); $this->define_admin_hooks(); $this->define_public_hooks(); } /** * Load the required dependencies for this plugin. * * Include the following files that make up the plugin: * * - Wp_Startup_Press_Room_Loader. Orchestrates the hooks of the plugin. * - Wp_Startup_Press_Room_i18n. Defines internationalization functionality. * - Wp_Startup_Press_Room_Admin. Defines all hooks for the admin area. * - Wp_Startup_Press_Room_Public. Defines all hooks for the public side of the site. * * Create an instance of the loader which will be used to register the hooks * with WordPress. * * @since 1.0.0 * @access private */ private function load_dependencies() { /** * The class responsible for orchestrating the actions and filters of the * core plugin. */ require_once plugin_dir_path( dirname( __FILE__ ) ) . 'includes/class-wp-startup-press-room-loader.php'; /** * The class responsible for defining internationalization functionality * of the plugin. */ require_once plugin_dir_path( dirname( __FILE__ ) ) . 'includes/class-wp-startup-press-room-i18n.php'; /** * The class responsible for defining all actions that occur in the admin area. */ require_once plugin_dir_path( dirname( __FILE__ ) ) . 'admin/class-wp-startup-press-room-admin.php'; /** * The class responsible for PR options page in the admin area. */ require_once plugin_dir_path( dirname( __FILE__ ) ) . 'admin/class-wp-startup-press-room-options.php'; /** * The class responsible for defining all actions that occur in the public-facing * side of the site. */ require_once plugin_dir_path( dirname( __FILE__ ) ) . 'public/class-wp-startup-press-room-public.php'; $this->loader = new Wp_Startup_Press_Room_Loader(); // Required files for registering the post type and taxonomies. require_once plugin_dir_path( dirname( __FILE__ ) ) . 'includes/class-post-type-registrations.php'; require_once plugin_dir_path( dirname( __FILE__ ) ) . 'includes/class-post-type-metaboxes.php'; // Instantiate registration class, so we can add it as a dependency to main plugin class. $post_type_registrations = new PR_Post_Type_Registrations; // Register callback that is fired when the plugin is activated. register_activation_hook( __FILE__, array( $post_type, 'activate' ) ); // Initialize registrations for post-activation requests. $post_type_registrations->init(); // Initialize metaboxes //$post_type_metaboxes = new PR_Meta_Box; //$post_type_metaboxes->init(); } /** * Define the locale for this plugin for internationalization. * * Uses the Wp_Startup_Press_Room_i18n class in order to set the domain and to register the hook * with WordPress. * * @since 1.0.0 * @access private */ private function set_locale() { $plugin_i18n = new Wp_Startup_Press_Room_i18n(); $this->loader->add_action( 'plugins_loaded', $plugin_i18n, 'load_plugin_textdomain' ); } /** * Register all of the hooks related to the admin area functionality * of the plugin. * * @since 1.0.0 * @access private */ private function define_admin_hooks() { $plugin_admin = new Wp_Startup_Press_Room_Admin( $this->get_plugin_name(), $this->get_version() ); $this->loader->add_action( 'admin_enqueue_scripts', $plugin_admin, 'enqueue_styles' ); $this->loader->add_action( 'admin_enqueue_scripts', $plugin_admin, 'enqueue_scripts' ); } /** * Register all of the hooks related to the public-facing functionality * of the plugin. * * @since 1.0.0 * @access private */ private function define_public_hooks() { $plugin_public = new Wp_Startup_Press_Room_Public( $this->get_plugin_name(), $this->get_version() ); $this->loader->add_action( 'wp_enqueue_scripts', $plugin_public, 'enqueue_styles' ); $this->loader->add_action( 'wp_enqueue_scripts', $plugin_public, 'enqueue_scripts' ); } /** * Run the loader to execute all of the hooks with WordPress. * * @since 1.0.0 */ public function run() { $this->loader->run(); } /** * The name of the plugin used to uniquely identify it within the context of * WordPress and to define internationalization functionality. * * @since 1.0.0 * @return string The name of the plugin. */ public function get_plugin_name() { return $this->plugin_name; } /** * The reference to the class that orchestrates the hooks with the plugin. * * @since 1.0.0 * @return Wp_Startup_Press_Room_Loader Orchestrates the hooks of the plugin. */ public function get_loader() { return $this->loader; } /** * Retrieve the version number of the plugin. * * @since 1.0.0 * @return string The version number of the plugin. */ public function get_version() { return $this->version; } }
stauziede/WP-Startup-Press-Room
includes/class-wp-startup-press-room.php
PHP
gpl-3.0
6,889
drop table if exists users; create table users ( id serial primary key, username varchar(128) not null, password varchar(128) not null, favorites text not null, minute integer, disabled boolean not null); drop table if exists messages; create table messages ( id serial primary key, user_id integer references users (id), message text not null, created_at timestamp not null);
alawibaba/autoseamless
schema.sql
SQL
gpl-3.0
458
/** * Copyright (c) 2006-2014 LOVE Development Team * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. **/ #ifndef LOVE_JOYSTICK_WRAP_JOYSTICK_H #define LOVE_JOYSTICK_WRAP_JOYSTICK_H // LOVE #include "common/config.h" #include "Joystick.h" #include "common/runtime.h" namespace love { namespace joystick { Joystick *luax_checkjoystick(lua_State *L, int idx); int w_Joystick_isConnected(lua_State *L); int w_Joystick_getName(lua_State *L); int w_Joystick_getID(lua_State *L); int w_Joystick_getGUID(lua_State *L); int w_Joystick_getAxisCount(lua_State *L); int w_Joystick_getButtonCount(lua_State *L); int w_Joystick_getHatCount(lua_State *L); int w_Joystick_getAxis(lua_State *L); int w_Joystick_getAxes(lua_State *L); int w_Joystick_getHat(lua_State *L); int w_Joystick_isDown(lua_State *L); int w_Joystick_isGamepad(lua_State *L); int w_Joystick_getGamepadAxis(lua_State *L); int w_Joystick_isGamepadDown(lua_State *L); int w_Joystick_isVibrationSupported(lua_State *L); int w_Joystick_setVibration(lua_State *L); int w_Joystick_getVibration(lua_State *L); extern "C" int luaopen_joystick(lua_State *L); } // joystick } // love #endif // LOVE_JOYSTICK_SDL_WRAP_JOYSTICK_H
albertz/love
src/modules/joystick/wrap_Joystick.h
C
gpl-3.0
1,996
/* Copyright (C) 2011 Srivats P. This file is part of "Ostinato" This 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 _ETH2_PDML_H #define _ETH2_PDML_H #include "pdmlprotocol.h" class PdmlEthProtocol : public PdmlProtocol { public: static PdmlProtocol* createInstance(); virtual void unknownFieldHandler(QString name, int pos, int size, const QXmlStreamAttributes &attributes, OstProto::Protocol *pbProto, OstProto::Stream *stream); virtual void postProtocolHandler(OstProto::Protocol *pbProto, OstProto::Stream *stream); protected: PdmlEthProtocol(); }; #endif
pstavirs/ostinato
common/eth2pdml.h
C
gpl-3.0
1,185
/* * Copyright 2013, winocm. <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * If you are going to use this software in any form that does not involve * releasing the source to this project or improving it, let me know beforehand. * * 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. */ /* * Compatibility support to bridge old pe_arm_xxx api and new * AWESOME SOC DISPATCH STUFF. */ #include <mach/mach_types.h> #include <pexpert/pexpert.h> #include <pexpert/arm/protos.h> #include <pexpert/arm/boot.h> #include <machine/machine_routines.h> #include <kern/debug.h> /** * pe_arm_init_interrupts * * Initialize the SoC dependent interrrupt controller. */ uint32_t pe_arm_init_interrupts(__unused void *args) { if (gPESocDispatch.interrupt_init == NULL) panic("gPESocDispatch.interrupt_init was null, did you forget to set up the table?"); gPESocDispatch.interrupt_init(); return 0; } /** * pe_arm_init_timebase * * Initialize the SoC dependent timebase. */ uint32_t pe_arm_init_timebase(__unused void *args) { if (gPESocDispatch.timebase_init == NULL) panic("gPESocDispatch.timebase_init was null, did you forget to set up the table?"); gPESocDispatch.timebase_init(); return 0; } /** * pe_arm_dispatch_interrupt * * Dispatch IRQ requests to the SoC specific handler. */ boolean_t pe_arm_dispatch_interrupt(void *context) { if (gPESocDispatch.handle_interrupt == NULL) panic("gPESocDispatch.handle_interrupt was null, did you forget to set up the table?"); gPESocDispatch.handle_interrupt(context); return TRUE; } /** * pe_arm_get_timebase * * Get current system timebase from the SoC handler. */ uint64_t pe_arm_get_timebase(__unused void *args) { if (gPESocDispatch.get_timebase == NULL) panic("gPESocDispatch.get_timebase was null, did you forget to set up the table?"); return gPESocDispatch.get_timebase(); } /** * pe_arm_set_timer_enabled * * Set platform timer enabled status. */ void pe_arm_set_timer_enabled(boolean_t enable) { if (gPESocDispatch.timer_enabled == NULL) panic("gPESocDispatch.timer_enabled was null, did you forget to set up the table?"); gPESocDispatch.timer_enabled(enable); } /* * iOS like functionality. */ uint32_t debug_enabled = 1; uint32_t PE_i_can_has_debugger(uint32_t * pe_debug) { if (pe_debug) { if (debug_enabled) *pe_debug = 1; else *pe_debug = 0; } return debug_enabled; } uint32_t PE_get_security_epoch(void) { return 0; }
p01arst0rm/decorum-linux
_resources/kernels/xnu-arm/pexpert/arm/common/pe_armsupport.c
C
gpl-3.0
3,815
<?php /* * AJGL CSV RFC Component * * Copyright (C) Antonio J. García Lagar <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Ajgl\Csv\Rfc\Tests\Spl; use Ajgl\Csv\Rfc\Spl\SplFileObject; /** * @author Antonio J. García Lagar <[email protected]> */ class SplFileObjectTest extends AbstractSplFileObjectTest { protected function buildFileObject() { return new SplFileObject('php://temp', 'w+'); } }
moodlerooms/moodle-local_xray
vendor/ajgl/csv-rfc/tests/Spl/SplFileObjectTest.php
PHP
gpl-3.0
541
package com.example.habitup.View; import android.content.Context; import android.content.res.Resources; import android.graphics.Color; import android.support.v4.content.ContextCompat; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import com.example.habitup.Model.Attributes; import com.example.habitup.Model.Habit; import com.example.habitup.R; import java.util.ArrayList; /** * This is the adapter for creating the habit list, which displays the habit name, and * it's schedule. * * @author Shari Barboza */ public class HabitListAdapter extends ArrayAdapter<Habit> { // The habits array private ArrayList<Habit> habits; public HabitListAdapter(Context context, int resource, ArrayList<Habit> habits) { super(context, resource, habits); this.habits = habits; } @Override public View getView(int position, View view, ViewGroup viewGroup) { View v = view; // Inflate a new view if (v == null) { LayoutInflater inflater = LayoutInflater.from(getContext()); v = inflater.inflate(R.layout.habit_list_item, null); } // Get the habit Habit habit = habits.get(position); String attributeName = habit.getHabitAttribute(); String attributeColour = Attributes.getColour(attributeName); // Set the name of the habit TextView habitNameView = v.findViewById(R.id.habit_name); habitNameView.setText(habit.getHabitName()); habitNameView.setTextColor(Color.parseColor(attributeColour)); // Get habit schedule boolean[] schedule = habit.getHabitSchedule(); View monView = v.findViewById(R.id.mon_box); View tueView = v.findViewById(R.id.tue_box); View wedView = v.findViewById(R.id.wed_box); View thuView = v.findViewById(R.id.thu_box); View friView = v.findViewById(R.id.fri_box); View satView = v.findViewById(R.id.sat_box); View sunView = v.findViewById(R.id.sun_box); View[] textViews = {monView, tueView, wedView, thuView, friView, satView, sunView}; // Display days of the month for the habit's schedule for (int i = 1; i < schedule.length; i++) { if (schedule[i]) { textViews[i-1].setVisibility(View.VISIBLE); } else { textViews[i-1].setVisibility(View.GONE); } } return v; } }
CMPUT301F17T29/HabitUp
app/src/main/java/com/example/habitup/View/HabitListAdapter.java
Java
gpl-3.0
2,677
#!/usr/bin/env python # coding=utf-8 """30. Digit fifth powers https://projecteuler.net/problem=30 Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits: > 1634 = 14 \+ 64 \+ 34 \+ 44 > 8208 = 84 \+ 24 \+ 04 \+ 84 > 9474 = 94 \+ 44 \+ 74 \+ 44 As 1 = 14 is not a sum it is not included. The sum of these numbers is 1634 + 8208 + 9474 = 19316. Find the sum of all the numbers that can be written as the sum of fifth powers of their digits. """
openqt/algorithms
projecteuler/pe030-digit-fifth-powers.py
Python
gpl-3.0
507
#include <stdio.h> #include <string.h> #include "stdbool.h" #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "esp_system.h" #include "esp_log.h" #include "bt.h" #define GATTS_TAG "MAIN" #define HCI_H4_CMD_PREAMBLE_SIZE (4) /* HCI Command opcode group field(OGF) */ #define HCI_GRP_HOST_CONT_BASEBAND_CMDS (0x03 << 10) /* 0x0C00 */ #define HCI_GRP_BLE_CMDS (0x08 << 10) #define HCI_RESET (0x0003 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) #define HCI_BLE_WRITE_ADV_ENABLE (0x000A | HCI_GRP_BLE_CMDS) #define HCI_BLE_WRITE_ADV_PARAMS (0x0006 | HCI_GRP_BLE_CMDS) #define HCI_BLE_WRITE_ADV_DATA (0x0008 | HCI_GRP_BLE_CMDS) #define HCIC_PARAM_SIZE_WRITE_ADV_ENABLE (1) #define HCIC_PARAM_SIZE_BLE_WRITE_ADV_PARAMS (15) #define HCIC_PARAM_SIZE_BLE_WRITE_ADV_DATA (31) #define BD_ADDR_LEN (6) /* Device address length */ typedef uint8_t bd_addr_t[BD_ADDR_LEN]; /* Device address */ #define UINT16_TO_STREAM(p, u16) {*(p)++ = (uint8_t)(u16); *(p)++ = (uint8_t)((u16) >> 8);} #define UINT8_TO_STREAM(p, u8) {*(p)++ = (uint8_t)(u8);} #define BDADDR_TO_STREAM(p, a) {int ijk; for (ijk = 0; ijk < BD_ADDR_LEN; ijk++) *(p)++ = (uint8_t) a[BD_ADDR_LEN - 1 - ijk];} #define ARRAY_TO_STREAM(p, a, len) {int ijk; for (ijk = 0; ijk < len; ijk++) *(p)++ = (uint8_t) a[ijk];} enum { H4_TYPE_COMMAND = 1, H4_TYPE_ACL = 2, H4_TYPE_SCO = 3, H4_TYPE_EVENT = 4 }; static uint8_t hci_cmd_buf[128]; /* * @brief: BT controller callback function, used to notify the upper layer that * controller is ready to receive command */ static void controller_rcv_pkt_ready(void) { printf("controller rcv pkt ready\n"); } /* * @brief: BT controller callback function, to transfer data packet to upper * controller is ready to receive command */ static int host_rcv_pkt(uint8_t *data, uint16_t len) { printf("host rcv pkt: "); for (uint16_t i=0; i<len; i++) printf("%02x", data[i]); printf("\n"); return 0; } static esp_vhci_host_callback_t vhci_host_cb = { controller_rcv_pkt_ready, host_rcv_pkt }; static uint16_t make_cmd_reset(uint8_t *buf) { UINT8_TO_STREAM (buf, H4_TYPE_COMMAND); UINT16_TO_STREAM (buf, HCI_RESET); UINT8_TO_STREAM (buf, 0); return HCI_H4_CMD_PREAMBLE_SIZE; } static uint16_t make_cmd_ble_set_adv_enable (uint8_t *buf, uint8_t adv_enable) { UINT8_TO_STREAM (buf, H4_TYPE_COMMAND); UINT16_TO_STREAM (buf, HCI_BLE_WRITE_ADV_ENABLE); UINT8_TO_STREAM (buf, HCIC_PARAM_SIZE_WRITE_ADV_ENABLE); UINT8_TO_STREAM (buf, adv_enable); return HCI_H4_CMD_PREAMBLE_SIZE + HCIC_PARAM_SIZE_WRITE_ADV_ENABLE; } static uint16_t make_cmd_ble_set_adv_param (uint8_t *buf, uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type, uint8_t addr_type_own, uint8_t addr_type_dir, bd_addr_t direct_bda, uint8_t channel_map, uint8_t adv_filter_policy) { UINT8_TO_STREAM (buf, H4_TYPE_COMMAND); UINT16_TO_STREAM (buf, HCI_BLE_WRITE_ADV_PARAMS); UINT8_TO_STREAM (buf, HCIC_PARAM_SIZE_BLE_WRITE_ADV_PARAMS ); UINT16_TO_STREAM (buf, adv_int_min); UINT16_TO_STREAM (buf, adv_int_max); UINT8_TO_STREAM (buf, adv_type); UINT8_TO_STREAM (buf, addr_type_own); UINT8_TO_STREAM (buf, addr_type_dir); BDADDR_TO_STREAM (buf, direct_bda); UINT8_TO_STREAM (buf, channel_map); UINT8_TO_STREAM (buf, adv_filter_policy); return HCI_H4_CMD_PREAMBLE_SIZE + HCIC_PARAM_SIZE_BLE_WRITE_ADV_PARAMS; } static uint16_t make_cmd_ble_set_adv_data(uint8_t *buf, uint8_t data_len, uint8_t *p_data) { UINT8_TO_STREAM (buf, H4_TYPE_COMMAND); UINT16_TO_STREAM (buf, HCI_BLE_WRITE_ADV_DATA); UINT8_TO_STREAM (buf, HCIC_PARAM_SIZE_BLE_WRITE_ADV_DATA + 1); memset(buf, 0, HCIC_PARAM_SIZE_BLE_WRITE_ADV_DATA); if (p_data != NULL && data_len > 0) { if (data_len > HCIC_PARAM_SIZE_BLE_WRITE_ADV_DATA) { data_len = HCIC_PARAM_SIZE_BLE_WRITE_ADV_DATA; } UINT8_TO_STREAM (buf, data_len); ARRAY_TO_STREAM (buf, p_data, data_len); } return HCI_H4_CMD_PREAMBLE_SIZE + HCIC_PARAM_SIZE_BLE_WRITE_ADV_DATA + 1; } static void hci_cmd_send_reset(void) { uint16_t sz = make_cmd_reset (hci_cmd_buf); esp_vhci_host_send_packet(hci_cmd_buf, sz); } static void hci_cmd_send_ble_adv_start(void) { uint16_t sz = make_cmd_ble_set_adv_enable (hci_cmd_buf, 1); esp_vhci_host_send_packet(hci_cmd_buf, sz); } static void hci_cmd_send_ble_set_adv_param(void) { uint16_t adv_intv_min = 256; // 160ms uint16_t adv_intv_max = 256; // 160ms uint8_t adv_type = 0; // connectable undirected advertising (ADV_IND) uint8_t own_addr_type = 0; // Public Device Address uint8_t peer_addr_type = 0; // Public Device Address uint8_t peer_addr[6] = {0x80, 0x81, 0x82, 0x83, 0x84, 0x85}; uint8_t adv_chn_map = 0x07; // 37, 38, 39 uint8_t adv_filter_policy = 0; // Process All Conn and Scan uint16_t sz = make_cmd_ble_set_adv_param(hci_cmd_buf, adv_intv_min, adv_intv_max, adv_type, own_addr_type, peer_addr_type, peer_addr, adv_chn_map, adv_filter_policy); esp_vhci_host_send_packet(hci_cmd_buf, sz); } static void hci_cmd_send_ble_set_adv_data(void) { uint8_t adv_data[31]; uint8_t adv_data_len; adv_data[0] = 2; // Len adv_data[1] = 0x01; // Type Flags adv_data[2] = 0x06; // GENERAL_DISC_MODE 0x02 | BR_EDR_NOT_SUPPORTED 0x04 adv_data[3] = 3; // Len adv_data[4] = 0x03; // Type 16-Bit UUID adv_data[5] = 0xAA; // Eddystone UUID 2 -> 0xFEAA LSB adv_data[6] = 0xFE; // Eddystone UUID 1 MSB adv_data[7] = 19; // Length of Beacon Data adv_data[8] = 0x16; // Type Service Data adv_data[9] = 0xAA; // Eddystone UUID 2 -> 0xFEAA LSB adv_data[10] = 0xFE; // Eddystone UUID 1 MSB adv_data[11] = 0x10; // Eddystone Frame Type adv_data[12] = 0x20; // Beacons TX power at 0m adv_data[13] = 0x03; // URL Scheme 'https://' adv_data[14] = 0x67; // URL add 1 'g' adv_data[15] = 0x6F; // URL add 2 'o' adv_data[16] = 0x6F; // URL add 3 'o' adv_data[17] = 0x2E; // URL add 4 '.' adv_data[18] = 0x67; // URL add 5 'g' adv_data[19] = 0x6C; // URL add 6 'l' adv_data[20] = 0x2F; // URL add 7 '/' adv_data[21] = 0x32; // URL add 8 '2' adv_data[22] = 0x79; // URL add 9 'y' adv_data[23] = 0x43; // URL add 10 'C' adv_data[24] = 0x36; // URL add 11 '6' adv_data[25] = 0x4B; // URL add 12 'K' adv_data[26] = 0x58; // URL add 13 'X' adv_data_len = 27; printf("Eddystone adv_data [%d]=",adv_data_len); for (int i=0; i<adv_data_len; i++) { printf("%02x",adv_data[i]); } printf("\n"); uint16_t sz = make_cmd_ble_set_adv_data(hci_cmd_buf, adv_data_len, (uint8_t *)adv_data); esp_vhci_host_send_packet(hci_cmd_buf, sz); } /* * @brief: send HCI commands to perform BLE advertising; */ void bleAdvtTask(void *pvParameters) { int cmd_cnt = 0; bool send_avail = false; esp_vhci_host_register_callback(&vhci_host_cb); printf("BLE advt task start\n"); while (1) { vTaskDelay(5000 / portTICK_PERIOD_MS); send_avail = esp_vhci_host_check_send_available(); if (send_avail) { switch (cmd_cnt) { case 0: hci_cmd_send_reset(); ++cmd_cnt; break; case 1: hci_cmd_send_ble_set_adv_param(); ++cmd_cnt; break; case 2: hci_cmd_send_ble_set_adv_data(); ++cmd_cnt; break; case 3: hci_cmd_send_ble_adv_start(); ++cmd_cnt; break; } } printf("BLE Advertise, flag_send_avail: %d, cmd_sent: %d\n", send_avail, cmd_cnt); } } int app_main() { esp_err_t ret; esp_bt_controller_config_t bt_cfg = BT_CONTROLLER_INIT_CONFIG_DEFAULT(); ret = esp_bt_controller_init(&bt_cfg); if (ret) { ESP_LOGE(GATTS_TAG, "%s initialize controller failed\n", __func__); return 1; } ret = esp_bt_controller_enable(ESP_BT_MODE_BTDM); if (ret) { ESP_LOGE(GATTS_TAG, "%s enable controller failed\n", __func__); return 1; } xTaskCreatePinnedToCore(&bleAdvtTask, "bleAdvtTask", 2048, NULL, 5, NULL, 0); return 0; }
pcbreflux/espressif
esp32/app/ble_app_eddystone/main/app_bt.c
C
gpl-3.0
8,842
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="ro"> <head> <!-- Generated by javadoc (version 1.7.0_80) on Mon Jun 20 18:37:10 EEST 2016 --> <title>JRPropertiesUtil.PropertySuffix (JasperReports 6.3.0 API)</title> <meta name="date" content="2016-06-20"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="JRPropertiesUtil.PropertySuffix (JasperReports 6.3.0 API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/JRPropertiesUtil.PropertySuffix.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../net/sf/jasperreports/engine/JRPropertiesUtil.html" title="class in net.sf.jasperreports.engine"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../net/sf/jasperreports/engine/JRPropertyExpression.html" title="interface in net.sf.jasperreports.engine"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?net/sf/jasperreports/engine/JRPropertiesUtil.PropertySuffix.html" target="_top">Frames</a></li> <li><a href="JRPropertiesUtil.PropertySuffix.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#field_summary">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field_detail">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">net.sf.jasperreports.engine</div> <h2 title="Class JRPropertiesUtil.PropertySuffix" class="title">Class JRPropertiesUtil.PropertySuffix</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>net.sf.jasperreports.engine.JRPropertiesUtil.PropertySuffix</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>Enclosing class:</dt> <dd><a href="../../../../net/sf/jasperreports/engine/JRPropertiesUtil.html" title="class in net.sf.jasperreports.engine">JRPropertiesUtil</a></dd> </dl> <hr> <br> <pre>public static class <span class="strong">JRPropertiesUtil.PropertySuffix</span> extends java.lang.Object</pre> <div class="block">Class used by <a href="../../../../net/sf/jasperreports/engine/JRPropertiesUtil.html#getProperties(java.lang.String)"><code>JRPropertiesUtil.getProperties(String)</code></a>.</div> <dl><dt><span class="strong">Author:</span></dt> <dd>Lucian Chirita</dd></dl> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- =========== FIELD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="field_summary"> <!-- --> </a> <h3>Field Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation"> <caption><span>Fields</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>protected java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../net/sf/jasperreports/engine/JRPropertiesUtil.PropertySuffix.html#key">key</a></strong></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>protected java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../net/sf/jasperreports/engine/JRPropertiesUtil.PropertySuffix.html#suffix">suffix</a></strong></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>protected java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../net/sf/jasperreports/engine/JRPropertiesUtil.PropertySuffix.html#value">value</a></strong></code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><strong><a href="../../../../net/sf/jasperreports/engine/JRPropertiesUtil.PropertySuffix.html#JRPropertiesUtil.PropertySuffix(java.lang.String,%20java.lang.String,%20java.lang.String)">JRPropertiesUtil.PropertySuffix</a></strong>(java.lang.String&nbsp;key, java.lang.String&nbsp;suffix, java.lang.String&nbsp;value)</code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span>Methods</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../net/sf/jasperreports/engine/JRPropertiesUtil.PropertySuffix.html#getKey()">getKey</a></strong>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../net/sf/jasperreports/engine/JRPropertiesUtil.PropertySuffix.html#getSuffix()">getSuffix</a></strong>()</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../net/sf/jasperreports/engine/JRPropertiesUtil.PropertySuffix.html#getValue()">getValue</a></strong>()</code>&nbsp;</td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ FIELD DETAIL =========== --> <ul class="blockList"> <li class="blockList"><a name="field_detail"> <!-- --> </a> <h3>Field Detail</h3> <a name="key"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>key</h4> <pre>protected final&nbsp;java.lang.String key</pre> </li> </ul> <a name="suffix"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>suffix</h4> <pre>protected final&nbsp;java.lang.String suffix</pre> </li> </ul> <a name="value"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>value</h4> <pre>protected final&nbsp;java.lang.String value</pre> </li> </ul> </li> </ul> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="JRPropertiesUtil.PropertySuffix(java.lang.String, java.lang.String, java.lang.String)"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>JRPropertiesUtil.PropertySuffix</h4> <pre>public&nbsp;JRPropertiesUtil.PropertySuffix(java.lang.String&nbsp;key, java.lang.String&nbsp;suffix, java.lang.String&nbsp;value)</pre> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method_detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="getKey()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getKey</h4> <pre>public&nbsp;java.lang.String&nbsp;getKey()</pre> </li> </ul> <a name="getSuffix()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getSuffix</h4> <pre>public&nbsp;java.lang.String&nbsp;getSuffix()</pre> </li> </ul> <a name="getValue()"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>getValue</h4> <pre>public&nbsp;java.lang.String&nbsp;getValue()</pre> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/JRPropertiesUtil.PropertySuffix.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../net/sf/jasperreports/engine/JRPropertiesUtil.html" title="class in net.sf.jasperreports.engine"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../net/sf/jasperreports/engine/JRPropertyExpression.html" title="interface in net.sf.jasperreports.engine"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?net/sf/jasperreports/engine/JRPropertiesUtil.PropertySuffix.html" target="_top">Frames</a></li> <li><a href="JRPropertiesUtil.PropertySuffix.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#field_summary">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field_detail">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small> <span style="font-decoration:none;font-family:Arial,Helvetica,sans-serif;font-size:8pt;font-style:normal;color:#000000;">&copy; 2001 - 2016 TIBCO Software Inc. <a href="http://www.jaspersoft.com" target="_blank" style="color:#000000;">www.jaspersoft.com</a></span> </small></p> </body> </html>
MHTaleb/Encologim
lib/JasperReport/docs/api/net/sf/jasperreports/engine/JRPropertiesUtil.PropertySuffix.html
HTML
gpl-3.0
12,799
if(NOT DEFINED IMP_TIMEOUT_FACTOR) if(${CMAKE_BUILD_TYPE} MATCHES "Debug") set(IMP_TIMEOUT_FACTOR 3 CACHE INT "A scaling factor for test timeouts") else() set(IMP_TIMEOUT_FACTOR 1 CACHE INT "A scaling factor for test timeouts") endif() endif() set(IMP_CHEAP_TIMEOUT 5 CACHE INT "Timeout for cheap tests") set(IMP_MEDIUM_TIMEOUT 15 CACHE INT "Timeout for medium tests") set(IMP_EXPENSIVE_TIMEOUT 120 CACHE INT "Timeout for expensive tests") set(IMP_CHEAP_COST 1 CACHE INTERNAL "") set(IMP_MEDIUM_COST 2 CACHE INTERNAL "") set(IMP_EXPENSIVE_COST 3 CACHE INTERNAL "") function(imp_add_python_tests modulename length type) set(modulename ${ARGV0}) set(length ${ARGV1}) set(ttype ${ARGV2}) list(REMOVE_AT ARGV 0) list(REMOVE_AT ARGV 0) list(REMOVE_AT ARGV 0) math(EXPR timeout "${IMP_TIMEOUT_FACTOR} * ${IMP_${length}_TIMEOUT}") foreach (test ${ARGV}) get_filename_component(path ${test} ABSOLUTE) GET_FILENAME_COMPONENT(name ${test} NAME) add_test("${modulename}-${name}" ${IMP_TEST_SETUP} python ${path} ${IMP_TEST_ARGUMENTS}) set_tests_properties("${modulename}-${name}" PROPERTIES LABELS "${modulename}-${ttype}-python-${length}") set_tests_properties("${modulename}-${name}" PROPERTIES TIMEOUT ${timeout}) set_tests_properties("${modulename}-${name}" PROPERTIES COST ${IMP_${length}_COST}) if(DEFINED IMP_TESTS_PROPERTIES) set_tests_properties("${modulename}-${name}" PROPERTIES ${IMP_TESTS_PROPERTIES}) endif() endforeach(test) endfunction(imp_add_python_tests) function(imp_add_cpp_tests modulename length output target_list type) set(modulename ${ARGV0}) set(length ${ARGV1}) set(output ${ARGV2}) set(target_list ${ARGV3}) set(ttype ${ARGV4}) list(REMOVE_AT ARGV 0) list(REMOVE_AT ARGV 0) list(REMOVE_AT ARGV 0) list(REMOVE_AT ARGV 0) list(REMOVE_AT ARGV 0) math(EXPR timeout "${IMP_TIMEOUT_FACTOR} * ${IMP_${length}_TIMEOUT}") foreach (test ${ARGV}) GET_FILENAME_COMPONENT(name ${test} NAME) GET_FILENAME_COMPONENT(name_we ${test} NAME_WE) add_executable("${modulename}-${name}" ${test}) target_link_libraries("${modulename}-${name}" ${IMP_LINK_LIBRARIES}) set_target_properties("${modulename}-${name}" PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${output}" OUTPUT_NAME ${name_we}) set_property(TARGET "${modulename}-${name}" PROPERTY FOLDER "${modulename}") add_test("${modulename}-${name}" ${IMP_TEST_SETUP} ${output}/${name_we}${CMAKE_EXECUTABLE_SUFFIX} ${IMP_TEST_ARGUMENTS}) set_tests_properties("${modulename}-${name}" PROPERTIES LABELS "${modulename}-${ttype}-cpp-${length}") if(DEFINED IMP_TESTS_PROPERTIES) set_tests_properties("${modulename}-${name}" PROPERTIES ${IMP_TESTS_PROPERTIES}) endif() set_tests_properties("${modulename}-${name}" PROPERTIES TIMEOUT ${timeout}) set_tests_properties("${modulename}-${name}" PROPERTIES COST ${IMP_${length}_COST}) set(${target_list} ${${target_list}} "${modulename}-${name}" CACHE INTERNAL "" FORCE) endforeach(test) endfunction(imp_add_cpp_tests) function(imp_add_tests modulename output target_list ttype) set(modulename ${ARGV0}) set(output ${ARGV1}) set(target_list ${ARGV2}) set(ttype ${ARGV3}) list(REMOVE_AT ARGV 0) list(REMOVE_AT ARGV 0) list(REMOVE_AT ARGV 0) list(REMOVE_AT ARGV 0) foreach (test ${ARGV}) GET_FILENAME_COMPONENT(name ${test} NAME) GET_FILENAME_COMPONENT(extension ${test} EXT) if("${extension}" MATCHES ".*py") set(type "py") else() set(type "cpp") endif() if(${name} MATCHES "^test_.*") set(cost "cheap") elseif(${name} MATCHES "^medium_test_.*") set(cost "medium") else() set(cost "expensive") endif() set(${type}_${cost} ${${type}_${cost}} ${test}) endforeach(test) imp_add_python_tests(${modulename} "CHEAP" ${ttype} "${py_cheap}") imp_add_python_tests(${modulename} "MEDIUM" ${ttype} "${py_medium}") imp_add_python_tests(${modulename} "EXPENSIVE" ${ttype} "${py_expensive}") imp_add_cpp_tests(${modulename} "CHEAP" ${output} ${target_list} ${ttype} "${cpp_cheap}") imp_add_cpp_tests(${modulename} "MEDIUM" ${output} ${target_list} ${ttype} "${cpp_medium}") imp_add_cpp_tests(${modulename} "EXPENSIVE" ${output} ${target_list} ${ttype} "${cpp_expensive}") endfunction(imp_add_tests)
shanot/imp
modules/rmf/dependency/RMF/cmake_modules/IMPAddTests.cmake
CMake
gpl-3.0
4,461
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <!-- qdeclarativepolygonmapitem.cpp --> <title>List of All Members for MapPolygon | Qt Location 5.7</title> <link rel="stylesheet" type="text/css" href="style/offline-simple.css" /> <script type="text/javascript"> window.onload = function(){document.getElementsByTagName("link").item(0).setAttribute("href", "style/offline.css");}; </script> </head> <body> <div class="header" id="qtdocheader"> <div class="main"> <div class="main-rounded"> <div class="navigationbar"> <table><tr> <td ><a href="../qtdoc/supported-platforms-and-configurations.html#qt-5-7">Qt 5.7</a></td><td ><a href="qtlocation-index.html">Qt Location</a></td><td ><a href="qtlocation-qmlmodule.html">QML Types</a></td><td >List of All Members for MapPolygon</td></tr></table><table class="buildversion"><tr> <td id="buildversion" width="100%" align="right">Qt 5.7.0 Reference Documentation</td> </tr></table> </div> </div> <div class="content"> <div class="line"> <div class="content mainContent"> <div class="sidebar"><div class="sidebar-content" id="sidebar-content"></div></div> <h1 class="title">List of All Members for MapPolygon</h1> <p>This is the complete list of members for <a href="qml-qtlocation-mappolygon.html">MapPolygon</a>, including inherited members.</p> <ul> <li class="fn"><b><b><a href="qml-qtlocation-mappolygon.html#border.color-prop">border.color</a></b></b> : color</li> <li class="fn"><b><b><a href="qml-qtlocation-mappolygon.html#border.width-prop">border.width</a></b></b> : int</li> <li class="fn"><b><b><a href="qml-qtlocation-mappolygon.html#color-prop">color</a></b></b> : color</li> <li class="fn"><b><b><a href="qml-qtlocation-mappolygon.html#path-prop">path</a></b></b> : list&lt;coordinate&gt;</li> <li class="fn">void <b><b><a href="qml-qtlocation-mappolygon.html#addCoordinate-method">addCoordinate</a></b></b>(<i>coordinate</i>)</li> <li class="fn">void <b><b><a href="qml-qtlocation-mappolygon.html#removeCoordinate-method">removeCoordinate</a></b></b>(<i>coordinate</i>)</li> </ul> </div> </div> </div> </div> </div> <div class="footer"> <p> <acronym title="Copyright">&copy;</acronym> 2016 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners.<br> The documentation provided herein is licensed under the terms of the <a href="http://www.gnu.org/licenses/fdl.html">GNU Free Documentation License version 1.3</a> as published by the Free Software Foundation.<br> Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners. </p> </div> </body> </html>
angeloprudentino/QtNets
Doc/qtlocation/qml-qtlocation-mappolygon-members.html
HTML
gpl-3.0
2,880
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_14) on Fri Jun 18 18:05:18 BST 2010 --> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> <TITLE> Uses of Class gr.forth.ics.graph.layout.forces2d.Forces.FRSpring (FlexiGraph Reference) </TITLE> <META NAME="date" CONTENT="2010-06-18"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class gr.forth.ics.graph.layout.forces2d.Forces.FRSpring (FlexiGraph Reference)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../gr/forth/ics/graph/layout/forces2d/Forces.FRSpring.html" title="class in gr.forth.ics.graph.layout.forces2d"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../index.html?gr/forth/ics/graph/layout/forces2d/\class-useForces.FRSpring.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="Forces.FRSpring.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Class<br>gr.forth.ics.graph.layout.forces2d.Forces.FRSpring</B></H2> </CENTER> No usage of gr.forth.ics.graph.layout.forces2d.Forces.FRSpring <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../gr/forth/ics/graph/layout/forces2d/Forces.FRSpring.html" title="class in gr.forth.ics.graph.layout.forces2d"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../index.html?gr/forth/ics/graph/layout/forces2d/\class-useForces.FRSpring.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="Forces.FRSpring.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
unidesigner/pyconto
scratch/flexigraph-0.1/dist/javadoc/gr/forth/ics/graph/layout/forces2d/class-use/Forces.FRSpring.html
HTML
gpl-3.0
6,443
/* Copyright © 2007, 2008, 2009, 2010, 2011 Vladimír Vondruš <[email protected]> This file is part of Kompas. Kompas is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 3 only, as published by the Free Software Foundation. Kompas 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 version 3 for more details. */ #include "FilesystemCache.h" #include "Utility/Directory.h" #include "Utility/Endianness.h" using namespace std; using namespace Kompas::Utility; using namespace Kompas::Core; namespace Kompas { namespace Plugins { PLUGIN_REGISTER(Kompas::Plugins::FilesystemCache, "cz.mosra.Kompas.Core.AbstractCache/0.2") bool FilesystemCache::initializeCache(const std::string& url) { if(!_url.empty()) finalizeCache(); _url = url; string _file = Directory::join(_url, "index.kps"); if(Directory::fileExists(_file)) { ifstream file(_file, ios::binary); if(!file.good()) { Error() << "Cannot open cache index" << _file; return false; } char* buffer = new char[4]; /* Check file signature */ file.get(buffer, 4); if(string(buffer) != "CCH") { Error() << "Unknown Kompas cache signature" << buffer << "in" << _file; return false; } /* Check file version */ file.read(buffer, 1); if(buffer[0] != 1) { Error() << "Unsupported Kompas cache version" << buffer[0] << "in" << _file; return false; } /* Block size */ file.read(buffer, 4); _blockSize = Endianness::littleEndian(*reinterpret_cast<unsigned int*>(buffer)); /* Block count */ file.read(buffer, 4); _maxBlockCount = Endianness::littleEndian(*reinterpret_cast<unsigned int*>(buffer)); /* Count of all entries */ file.read(buffer, 4); unsigned int count = Endianness::littleEndian(*reinterpret_cast<unsigned int*>(buffer)); _entries.reserve(count); /* Populate the hash table with entries */ for(unsigned int i = 0; i != count; ++i) { if(!file.good()) { Error() << "Incomplete cache index" << _file; return false; } Entry* entry = new Entry(); /* SHA-1, file size, key size and usage */ file.read(reinterpret_cast<char*>(&entry->sha1), 20); file.read(buffer, 4); entry->size = Endianness::littleEndian(*reinterpret_cast<unsigned int*>(buffer)); file.read(buffer, 4); file.read(reinterpret_cast<char*>(&entry->usage), 1); /* Key */ unsigned int keySize = Endianness::littleEndian(*reinterpret_cast<unsigned int*>(buffer)); char* key = new char[keySize]; file.read(key, keySize); entry->key = string(key, keySize); delete[] key; /* Find hash of the file, if it already exists, increase usage count */ unordered_map<Sha1::Digest, unsigned int>::iterator it = _files.find(entry->sha1); if(it != _files.end()) ++it->second; /* If it doesn't exist, add the hash and increase used size */ else { _files.insert(pair<Sha1::Digest, unsigned int>(entry->sha1, 1u)); _usedBlockCount += blockCount(entry->size); } /* Add entry to entries table */ set(entry); } file.close(); } Debug() << "Initialized cache with block size" << _blockSize << "B," << _maxBlockCount << "blocks, containing" << _entries.size() << "entries of size" << _usedBlockCount << "blocks."; return true; } void FilesystemCache::finalizeCache() { if(_url.empty()) return; string _file = Directory::join(_url, "index.kps"); Directory::mkpath(Directory::path(_file)); ofstream file(_file.c_str(), ios::binary); if(!file.good()) { Error() << "Cannot write cache index" << _file; /* Avoid memory leak */ for(unordered_map<string, Entry*>::const_iterator it = _entries.begin(); it != _entries.end(); ++it) delete it->second; return; } unsigned int buffer; /* Write file signature, version, block size, block count and entry count */ file.write("CCH", 3); file.write("\1", 1); buffer = Endianness::littleEndian(static_cast<unsigned int>(_blockSize)); file.write(reinterpret_cast<const char*>(&buffer), 4); buffer = Endianness::littleEndian(static_cast<unsigned int>(_maxBlockCount)); file.write(reinterpret_cast<const char*>(&buffer), 4); buffer = Endianness::littleEndian(static_cast<unsigned int>(_entries.size())); file.write(reinterpret_cast<const char*>(&buffer), 4); /* Foreach all entries and write them to index */ if(_position != 0) { Entry* entry = _position; do { file.write(reinterpret_cast<const char*>(&entry->sha1), Sha1::DigestSize); buffer = Endianness::littleEndian<unsigned int>(entry->size); file.write(reinterpret_cast<const char*>(&buffer), 4); buffer = Endianness::littleEndian<unsigned int>(entry->key.size()); file.write(reinterpret_cast<const char*>(&buffer), 4); file.write(reinterpret_cast<const char*>(&entry->usage), 1); file.write(entry->key.c_str(), entry->key.size()); entry = entry->next; delete entry->previous; } while(entry != _position); } file.close(); _position = 0; _usedBlockCount = 0; _entries.clear(); _files.clear(); _url.clear(); } void FilesystemCache::setBlockSize(size_t size) { _blockSize = size; if(_entries.size() == 0) return; /* Rebuild files map */ _files.clear(); _usedBlockCount = 0; Entry* entry = _position; do { /* Find hash of the file, if it already exists, increase usage count */ unordered_map<Sha1::Digest, unsigned int>::iterator it = _files.find(entry->sha1); if(it != _files.end()) ++it->second; /* If it doesn't exist, add the hash and increase used size */ else { _files.insert(pair<Sha1::Digest, unsigned int>(entry->sha1, 1u)); _usedBlockCount += blockCount(entry->size); } entry = entry->next; } while(entry != _position); } void FilesystemCache::purge() { Debug() << "Cleaning cache."; for(unordered_map<Sha1::Digest, unsigned int>::iterator it = _files.begin(); it != _files.end(); ++it) Directory::rm(fileUrl(it->first)); _entries.clear(); _files.clear(); _position = 0; _usedBlockCount = 0; optimize(); } void FilesystemCache::optimize() { size_t orphanEntryCount = 0; size_t orphanFileCount = 0; size_t orphanDirectoryCount = 0; /* Remove entries without files */ if(_position != 0) { Entry* entry = _position; do { Entry* next = entry->next; /* If the file doesn't exist, remove entry */ if(!Directory::fileExists(fileUrl(entry->sha1))) { ++orphanEntryCount; remove(_entries.find(entry->key)); } entry = next; } while(_position == 0 || entry != _position); } /* Delete files which are not in the file table */ Directory d(_url, Directory::SkipDotAndDotDot); for(Directory::const_iterator it = d.begin(); it != d.end(); ++it) { if(*it == "index.kps") continue; /* Subdirectory, open it and look */ if(it->size() == 2) { string subdir = Directory::join(_url, *it); bool used = false; Directory sd(subdir, Directory::SkipDotAndDotDot); /* Remove unused files */ for(Directory::const_iterator sit = sd.begin(); sit != sd.end(); ++sit) { if(sit->size() == 38) { Sha1::Digest sha1 = Sha1::Digest::fromHexString(*it + *sit); if(sha1 != Sha1::Digest() && _files.find(sha1) == _files.end()) { if(Directory::rm(Directory::join(subdir, *sit))) ++orphanFileCount; continue; } } used = true; } if(!used) { if(Directory::rm(subdir)) ++orphanDirectoryCount; } } } Debug() << "Optimization removed" << orphanEntryCount << "orphan entries," << orphanFileCount << "orphan files and" << orphanDirectoryCount << "orphan directories."; } string FilesystemCache::get(const std::string& key) { ++_getCount; /* Find the key in entry table */ unordered_map<string, Entry*>::iterator eit = _entries.find(key); if(eit == _entries.end()) { Debug() << "Cache miss."; return string(); } Entry* entry = eit->second; /* Hash found, open the file */ string _file = fileUrl(entry->sha1); ifstream file(_file, ios::binary); if(!file.is_open()) { Error() << "Cannot open cached file" << _file; return string(); } /* Increase usage count and return file contents */ ++entry->usage; char* buffer = new char[entry->size]; file.read(buffer, entry->size); string s(buffer, entry->size); delete[] buffer; ++_hitCount; Debug() << "Retrieved entry" << entry->sha1.hexString() << "from cache. Hit rate:" << ((double) _hitCount)/_getCount; return s; } bool FilesystemCache::set(const std::string& key, const std::string& data) { if(_url.empty()) return false; /* Hash of the data */ Sha1::Digest sha1 = Sha1::digest(data); /* Add the entry */ Entry* entry = new Entry(); entry->key = key; entry->sha1 = sha1; entry->size = data.size(); entry->usage = 0; /* Find the hash in file table, if it exists, increase usage count */ unordered_map<Sha1::Digest, unsigned int>::iterator it = _files.find(sha1); if(it != _files.end()) { ++it->second; Debug() << "Entry" << sha1.hexString() << "already exists in cache."; /* If it doesn't exists, prepare free space and insert it */ } else { if(!reserveSpace(data.size())) return false; _usedBlockCount += blockCount(data.size()); _files.insert(pair<Sha1::Digest, unsigned int>(sha1, 1u)); if(!Directory::mkpath(filePath(sha1))) return false; string _file = fileUrl(sha1); ofstream file(_file, ios::binary); if(!file.good()) { Error() << "Cannot write cache file" << _file; return false; } file.write(data.c_str(), data.size()); file.close(); Debug() << "Added entry" << sha1.hexString() << "to cache."; } set(entry); return true; } void FilesystemCache::set(Entry* entry) { /* Find the key in entry table and remove it if it already exists */ unordered_map<string, Entry*>::iterator eit = _entries.find(entry->key); if(eit != _entries.end()) remove(eit); /* First item in the cache, initialize circular linked list */ if(_position == 0) { entry->next = entry; entry->previous = entry; _position = entry; } else { entry->next = _position; entry->previous = _position->previous; _position->previous->next = entry; _position->previous = entry; } _entries.insert(pair<string, Entry*>(entry->key, entry)); } void FilesystemCache::remove(const unordered_map<string, Entry*>::iterator& eit) { Entry* entry = eit->second; /* Disconnect the entry from circular linked list and remove it from the table */ if(entry->next == entry) _position = 0; else { entry->next->previous = entry->previous; entry->previous->next = entry->next; if(_position == entry) _position = _position->next; } _entries.erase(eit); /* Find the hash in file table, decrease usage count */ unordered_map<Sha1::Digest, unsigned int>::iterator it = _files.find(entry->sha1); /* If the file is not used anymore, remove it and decrease used size */ if(it != _files.end() && --it->second == 0) { Directory::rm(fileUrl(entry->sha1)); Directory::rm(filePath(entry->sha1)); _files.erase(it); _usedBlockCount -= blockCount(entry->size); } Debug() << "Removed entry" << entry->sha1.hexString() << "from cache, freed" << blockCount(entry->size) << "blocks."; delete entry; } bool FilesystemCache::reserveSpace(int required) { /* If we need more space than is available, don't do anything */ if(blockCount(required) > _maxBlockCount) { Error() << "Cannot reserve" << blockCount(required) << "blocks in cache of" << _maxBlockCount << "blocks."; return false; } /* Go through the cycle and exponentially decrease usage count */ while(_usedBlockCount+blockCount(required) > _maxBlockCount) { _position->usage >>= 1; /* If the usage decreased to zero, remove the entry */ if(_position->usage == 0) remove(_entries.find(_position->key)); /* Otherwise advance to next entry */ else _position = _position->next; } Debug() << "Reserved" << blockCount(required) << "blocks in cache of" << _maxBlockCount << "blocks."; return true; } string FilesystemCache::filePath(const Sha1::Digest& sha1) const { return Directory::join(_url, sha1.hexString().substr(0, 2)); } string FilesystemCache::fileUrl(const Sha1::Digest& sha1) const { return Directory::join(filePath(sha1), sha1.hexString().substr(2)); } }}
mosra/kompas-plugins
src/FilesystemCache/FilesystemCache.cpp
C++
gpl-3.0
13,964