answer
stringlengths
15
1.25M
#ifndef PCA10031_H #define PCA10031_H // LEDs definitions for PCA10031 (nrf51 Dongle) #define LEDS_NUMBER 3 #define LED_START 21 #define LED_RGB_RED 21 #define LED_RGB_GREEN 22 #define LED_RGB_BLUE 23 #define LED_STOP 23 #define LED_RGB_RED_MASK (1<<LED_RGB_RED) #define LED_RGB_GREEN_MASK (1<<LED_RGB_GREEN) #define LED_RGB_BLUE_MASK (1<<LED_RGB_BLUE) #define LEDS_LIST { LED_RGB_RED, LED_RGB_GREEN, LED_RGB_BLUE} // defining RGB led as 3 single LEDs #define BSP_LED_0 LED_RGB_RED #define BSP_LED_1 LED_RGB_GREEN #define BSP_LED_2 LED_RGB_BLUE #define BSP_LED_0_MASK (1<<BSP_LED_0) #define BSP_LED_1_MASK (1<<BSP_LED_1) #define BSP_LED_2_MASK (1<<BSP_LED_2) #define LEDS_MASK (BSP_LED_0_MASK | BSP_LED_1_MASK | BSP_LED_2_MASK) //defines which LEDs are lit when signal is low #define LEDS_INV_MASK LEDS_MASK // there are no user buttons #define BUTTONS_NUMBER 0 #define BUTTONS_LIST {} #define BUTTONS_MASK 0x00000000 // UART connection with J-Link #define RX_PIN_NUMBER 11 #define TX_PIN_NUMBER 9 #define CTS_PIN_NUMBER 10 #define RTS_PIN_NUMBER 8 #define HWFC true #endif
#pragma once #define <API key> "ABF7" #define USBD_PRODUCT_STRING "Airbot-F7" #define LED0_PIN PB12 #define USE_BEEPER #define BEEPER_PIN PB0 #define BEEPER_INVERTED #define ENABLE_DSHOT_DMAR true #define USE_SPI #define USE_SPI_DEVICE_3 #define SPI3_SCK_PIN PB3 #define SPI3_MISO_PIN PB4 #define SPI3_MOSI_PIN PB5 #define SPI3_NSS_PIN PD2 #define USE_GYRO #define <API key> #define <API key> #define GYRO_1_SPI_INSTANCE SPI3 #define GYRO_1_CS_PIN SPI3_NSS_PIN #define GYRO_1_ALIGN CW90_DEG #define GYRO_1_EXTI_PIN NONE #define GYRO_2_SPI_INSTANCE SPI1 #define GYRO_2_CS_PIN PC4 #define GYRO_2_EXTI_PIN NONE #define GYRO_2_ALIGN CW0_DEG #define USE_ACC #define USE_ACC_SPI_MPU6000 #define USE_ACC_SPI_MPU6500 #define USE_SPI_DEVICE_2 #define SPI2_SCK_PIN PB13 #define SPI2_MISO_PIN PB14 #define SPI2_MOSI_PIN PB15 #define USE_MAX7456 #define <API key> SPI2 #define MAX7456_SPI_CS_PIN PC15 #define USE_SPI_DEVICE_1 #define SPI1_SCK_PIN PA5 #define SPI1_MISO_PIN PA6 #define SPI1_MOSI_PIN PA7 #define USE_FLASHFS #define USE_FLASH_M25P16 #define FLASH_CS_PIN PA3 #define FLASH_SPI_INSTANCE SPI1 #define <API key> #define USE_VCP #define USE_USB_DETECT #define USE_UART1 #define UART1_RX_PIN PA10 #define UART1_TX_PIN PA9 #define USE_UART2 #define UART2_TX_PIN PA2 #define USE_UART3 #define UART3_RX_PIN PC11 #define UART3_TX_PIN PC10 #define USE_UART4 #define UART4_RX_PIN PA1 #define UART4_TX_PIN PA0 #define USE_UART5 #define UART5_TX_PIN PC12 #define USE_UART6 #define UART6_RX_PIN PC7 #define UART6_TX_PIN PC6 #define USE_SOFTSERIAL1 #define SERIAL_PORT_COUNT 8 #define DEFAULT_RX_FEATURE FEATURE_RX_SERIAL #define SERIALRX_PROVIDER SERIALRX_SBUS #define SERIALRX_UART SERIAL_PORT_USART6 #define CAMERA_CONTROL_PIN PA8 #define USE_I2C #define USE_I2C_DEVICE_1 #define I2C1_SCL PB8 #define I2C1_SDA PB9 #define USE_ADC #define <API key> PC1 #define VBAT_ADC_PIN PC0 #define <API key> VOLTAGE_METER_ADC #define <API key> CURRENT_METER_ADC #define <API key> 179 #define DEFAULT_FEATURES (FEATURE_OSD | FEATURE_TELEMETRY | FEATURE_SOFTSERIAL | FEATURE_AIRMODE) #define USE_ESCSERIAL #define TARGET_IO_PORTA 0xffff #define TARGET_IO_PORTB 0xffff #define TARGET_IO_PORTC 0xffff #define TARGET_IO_PORTD 0xffff #define <API key> 6 #define USED_TIMERS (TIM_N(1)|TIM_N(2)|TIM_N(4)|TIM_N(8))
#!/usr/bin/env perl use File::Basename; use Getopt::Long; use Term::ANSIColor; use POSIX qw(strftime); use Cwd; use FindBin qw($RealBin); use lib "$RealBin/lib"; my ($proj, $adir) = @ARGV; my $time = time; chdir($proj); my $command = "tar cf - ./ | ( cd $adir; tar xfp -) >> $proj/error.log 2>&1"; if( -d $adir ){ `echo "Archiving command failed. The dIrectory is already exist." |tee -a $proj/process.log >> $proj/process_current.log`; exit; } else{ `mkdir -p $adir`; } if ( system($command) != 0 ){ `echo "Archiving command failed." |tee -a $proj/process.log >> $proj/process_current.log`; } else{ `rm -rf $proj`; `ln -s $adir $proj`; my $runningtime = &runTime($time); `echo "$runningtime" |tee -a $proj/process.log >> $proj/process_current.log`; `echo "All Done." |tee -a $proj/process.log >> $proj/process_current.log`; `echo "\n*** EDGE_UI: project archived ***" |tee -a $proj/process.log >> $proj/process_current.log`; } sub runTime { my $time=shift; my $runTime = time() - $time; my $time_string = sprintf(" Running time: %02d:%02d:%02d\n\n", int($runTime / 3600), int(($runTime % 3600) / 60), int($runTime % 60)); return $time_string; }
#ifndef <API key> #define <API key> #include "Layers.h" #include <windows.h> #include <d3d9.h> #include "gfxContext.h" #include "nsIWidget.h" #include "DeviceManagerD3D9.h" namespace mozilla { namespace layers { class LayerD3D9; class ThebesLayerD3D9; /* * This is the LayerManager used for Direct3D 9. For now this will render on * the main thread. */ class LayerManagerD3D9 : public LayerManager { public: LayerManagerD3D9(nsIWidget *aWidget); virtual ~LayerManagerD3D9(); /* * Initializes the layer manager, this is when the layer manager will * actually access the device and attempt to create the swap chain used * to draw to the window. If this method fails the device cannot be used. * This function is not threadsafe. * * \return True is initialization was succesful, false when it was not. */ bool Initialize(bool force = false); /* * Sets the clipping region for this layer manager. This is important on * windows because using OGL we no longer have GDI's native clipping. Therefor * widget must tell us what part of the screen is being invalidated, * and we should clip to this. * * \param aClippingRegion Region to clip to. Setting an empty region * will disable clipping. */ void SetClippingRegion(const nsIntRegion& aClippingRegion); /* * LayerManager implementation. */ virtual void Destroy(); virtual void BeginTransaction(); virtual void <API key>(gfxContext* aTarget); void EndConstruction(); virtual bool EndEmptyTransaction(EndTransactionFlags aFlags = END_DEFAULT); struct CallbackInfo { <API key> Callback; void *CallbackData; }; virtual void EndTransaction(<API key> aCallback, void* aCallbackData, EndTransactionFlags aFlags = END_DEFAULT); const CallbackInfo &GetCallbackInfo() { return <API key>; } void SetRoot(Layer* aLayer); virtual bool <API key>(const gfx::IntSize &aSize) { if (!mDeviceManager) return false; int32_t maxSize = mDeviceManager->GetMaxTextureSize(); return aSize <= gfx::IntSize(maxSize, maxSize); } virtual int32_t GetMaxTextureSize() const { return mDeviceManager->GetMaxTextureSize(); } virtual already_AddRefed<ThebesLayer> CreateThebesLayer(); virtual already_AddRefed<ContainerLayer> <API key>(); virtual already_AddRefed<ImageLayer> CreateImageLayer(); virtual already_AddRefed<ColorLayer> CreateColorLayer(); virtual already_AddRefed<CanvasLayer> CreateCanvasLayer(); virtual already_AddRefed<ReadbackLayer> CreateReadbackLayer(); virtual LayersBackend GetBackendType() { return LayersBackend::LAYERS_D3D9; } virtual void GetBackendName(nsAString& name) { name.AssignLiteral("Direct3D 9"); } bool DeviceWasRemoved() { return deviceManager()->DeviceWasRemoved(); } /* * Helper methods. */ void SetClippingEnabled(bool aEnabled); void SetShaderMode(DeviceManagerD3D9::ShaderMode aMode, Layer* aMask, bool aIs2D = true) { mDeviceManager->SetShaderMode(aMode, aMask, aIs2D); } IDirect3DDevice9 *device() const { return mDeviceManager->device(); } DeviceManagerD3D9 *deviceManager() const { return mDeviceManager; } /** * Return pointer to the Nv3DVUtils instance. Re-direct to mDeviceManager. */ Nv3DVUtils *GetNv3DVUtils() { return mDeviceManager ? mDeviceManager->GetNv3DVUtils() : nullptr; } virtual const char* Name() const { return "D3D9"; } void ReportFailure(const nsACString &aMsg, HRESULT aCode); bool CompositingDisabled() { return <API key>; } void <API key>(bool <API key>) { <API key> = <API key>; } private: /* Device manager instance for this layer manager */ nsRefPtr<DeviceManagerD3D9> mDeviceManager; /* Swap chain associated with this layer manager */ nsRefPtr<SwapChainD3D9> mSwapChain; /* Widget associated with this layer manager */ nsIWidget *mWidget; /* * Context target, nullptr when drawing directly to our swap chain. */ nsRefPtr<gfxContext> mTarget; /* Callback info for current transaction */ CallbackInfo <API key>; /* * Region we're clipping our current drawing to. */ nsIntRegion mClippingRegion; /* * Device reset count at last paint. Whenever this changes, we need to * do a full layer tree update. */ uint32_t mDeviceResetCount; /* * True if we should only be drawing layer contents, not * compositing them to the target. */ bool <API key>; /* * Render the current layer tree to the active target. */ void Render(); /* * Setup the pipeline. */ void SetupPipeline(); /* * Copies the content of our backbuffer to the set transaction target. */ void PaintToTarget(); }; /* * General information and tree management for OGL layers. */ class LayerD3D9 { public: LayerD3D9(LayerManagerD3D9 *aManager); virtual LayerD3D9 *GetFirstChildD3D9() { return nullptr; } void SetFirstChild(LayerD3D9 *aParent); virtual Layer* GetLayer() = 0; virtual void RenderLayer() = 0; /* This function may be used on device resets to clear all VRAM resources * that a layer might be using. */ virtual void CleanResources() {} IDirect3DDevice9 *device() const { return mD3DManager->device(); } /* Called by the layer manager when it's destroyed */ virtual void <API key>() {} void ReportFailure(const nsACString &aMsg, HRESULT aCode) { return mD3DManager->ReportFailure(aMsg, aCode); } void <API key>() { Layer* layer = GetLayer(); const gfx::Matrix4x4& transform = layer-><API key>(); device()-><API key>(CBmLayerTransform, &transform._11, 4); float opacity[4]; /* * We always upload a 4 component float, but the shader will use only the * first component since it's declared as a 'float'. */ opacity[0] = layer->GetEffectiveOpacity(); device()-><API key>(CBfLayerOpacity, opacity, 1); } /* * Returns a texture containing the contents of this * layer. Will try to return an existing texture if possible, or a temporary * one if not. It is the callee's responsibility to release the shader * resource view. Will return null if a texture could not be constructed. * The texture will not be transformed, i.e., it will be in the same coord * space as this. * Any layer that can be used as a mask layer should override this method. * If aSize is non-null and a texture is successfully returned, aSize will * contain the size of the texture. */ virtual already_AddRefed<IDirect3DTexture9> GetAsTexture(gfx::IntSize* aSize) { return nullptr; } protected: LayerManagerD3D9 *mD3DManager; }; /* * RAII helper for locking D3D9 textures. */ class LockTextureRectD3D9 { public: LockTextureRectD3D9(IDirect3DTexture9* aTexture) : mTexture(aTexture) { mLockResult = mTexture->LockRect(0, &mR, nullptr, 0); } ~LockTextureRectD3D9() { mTexture->UnlockRect(0); } bool HasLock() { return SUCCEEDED(mLockResult); } D3DLOCKED_RECT GetLockRect() { return mR; } private: LockTextureRectD3D9 (const LockTextureRectD3D9&); LockTextureRectD3D9& operator= (const LockTextureRectD3D9&); IDirect3DTexture9* mTexture; D3DLOCKED_RECT mR; HRESULT mLockResult; }; } /* layers */ } /* mozilla */ #endif /* <API key> */
<?php // Text $_['text_title'] = 'United Parcel Service (UPS)'; $_['text_weight'] = 'Gewicht:'; $_['text_us_origin_01'] = 'UPS US Nächster Tag'; $_['text_us_origin_02'] = 'UPS US Übernächster Tag Luft'; $_['text_us_origin_03'] = 'UPS US Normal'; $_['text_us_origin_07'] = 'UPS US Weltweit Express'; $_['text_us_origin_08'] = 'UPS US Weltweit Beschleunigt'; $_['text_us_origin_11'] = 'UPS US Standard'; $_['text_us_origin_12'] = 'UPS US 3-Tage'; $_['text_us_origin_13'] = 'UPS US Nächster Tag Luft Spartarif'; $_['text_us_origin_14'] = 'UPS US Nächster Tag Luft Vormittag'; $_['text_us_origin_54'] = 'UPS US Weltweit Express Plus'; $_['text_us_origin_59'] = 'UPS US Übernächster Tag Vormittag'; $_['text_us_origin_65'] = 'UPS US Spartarif'; $_['text_ca_origin_01'] = 'UPS CA Express'; $_['text_ca_origin_02'] = 'UPS CA Beschleunigt'; $_['text_ca_origin_07'] = 'UPS CA Weltweit Express'; $_['text_ca_origin_08'] = 'UPS CA Weltweit Beschleunigt'; $_['text_ca_origin_11'] = 'UPS CA Standard'; $_['text_ca_origin_12'] = 'UPS CA 3 Tage'; $_['text_ca_origin_13'] = 'UPS CA Spartarif'; $_['text_ca_origin_14'] = 'UPS CA Express Früher Vormittag'; $_['text_ca_origin_54'] = 'UPS CA Weltweit Express Plus'; $_['text_ca_origin_65'] = 'UPS CA Spartarif'; $_['text_eu_origin_07'] = 'UPS EU Express'; $_['text_eu_origin_08'] = 'UPS EU Beschleunigt'; $_['text_eu_origin_11'] = 'UPS EU Standard'; $_['text_eu_origin_54'] = 'UPS EU Weltweit Express Plus'; $_['text_eu_origin_65'] = 'UPS EU Spartarif'; $_['text_eu_origin_82'] = 'UPS EU Heute Standard'; $_['text_eu_origin_83'] = 'UPS EU Heute Expresskurier'; $_['text_eu_origin_84'] = 'UPS EU Heute Intercity'; $_['text_eu_origin_85'] = 'UPS EU Heute Expresskurier'; $_['text_eu_origin_86'] = 'UPS EU Heute Express Spartarif'; $_['text_eu_origin_01'] = 'UPS EU Nächster Tag Luft'; $_['text_eu_origin_02'] = 'UPS EU Übernächster Tag Luft'; $_['text_eu_origin_03'] = 'UPS EU Normal'; $_['text_eu_origin_07'] = 'UPS EU Weltweit Express'; $_['text_eu_origin_08'] = 'UPS EU Weltweit Beschleunigt'; $_['text_eu_origin_14'] = 'UPS EU Nächster Tag Luft Früh'; $_['text_eu_origin_54'] = 'UPS EU Weltweit Express Plus'; $_['text_eu_origin_65'] = 'UPS EU Spartarif'; $_['text_mx_origin_07'] = 'UPS MX Express'; $_['text_mx_origin_08'] = 'UPS MX Beschleunigt'; $_['text_mx_origin_54'] = 'UPS MX Express Plus'; $_['text_mx_origin_65'] = 'UPS MX Spartarif'; $_['<API key>'] = 'UPS Rest Express'; $_['<API key>'] = 'UPS Rest Worldwide Beschleunigt'; $_['<API key>'] = 'UPS Rest Standard'; $_['<API key>'] = 'UPS Rest Worldwide Express Plus'; $_['<API key>'] = 'UPS Rest Spartarif'; ?>
package io.lumeer.storage.mongodb.dao.project; import static com.mongodb.client.model.Filters.eq; import static com.mongodb.client.model.Updates.inc; import static io.lumeer.storage.mongodb.util.MongoFilters.idFilter; import static io.lumeer.storage.mongodb.util.MongoFilters.nameFilter; import io.lumeer.api.model.Project; import io.lumeer.api.model.ResourceType; import io.lumeer.api.model.Sequence; import io.lumeer.engine.api.event.<API key>; import io.lumeer.engine.api.event.RemoveSequence; import io.lumeer.storage.api.dao.SequenceDao; import io.lumeer.storage.api.exception.<API key>; import io.lumeer.storage.api.exception.StorageException; import io.lumeer.storage.mongodb.codecs.SequenceCodec; import io.lumeer.storage.mongodb.util.MongoFilters; import com.mongodb.MongoException; import com.mongodb.client.MongoCollection; import com.mongodb.client.model.<API key>; import com.mongodb.client.model.IndexOptions; import com.mongodb.client.model.Indexes; import com.mongodb.client.model.ReturnDocument; import com.mongodb.client.model.Sorts; import org.bson.Document; import org.bson.conversions.Bson; import java.util.ArrayList; import java.util.List; import javax.enterprise.context.RequestScoped; import javax.enterprise.event.Event; import javax.inject.Inject; @RequestScoped public class MongoSequenceDao extends <API key> implements SequenceDao { private static final String PREFIX = "sequences_p-"; @Inject private Event<<API key>> <API key>; @Inject private Event<RemoveSequence> removeSequenceEvent; @Override public void createRepository(final Project project) { database.createCollection(<API key>(project)); MongoCollection<Document> projectCollection = database.getCollection(<API key>(project)); projectCollection.createIndex(Indexes.ascending(SequenceCodec.NAME), new IndexOptions().unique(true)); } @Override public void deleteRepository(final Project project) { database.getCollection(<API key>(project)).drop(); } @Override public List<Sequence> getAllSequences() { return databaseCollection().find().sort(Sorts.ascending(SequenceCodec.NAME)).into(new ArrayList<>()); } @Override public Sequence getSequence(final String name) { return databaseCollection().find(nameFilter(name)).first(); } @Override public Sequence updateSequence(final String id, final Sequence sequence) { return updateSequence(sequence, MongoFilters.idFilter(id)); } @Override public void deleteSequence(final String id) { final Sequence sequence = databaseCollection().findOneAndDelete(idFilter(id)); if (sequence == null) { throw new StorageException("Sequence '" + id + "' has not been deleted."); } if (removeSequenceEvent != null) { removeSequenceEvent.fire(new RemoveSequence(sequence)); } } private Sequence updateSequence(final Sequence sequence, final Bson filter) { <API key> options = new <API key>().returnDocument(ReturnDocument.AFTER); try { Bson update = new Document("$set", sequence); final Sequence returnedSequence = databaseCollection().findOneAndUpdate(filter, update, options); if (returnedSequence == null) { throw new StorageException("Sequence '" + sequence.getId() + "' has not been updated."); } if (<API key> != null) { <API key>.fire(new <API key>(returnedSequence)); } return returnedSequence; } catch (MongoException ex) { throw new StorageException("Cannot update sequence " + sequence, ex); } } @Override public synchronized int getNextSequenceNo(final String indexName) { final <API key> options = new <API key>(); options.returnDocument(ReturnDocument.AFTER); final Sequence seq = databaseCollection().findOneAndUpdate(eq(SequenceCodec.NAME, indexName), inc(SequenceCodec.SEQ, 1), options); if (seq == null) { // the sequence did not exist resetSequence(indexName); return 0; } else { return seq.getSeq(); } } @Override public synchronized void resetSequence(final String indexName) { final <API key> options = new <API key>().returnDocument(ReturnDocument.AFTER).upsert(true); final Sequence sequence = new Sequence(indexName, 0); Bson update = new org.bson.Document("$set", sequence); databaseCollection().findOneAndUpdate(eq(SequenceCodec.NAME, indexName), update, options); } public String <API key>(Project project) { return PREFIX + project.getId(); } String <API key>() { if (!getProject().isPresent()) { throw new <API key>(ResourceType.PROJECT); } return <API key>(getProject().get()); } MongoCollection<Sequence> databaseCollection() { return database.getCollection(<API key>(), Sequence.class); } }
import bpy from fashion_project.modules.draw.detail_tool.detail_tool import ToolDetail class FP_DetailTool(bpy.types.Operator): bl_idname = "fp.detail_tool" bl_label = "FP_DetailTool" @classmethod def poll(cls, context): return ToolDetail().poll(context) def execute(self, context): ToolDetail().create(context) return {'FINISHED'} def register(): bpy.utils.register_class(FP_DetailTool) def unregister(): bpy.utils.unregister_class(FP_DetailTool)
package org.labcrypto.edusys.facade.messaging; public interface MessagingFacade { String sendSms (String to, String body); String[] sendSms (String[] tos, String body); }
require 'package' class Dejagnu < Package description 'DejaGnu is a framework for running test suites on GNU tools.' homepage 'http: version '1.6.1' source_url 'https://ftpmirror.gnu.org/dejagnu/dejagnu-1.6.1.tar.gz' source_sha256 '<SHA256-like>' binary_url ({ aarch64: 'https://dl.bintray.com/chromebrew/chromebrew/dejagnu-1.6.1-chromeos-armv7l.tar.xz', armv7l: 'https://dl.bintray.com/chromebrew/chromebrew/dejagnu-1.6.1-chromeos-armv7l.tar.xz', i686: 'https://dl.bintray.com/chromebrew/chromebrew/dejagnu-1.6.1-chromeos-i686.tar.xz', x86_64: 'https://dl.bintray.com/chromebrew/chromebrew/dejagnu-1.6.1-chromeos-x86_64.tar.xz', }) binary_sha256 ({ aarch64: '<SHA256-like>', armv7l: '<SHA256-like>', i686: '<SHA256-like>', x86_64: '<SHA256-like>', }) depends_on 'expect' depends_on 'texinfo' def self.build system "./configure", "--prefix=#{CREW_PREFIX}", "--libdir=#{CREW_LIB_PREFIX}" system "makeinfo --html --no-split -o doc/dejagnu.html doc/dejagnu.texi" system "makeinfo --plaintext -o doc/dejagnu.txt doc/dejagnu.texi" end def self.check system "make check" end def self.install system "make DESTDIR=#{CREW_DEST_DIR} install" system "install -v -dm755 #{CREW_DEST_PREFIX}/share/doc/dejagnu-1.6.1" system "install -v -m644 doc/dejagnu.html #{CREW_DEST_PREFIX}/share/doc/dejagnu-1.6.1" system "install -v -m644 doc/dejagnu.txt #{CREW_DEST_PREFIX}/share/doc/dejagnu-1.6.1" end end
// This program is free software; you can redistribute it and/or modify it // any later version. See COPYING for more details. // Useful data structures and values for interfacing with HashFast products // Version 1.1 #ifndef _HF_PROTOCOL_H_ #define _HF_PROTOCOL_H_ #define HF_PROTOCOL_VERSION ((0<<8)|1) #define HF_PREAMBLE (uint8_t) 0xaa #define <API key> (uint8_t) 0xff #define HF_GWQ_ADDRESS (uint8_t) 254 // Serial protocol operation codes (Second header byte) #define OP_NULL 0 #define OP_ROOT 1 #define OP_RESET 2 #define OP_PLL_CONFIG 3 #define OP_ADDRESS 4 #define OP_READDRESS 5 #define OP_HIGHEST 6 #define OP_BAUD 7 #define OP_UNROOT 8 #define OP_HASH 9 #define OP_NONCE 10 #define OP_ABORT 11 #define OP_STATUS 12 #define OP_GPIO 13 #define OP_CONFIG 14 #define OP_STATISTICS 15 #define OP_GROUP 16 #define OP_CLOCKGATE 17 // Conversions for the ADC readings from GN on-chip sensors #define GN_CORE_VOLTAGE(a) ((float)(a)/256*1.2) #define GN_DIE_TEMPERATURE(a) ((((float)(a)*240)/4096.0)-61.5) // What to use in an OP_CONFIG hdata field to set thermal overload point to a given temp in degrees C #define GN_THERMAL_CUTOFF(temp) ((uint16_t)(((temp)+61.5)*4096/240)) // The sequence distance between a sent and received sequence number. #define <API key>(tx,rx) ((tx)>=(rx)?((tx)-(rx)):(info->num_sequence+(tx)-(rx))) // Values the protocol field in the above structure may take #define <API key> 0 #define <API key> 1 // Conversions for the board/module level sensors #define M_VOLTAGE(a) ((float)(a)*19.0734e-6) #define M_PHASE_CURRENT(a) ((float)(a)*0.794728597e-3) // Values info->device_type can take #define HFD_G1 1 // HashFast G-1 GN ASIC #define HFD_VC709 128 #define HFD_ExpressAGX 129 // USB interface specific operation codes #define OP_USB_INIT 128 // Initialize USB interface details #define OP_GET_TRACE 129 // Send back the trace buffer if present #define OP_LOOPBACK_USB 130 #define OP_LOOPBACK_UART 131 #define OP_DFU 132 // Jump into the boot loader #define OP_USB_SHUTDOWN 133 // Initialize USB interface details #define OP_DIE_STATUS 134 // Die status. There are 4 die per ASIC #define OP_GWQ_STATUS 135 // Global Work Queue protocol status #define OP_WORK_RESTART 136 // Stratum work restart regime #define OP_USB_STATS1 137 // Statistics class 1 #define OP_USB_GWQSTATS 138 // GWQ protocol statistics #define OP_USB_NOTICE 139 // Asynchronous notification event #define OP_PING 140 // Echo #define OP_CORE_MAP 141 // Return core map #define OP_VERSION 142 // Version information #define OP_FAN 143 // Set Fan Speed #define OP_USB_DEBUG 255 // HashFast vendor and product ID's #define HF_USB_VENDOR_ID 0x297c #define <API key> 0x0001 // If this bit is set, search forward for other nonce(s) #define HF_NTIME_MASK 0xfff // Mask for for ntime #define HF_NONCE_SEARCH 0x1000 // Search bit in candidate_nonce -> ntime // Fault codes that can be returned in struct hf_usb_init_base.operation_status #define E_RESET_TIMEOUT 1 #define E_ADDRESS_TIMEOUT 2 #define E_CLOCKGATE_TIMEOUT 3 #define E_CONFIG_TIMEOUT 4 #define <API key> 5 #define <API key> 6 #define E_TOO_MANY_GROUPS 7 #define E_NO_SLAVES 8 #define E_SLAVE_COMM 9 #define E_MAIN_POWER_BAD 10 #define <API key> 11 #define E_BOARD_1 12 #define E_BOARD_2 13 #define E_BOARD_3 14 #define E_BOARD_4 15 #define E_BOARD_5 16 #define E_CORE_POWER_FAULT 17 #define E_BAUD_TIMEOUT 18 #define E_ADDRESS_FAILURE 19 #define U32SIZE(x) (sizeof(x)/sizeof(uint32_t)) // Baud rate vs. code for gpi[7:5] coming out of reset #define BAUD_RATE_PWRUP_0 115200 #define BAUD_RATE_PWRUP_1 9600 #define BAUD_RATE_PWRUP_2 38400 #define BAUD_RATE_PWRUP_3 57600 #define BAUD_RATE_PWRUP_4 230400 #define BAUD_RATE_PWRUP_5 576000 #define BAUD_RATE_PWRUP_6 921600 #define BAUD_RATE_PWRUP_7 1152000 // OP_WORK_RESTART hash clock change methods. // May be issued *infrequently* by the host to adjust hash clock rate for thermal control // The "hdata" field, if non zero, contains adjustment instructions. Bits 15:12 of "hdata" // contain the adjustment type according to the following code, and bits 11:0 contain the // associated value. Examples: // hdata = (1<<12)|550 = Set hash clock rate to 550 Mhz // hdata = (4<<12)|1 = Increase hash clock rate by 1% // hdata = (6<<12) = Go back to whatever the "original" OP_USB_INIT settings were // Finally, if 4 bytes of "data" follows the OP_WORK_RESTART header, then that data is taken // as a little endian bitmap, bit set = enable clock change to that die, bit clear = don't // change clock on that die, i.e. considered as a uint32_t, then 0x1 = die 0, 0x2 = die 1 etc. #define WR_NO_CHANGE 0 #define WR_CLOCK_VALUE 1 #define WR_MHZ_INCREASE 2 #define WR_MHZ_DECREASE 3 #define WR_PERCENT_INCREASE 4 #define WR_PERCENT_DECREASE 5 #define WR_REVERT 6 #define WR_COMMAND_SHIFT 12 // Structure definitions, LE platforms #if __BYTE_ORDER == __BIG_ENDIAN && !defined(WIN32) #include "hf_protocol_be.h" #else // Generic header struct hf_header { uint8_t preamble; // Always 0xaa uint8_t operation_code; uint8_t chip_address; uint8_t core_address; uint16_t hdata; // Header specific data uint8_t data_length; // .. of data frame to follow, in 4 byte blocks, 0=no data uint8_t crc8; // Computed across bytes 1-6 inclusive } __attribute__((packed,aligned(4))); // 8 bytes total // Header specific to OP_PLL_CONFIG struct hf_pll_config { uint8_t preamble; uint8_t operation_code; uint8_t chip_address; uint8_t pll_divr:6; uint8_t pll_bypass:1; uint8_t pll_reset:1; uint8_t pll_divf; uint8_t spare1:1; // Must always be 0 uint8_t pll_divq:3; uint8_t pll_range:3; uint8_t pll_fse:1; // Must always be 1 uint8_t data_length; // Always 0 uint8_t crc8; // Computed across bytes 1-6 inclusive } __attribute__((packed,aligned(4))); // 8 bytes total // OP_HASH serial data struct hf_hash_serial { uint8_t midstate[32]; // Computed from first half of block header uint8_t merkle_residual[4]; // From block header uint32_t timestamp; // From block header uint32_t bits; // Actual difficulty target for block header uint32_t starting_nonce; // Usually set to 0 uint32_t nonce_loops; // How many nonces to search, or 0 for 2^32 uint16_t ntime_loops; // How many times to roll timestamp, or 0 uint8_t search_difficulty; // Search difficulty to use, # of '0' digits required uint8_t option; uint8_t group; uint8_t spare3[3]; } __attribute__((packed,aligned(4))); // OP_HASH usb data - header+data = 64 bytes struct hf_hash_usb { uint8_t midstate[32]; // Computed from first half of block header uint8_t merkle_residual[4]; // From block header uint32_t timestamp; // From block header uint32_t bits; // Actual difficulty target for block header uint32_t starting_nonce; // Usually set to 0 uint32_t nonce_loops; // How many nonces to search, or 0 for 2^32 uint16_t ntime_loops; // How many times to roll timestamp, or 0 uint8_t search_difficulty; // Search difficulty to use, # of '0' digits required uint8_t group; // Non-zero for valid group } __attribute__((packed,aligned(4))); // OP_NONCE data struct hf_candidate_nonce { uint32_t nonce; // Candidate nonce uint16_t sequence; // Sequence number from corresponding OP_HASH uint16_t ntime; // ntime offset, if ntime roll occurred, in LS 12 bits // If b12 set, search forward next 128 nonces to find solution(s) } __attribute__((packed,aligned(4))); // OP_CONFIG data struct hf_config_data { uint16_t status_period:11; // Periodic status time, msec uint16_t <API key>:1; // Send periodic status uint16_t <API key>:1; // Schedule status whenever core goes idle uint16_t <API key>:1; // Schedule status whenever core pending goes idle uint16_t pwm_active_level:1; // Active level of PWM outputs, if used uint16_t <API key>:1; // Forward priv pkts -- diagnostic uint8_t status_batch_delay; // Batching delay, time to wait before sending status uint8_t watchdog:7; // Watchdog timeout, seconds uint8_t disable_sensors:1; // Diagnostic uint8_t rx_header_timeout:7; // Header timeout in char times uint8_t <API key>:1; // Ignore rx header crc's (diagnostic) uint8_t rx_data_timeout:7; // Data timeout in char times / 16 uint8_t rx_ignore_data_crc:1; // Ignore rx data crc's (diagnostic) uint8_t stats_interval:7; // Minimum interval to report statistics (seconds) uint8_t stat_diagnostic:1; // Never set this uint8_t measure_interval; // Die temperature measurement interval (msec) uint32_t one_usec:12; // How many LF clocks per usec. uint32_t <API key>:4; // Maximum # of nonces to combine in a single frame uint32_t <API key>:8; // Bit mask for sample points (up to 5 bits set) uint32_t pwm_phases:2; // phases - 1 uint32_t trim:4; // Trim value for temperature measurements uint32_t clock_diagnostic:1; // Never set this uint32_t forward_all_packets:1; // Forward everything - diagnostic. uint16_t pwm_period; // Period of PWM outputs, in reference clock cycles uint16_t pwm_pulse_period; // Initial count, phase 0 } __attribute__((packed,aligned(4))); // OP_GROUP data struct hf_group_data { uint16_t nonce_msoffset; // This value << 16 added to starting nonce uint16_t ntime_offset; // This value added to timestamp } __attribute__((packed,aligned(4))); // Structure of the monitor fields for G-1, returned in OP_STATUS, core bitmap follows this struct hf_g1_monitor { uint16_t die_temperature; // Die temperature ADC count uint8_t core_voltage[6]; // Core voltage // [0] = main sensor // [1]-[5] = other positions } __attribute__((packed,aligned(4))); // What comes back in the body of an OP_STATISTICS frame (On die statistics) struct hf_statistics { uint8_t rx_header_crc; // Header CRC error's uint8_t rx_body_crc; // Data CRC error's uint8_t rx_header_timeouts; // Header timeouts uint8_t rx_body_timeouts; // Data timeouts uint8_t <API key>; // Core nonce Q overrun events uint8_t <API key>; // System nonce Q overrun events uint8_t stats_overrun; // Overrun in statistics reporting uint8_t spare; } __attribute__((packed,aligned(4))); // USB protocol data structures // Convenience header specific to OP_USB_INIT struct hf_usb_init_header { uint8_t preamble; // Always 0xaa uint8_t operation_code; uint8_t spare1; uint8_t protocol:3; // Which protocol to use uint8_t user_configuration:1; // Use the following configuration data uint8_t pll_bypass:1; // Force PLL bypass, hash clock = ref clock uint8_t <API key>:1; // Do not perform automatic ASIC initialization uint8_t <API key>:1; // Do core tests at speed, return second bitmap uint8_t leave_powered_down:1; // Init USB only, leave device powered down uint16_t hash_clock; // Requested hash clock frequency uint8_t data_length; // .. of data frame to follow, in 4 byte blocks uint8_t crc8; // Computed across bytes 1-6 inclusive } __attribute__((packed,aligned(4))); // 8 bytes total // Options (only if present) that may be appended to the above header // Each option involving a numerical value will only be in effect if the value is non-zero // This allows the user to select only those options desired for modification. Do not // use this facility unless you are an expert - loading inconsistent settings will not work. struct hf_usb_init_options { uint16_t group_ntime_roll; // Total ntime roll amount per group uint16_t core_ntime_roll; // Total core ntime roll amount uint8_t <API key>; // Lowest normal operating limit uint8_t <API key>; // Highest normal operating limit uint16_t spare; } __attribute__((packed,aligned(4))); // Base item returned from device for OP_USB_INIT struct hf_usb_init_base { uint16_t firmware_rev; // Firmware revision uint16_t hardware_rev; // Hardware revision uint32_t serial_number; // Board serial number uint8_t operation_status; // Reply status for OP_USB_INIT (0 = success) uint8_t extra_status_1; // Extra reply status information, code specific uint16_t sequence_modulus; // Sequence numbers are to be modulo this uint16_t hash_clockrate; // Actual hash clock rate used (nearest Mhz) uint16_t inflight_target; // Target inflight amount for GWQ protocol } __attribute__((packed,aligned(4))); // The above base item (16 bytes) is followed by the struct hf_config_data (16 bytes) actually // used internally (so users may modify non-critical fields by doing subsequent // OP_CONFIG operations). This is followed by a device specific "core good" bitmap (unless the // user disabled initialization), and optionally by an at-speed "core good" bitmap. // Information in an OP_DIE_STATUS frame. This is for one die - there are four per ASIC. // Board level phase current and voltage sensors are likely to disappear in later production models. struct hf_g1_die_data { struct hf_g1_monitor die; // Die sensors - 8 bytes uint16_t phase_currents[4]; // Phase currents (0 if unavailable) uint16_t voltage; // Voltage at device boundary (0 if unavailable) uint16_t temperature; // Regulator temp sensor uint16_t tacho; // See documentation uint16_t spare; } __attribute__((packed,aligned(4))); // 24 bytes total // Information for an OP_GWQ_STATUS frame // If sequence_head == sequence_tail, then there is no active work and sequence_head is invalid struct hf_gwq_data { uint64_t hash_count; // Add this to host's cumulative hash count uint16_t sequence_head; // The latest, internal, active sequence uint16_t sequence_tail; // The latest, internal, inactive sequence uint16_t shed_count; // # of cores have been shedded for thermal control uint16_t spare; } __attribute__((packed,aligned(4))); // Information for an OP_USB_STATS1 frame - Communication statistics struct hf_usb_stats1 { // USB incoming uint16_t usb_rx_preambles; uint16_t <API key>; uint16_t usb_rx_bad_hcrc; // USB outgoing uint16_t usb_tx_attempts; uint16_t usb_tx_packets; uint16_t usb_tx_timeouts; uint16_t usb_tx_incompletes; uint16_t <API key>; uint16_t usb_tx_disconnected; uint16_t usb_tx_suspended; // Internal UART transmit uint16_t uart_tx_queue_dma; uint16_t uart_tx_interrupts; // Internal UART receive uint16_t <API key>; uint16_t <API key>; uint16_t uart_rx_header_done; uint16_t uart_rx_data_done; uint16_t uart_rx_bad_hcrc; //uint16_t uart_rx_bad_crc32; uint16_t uart_rx_bad_dma; uint16_t uart_rx_short_dma; uint16_t <API key>; uint8_t max_tx_buffers; // Maximum # of send buffers ever used uint8_t max_rx_buffers; // Maximum # of receive buffers ever used } __attribute__((packed,aligned(4))); // Information for an OP_USB_NOTICE frame struct hf_usb_notice_data { uint32_t extra_data; // Depends on notification code char message[]; // NULL terminated, little endian byte order }; #endif #endif
package org.structr.knowledge.iso25964; import java.net.URI; import java.util.Locale; import org.structr.api.schema.JsonObjectType; import org.structr.api.schema.JsonSchema; import org.structr.common.PropertyView; import org.structr.core.graph.NodeInterface; import org.structr.schema.SchemaService; /** * Class as defined in ISO 25964 data model */ public interface CustomTermAttribute extends NodeInterface { static class Impl { static { final JsonSchema schema = SchemaService.getDynamicSchema(); final JsonObjectType type = schema.addType("CustomTermAttribute"); type.setImplements(URI.create("https://structr.org/v1.1/definitions/CustomTermAttribute")); type.addStringProperty("lexicalValue", PropertyView.All, PropertyView.Ui).setIndexed(true).setRequired(true); type.addStringProperty("customAttributeType", PropertyView.All, PropertyView.Ui).setIndexed(true).setRequired(true); type.addEnumProperty("lang", PropertyView.All, PropertyView.Ui).setEnums(Locale.getISOLanguages()); }} }
#pragma once #if NOT_TARGET(__STM32F1__) #error "Oops! Select an STM32F1 board in 'Tools > Board.'" #endif #define BOARD_INFO_NAME "GTM32 Pro VB" #define <API key> "STM32F103VET6" #define BOARD_NO_NATIVE_USB //#define DISABLE_DEBUG // It is required to disable JTAG function because its pins are // used as GPIO to drive the Y axis stepper. // DO NOT ENABLE! #define DISABLE_JTAG // If you don't need the SWDIO functionality (any more), you may // disable SWD here to regain PA13/PA14 pins for other use. //#define DISABLE_JTAGSWD // Ignore temp readings during development. //#define <API key> 2000 // Enable EEPROM Emulation for this board as it doesn't have EEPROM #if EITHER(NO_EEPROM_SELECTED, <API key>) #define <API key> #define MARLIN_EEPROM_SIZE 0x1000 // 4KB #endif // Limit Switches #define X_MIN_PIN PE5 // ENDSTOPS 15,17 #define X_MAX_PIN PE4 // ENDSTOPS 16,18 #define Y_MIN_PIN PE3 // ENDSTOPS 9,11 #define Y_MAX_PIN PE2 // ENDSTOPS 10,12 #define Z_MIN_PIN PE1 // ENDSTOPS 3,5 #define Z_MAX_PIN PE0 // ENDSTOPS 4,6 // Steppers #define X_STEP_PIN PC6 #define X_DIR_PIN PD13 #define X_ENABLE_PIN PA8 #define Y_STEP_PIN PA12 #define Y_DIR_PIN PA11 #define Y_ENABLE_PIN PA15 #define Z_STEP_PIN PD6 #define Z_DIR_PIN PD3 #define Z_ENABLE_PIN PB3 // Extruder stepper pins // NOTE: Numbering here is made according to EXT connector numbers, // the FANx_PWM line numbering in the schematics is reverse. // That is, E0_*_PIN are the E2_* lines connected to E2_A1 step // stick that drives the EXT0 output on the board. #define E0_STEP_PIN PC14 #define E0_DIR_PIN PC13 #define E0_ENABLE_PIN PC15 #define E1_STEP_PIN PA0 #define E1_DIR_PIN PB6 #define E1_ENABLE_PIN PA1 #define E2_STEP_PIN PB2 #define E2_DIR_PIN PB11 #define E2_ENABLE_PIN PC4 // Heaters / Fans #define HEATER_0_PIN PB0 // EXT0 port #define HEATER_1_PIN PB5 // EXT1 port #define HEATER_2_PIN PB4 // EXT2 port #define HEATER_BED_PIN PB1 // CON2X3 hotbed port // These are FAN PWM pins on EXT0..EXT2 connectors. //#define FAN_PIN PB9 // EXT0 port #define FAN1_PIN PB8 // EXT1 port #define FAN2_PIN PB7 // EXT2 port #ifndef E0_AUTO_FAN_PIN #define E0_AUTO_FAN_PIN PB9 // EXT0 port, used as main extruder fan #endif // Temperature Sensors #define TEMP_0_PIN PC2 // EXT0 port #define TEMP_1_PIN PC1 // EXT1 port #define TEMP_2_PIN PC0 // EXT2 port #define TEMP_BED_PIN PC3 // CON2X3 hotbed port // Misc. Functions #define LED_PWM PD12 // External LED, pin 2 on LED labeled connector // LCD / Controller #if HAS_WIRED_LCD #if IS_RRD_SC // LCD display on J2 FFC40 // Geeetech's LCD2004A Control Panel is very much like // RepRapDiscount Smart Controller, but adds an FFC40 connector #define LCD_PINS_RS PE6 // CS chip select /SS chip slave select #define LCD_PINS_ENABLE PE14 // SID (MOSI) #define LCD_PINS_D4 PD8 // SCK (CLK) clock #define LCD_PINS_D5 PD9 #define LCD_PINS_D6 PD10 #define LCD_PINS_D7 PE15 #else // Serial LCDs can be implemented in ExtUI //#define LCD_UART_TX PD8 //#define LCD_UART_RX PD9 #endif #if HAS_MARLINUI_U8GLIB #ifndef <API key> #define <API key> DELAY_NS(96) #endif #ifndef <API key> #define <API key> DELAY_NS(48) #endif #ifndef <API key> #define <API key> DELAY_NS(715) #endif #endif #endif // HAS_WIRED_LCD #if IS_RRD_SC // Geeetech's LCD2004A Control Panel is very much like // RepRapDiscount Smart Controller, but adds an FFC40 connector // connected with a flat wire to J2 connector on the board. #define BTN_EN1 PE8 #define BTN_EN2 PE9 #define BTN_ENC PE13 #define <API key> #define <API key> #endif // Beeper #ifdef <API key> // This is pin 32 on J2 FFC40 and pin, goes to the beeper // on Geeetech's version of RepRapDiscount Smart Controller // (e.g. on Rostock 301) #define BEEPER_PIN PE12 #else // This is the beeper on the board itself #define BEEPER_PIN PB10 #endif /** * The on-board TF_CARD_SOCKET microSD card socket has no SD Detect pin wired. * * The FFC10 (SD_CARD) connector has the same pins as those routed to the FFC40 (J2) * connector, which usually go to the SD Card slot on the Geeetech version of the * RepRapDiscount Smart Controller. Both connectors have the card detect signal. * * The on-board SD card and the external card (on either SD_CARD or J2) are two * separate devices and can work simultaneously. Unfortunately, Marlin only supports * a single SPI Flash device (as of 2019-07-05) so only one is enabled here. */ #if ENABLED(<API key>) // SD Card on RepRapDiscount Smart Controller (J2) or on SD_CARD connector #define SS_PIN PC11 #define SCK_PIN PC12 #define MOSI_PIN PD2 #define MISO_PIN PC8 #define SD_DETECT_PIN PC7 #else // Use the on-board card socket labeled TF_CARD_SOCKET #define SS_PIN PA4 #define SCK_PIN PA5 #define MOSI_PIN PA7 #define MISO_PIN PA6 #define SD_DETECT_PIN -1 // Card detect is not connected #endif #define SDSS SS_PIN // ESP WiFi can be soldered to J9 connector which is wired to USART2. // Must define WIFISUPPORT in Configuration.h for the printer. #define ESP_WIFI_MODULE_COM 2 #define <API key> 115200 #define <API key> -1
<?php /** * @see <API key> */ //require_once 'Zend/Markup/Exception.php'; class <API key> extends <API key> { }
<?php namespace Elementor\Modules\WpCli; use Elementor\Api; use Elementor\Plugin; use Elementor\TemplateLibrary\Source_Local; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly } /** * Elementor Page Builder cli tools. */ class Library extends \WP_CLI_Command { /** * Sync Elementor Library. * * [--network] * Sync library in all the sites in the network. * * [--force] * Force sync even if it's looks like that the library is already up to date. * * ## EXAMPLES * * 1. wp elementor library sync * - This will sync the library with Elementor cloud library. * * 2. wp elementor library sync --force * - This will sync the library with Elementor cloud even if it's looks like that the library is already up to date. * * 3. wp elementor library sync --network * - This will sync the library with Elementor cloud library for each site in the network if needed. * * @since 2.8.0 * @access public */ public function sync( $args, $assoc_args ) { $network = isset( $assoc_args['network'] ) && is_multisite(); if ( $network ) { /** @var \WP_Site[] $sites */ $sites = get_sites(); foreach ( $sites as $keys => $blog ) { // Cast $blog as an array instead of object $blog_id = $blog->blog_id; switch_to_blog( $blog_id ); \WP_CLI::line( 'Site #' . $blog_id . ' - ' . get_option( 'blogname' ) ); $this->do_sync( isset( $assoc_args['force'] ) ); \WP_CLI::success( 'Done! - ' . get_option( 'home' ) ); <API key>(); } } else { $this->do_sync( isset( $assoc_args['force'] ) ); \WP_CLI::success( 'Done!' ); } } /** * Import template files to the Library. * * ## EXAMPLES * * 1. wp elementor library import <file-path> * - This will import a file or a zip of multiple files to the library. * * @param $args * @param $assoc_args * * @since 2.8.0 * @access public */ public function import( $args ) { if ( empty( $args[0] ) ) { \WP_CLI::error( 'Please set file path.' ); } $file = $args[0]; /** @var Source_Local $source */ $source = Plugin::$instance->templates_manager->get_source( 'local' ); $imported_items = $source->import_template( basename( $file ), $file ); if ( is_wp_error( $imported_items ) ) { \WP_CLI::error( $imported_items->get_error_message() ); } \WP_CLI::success( count( $imported_items ) . ' item(s) has been imported.' ); } /** * Connect site to Elementor Library. * (Network is not supported) * * --user * The user to connect <id|login|email> * * --token * A connect token from Elementor Account Dashboard. * * ## EXAMPLES * * 1. wp elementor library connect --user=admin --token=<connect-cli-token> * - This will connect the admin to Elementor library. * * @param $args * @param $assoc_args * * @since 2.8.0 * @access public */ public function connect( $args, $assoc_args ) { if ( ! get_current_user_id() ) { \WP_CLI::error( 'Please set user to connect (--user=<id|login|email>).' ); } if ( empty( $assoc_args['token'] ) ) { \WP_CLI::error( 'Please set connect token.' ); } $_REQUEST['mode'] = 'cli'; $_REQUEST['token'] = $assoc_args['token']; $app = $this->get_library_app(); $app->action_authorize(); $app->action_get_token(); } /** * Disconnect site from Elementor Library. * * --user * The user to disconnect <id|login|email> * * ## EXAMPLES * * 1. wp elementor library disconnect --user=admin * - This will disconnect the admin from Elementor library. * * @param $args * @param $assoc_args * * @since 2.8.0 * @access public */ public function disconnect() { if ( ! get_current_user_id() ) { \WP_CLI::error( 'Please set user to connect (--user=<id|login|email>).' ); } $_REQUEST['mode'] = 'cli'; $this->get_library_app()->action_disconnect(); } private function do_sync() { $data = Api::get_library_data( true ); if ( empty( $data ) ) { \WP_CLI::error( 'Cannot sync library.' ); } } /** * @return \Elementor\Core\Common\Modules\Connect\Apps\Library */ private function get_library_app() { $connect = Plugin::$instance->common->get_component( 'connect' ); $app = $connect->get_app( 'library' ); // Before init. if ( ! $app ) { $connect->init(); $app = $connect->get_app( 'library' ); } return $app; } }
<html><body>Nagel:<br> You can find <font color="LEVEL">the corpses beyond the cracked gap</font>.<br> </body></html>
package de.linogistix.los.stocktaking.crud; import javax.ejb.EJB; import javax.ejb.Stateless; import org.mywms.service.BasicService; import de.linogistix.los.crud.<API key>; import de.linogistix.los.stocktaking.model.LOSStocktakingOrder; import de.linogistix.los.stocktaking.service.<API key>; /** * @author krane * */ @Stateless public class <API key> extends <API key><LOSStocktakingOrder> implements <API key> { @EJB <API key> service; @Override protected BasicService<LOSStocktakingOrder> getBasicService() { return service; } }
<?php /* * smtp.php * * @(#) $Header: /home/mlemos/cvsroot/smtp/smtp.php,v 1.37 2004/10/05 04:00:46 mlemos Exp $ * */ class smtp_class { var $user=""; var $realm=""; var $password=""; var $workstation=""; var $<API key>=""; var $host_name=""; var $host_port=25; var $localhost=""; var $timeout=0; var $data_timeout=0; var $direct_delivery=0; var $error=""; var $debug=0; var $html_debug=0; var $esmtp=1; var $esmtp_host=""; var $esmtp_extensions=array(); var $<API key>=100; var $exclude_address=""; var $getmxrr="GetMXRR"; var $pop3_auth_host=""; var $pop3_auth_port=110; /* private variables - DO NOT ACCESS */ var $state="Disconnected"; var $connection=0; var $pending_recipients=0; var $next_token=""; var $direct_sender=""; var $connected_domain=""; var $result_code; /* Private methods - DO NOT CALL */ Function Tokenize($string,$separator="") { if(!strcmp($separator,"")) { $separator=$string; $string=$this->next_token; } for($character=0;$character<strlen($separator);$character++) { if(GetType($position=strpos($string,$separator[$character]))=="integer") $found=(IsSet($found) ? min($found,$position) : $position); } if(IsSet($found)) { $this->next_token=substr($string,$found+1); return(substr($string,0,$found)); } else { $this->next_token=""; return($string); } } Function OutputDebug($message) { $message.="\n"; if($this->html_debug) $message=str_replace("\n","<br />\n",HtmlEntities($message)); echo $message; flush(); } Function SetDataAccessError($error) { $this->error=$error; if(function_exists("socket_get_status")) { $status=socket_get_status($this->connection); if($status["timed_out"]) $this->error.=": data access time out"; elseif($status["eof"]) $this->error.=": the server disconnected"; } } Function GetLine() { for($line="";;) { if(feof($this->connection)) { $this->error="reached the end of data while reading from the SMTP server conection"; return(""); } if(GetType($data=fgets($this->connection,100))!="string" || strlen($data)==0) { $this->SetDataAccessError("it was not possible to read line from the SMTP server"); return(""); } $line.=$data; $length=strlen($line); if($length>=2 && substr($line,$length-2,2)=="\r\n") { $line=substr($line,0,$length-2); if($this->debug) $this->OutputDebug("S $line"); return($line); } } } Function PutLine($line) { if($this->debug) $this->OutputDebug("C $line"); if(!fputs($this->connection,"$line\r\n")) { $this->SetDataAccessError("it was not possible to send a line to the SMTP server"); return(0); } return(1); } Function PutData(&$data) { if(strlen($data)) { if($this->debug) $this->OutputDebug("C $data"); if(!fputs($this->connection,$data)) { $this->SetDataAccessError("it was not possible to send data to the SMTP server"); return(0); } } return(1); } Function VerifyResultLines($code,&$responses) { $responses=array(); Unset($this->result_code); while(strlen($line=$this->GetLine($this->connection))) { if(IsSet($this->result_code)) { if(strcmp($this->Tokenize($line," -"),$this->result_code)) { $this->error=$line; return(0); } } else { $this->result_code=$this->Tokenize($line," -"); if(GetType($code)=="array") { for($codes=0;$codes<count($code) && strcmp($this->result_code,$code[$codes]);$codes++); if($codes>=count($code)) { $this->error=$line; return(0); } } else { if(strcmp($this->result_code,$code)) { $this->error=$line; return(0); } } } $responses[]=$this->Tokenize(""); if(!strcmp($this->result_code,$this->Tokenize($line," "))) return(1); } return(-1); } Function FlushRecipients() { if($this->pending_sender) { if($this->VerifyResultLines("250",$responses)<=0) return(0); $this->pending_sender=0; } for(;$this->pending_recipients;$this->pending_recipients { if($this->VerifyResultLines(array("250","251"),$responses)<=0) return(0); } return(1); } Function ConnectToHost($domain, $port, $resolve_message) { if(ereg('^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$',$domain)) $ip=$domain; else { if($this->debug) $this->OutputDebug($resolve_message); if(!strcmp($ip=@gethostbyname($domain),$domain)) return("could not resolve host \"".$domain."\""); } if(strlen($this->exclude_address) && !strcmp(@gethostbyname($this->exclude_address),$ip)) return("domain \"".$domain."\" resolved to an address excluded to be valid"); if($this->debug) $this->OutputDebug("Connecting to host address \"".$ip."\"..."); if(($this->connection=($this->timeout ? @fsockopen($ip,$port,$errno,$error,$this->timeout) : @fsockopen($ip,$port)))) return(""); $error=($this->timeout ? strval($error) : "??"); switch($error) { case "-3": return("-3 socket could not be created"); case "-4": return("-4 dns lookup on hostname \"".$domain."\" failed"); case "-5": return("-5 connection refused or timed out"); case "-6": return("-6 fdopen() call failed"); case "-7": return("-7 setvbuf() call failed"); } return("could not connect to the host \"".$domain."\": ".$error); } Function SASLAuthenticate($mechanisms, $credentials, &$authenticated, &$mechanism) { $authenticated=0; if(!function_exists("class_exists") || !class_exists("sasl_client_class")) { $this->error="it is not possible to authenticate using the specified mechanism because the SASL library class is not loaded"; return(0); } $sasl=new sasl_client_class; $sasl->SetCredential("user",$credentials["user"]); $sasl->SetCredential("password",$credentials["password"]); if(IsSet($credentials["realm"])) $sasl->SetCredential("realm",$credentials["realm"]); if(IsSet($credentials["workstation"])) $sasl->SetCredential("workstation",$credentials["workstation"]); if(IsSet($credentials["mode"])) $sasl->SetCredential("mode",$credentials["mode"]); do { $status=$sasl->Start($mechanisms,$message,$interactions); } while($status==SASL_INTERACT); switch($status) { case SASL_CONTINUE: break; case SASL_NOMECH: if(strlen($this-><API key>)) { $this->error="authenticated mechanism ".$this-><API key>." may not be used: ".$sasl->error; return(0); } break; default: $this->error="Could not start the SASL authentication client: ".$sasl->error; return(0); } if(strlen($mechanism=$sasl->mechanism)) { if($this->PutLine("AUTH ".$sasl->mechanism.(IsSet($message) ? " ".base64_encode($message) : ""))==0) { $this->error="Could not send the AUTH command"; return(0); } if(!$this->VerifyResultLines(array("235","334"),$responses)) return(0); switch($this->result_code) { case "235": $response=""; $authenticated=1; break; case "334": $response=base64_decode($responses[0]); break; default: $this->error="Authentication error: ".$responses[0]; return(0); } for(;!$authenticated;) { do { $status=$sasl->Step($response,$message,$interactions); } while($status==SASL_INTERACT); switch($status) { case SASL_CONTINUE: if($this->PutLine(base64_encode($message))==0) { $this->error="Could not send the authentication step message"; return(0); } if(!$this->VerifyResultLines(array("235","334"),$responses)) return(0); switch($this->result_code) { case "235": $response=""; $authenticated=1; break; case "334": $response=base64_decode($responses[0]); break; default: $this->error="Authentication error: ".$responses[0]; return(0); } break; default: $this->error="Could not process the SASL authentication step: ".$sasl->error; return(0); } } } return(1); } /* Public methods */ Function Connect($domain="") { if(strcmp($this->state,"Disconnected")) { $this->error="connection is already established"; return(0); } $this->error=$error=""; $this->esmtp_host=""; $this->esmtp_extensions=array(); $hosts=array(); if($this->direct_delivery) { if(strlen($domain)==0) return(1); $hosts=$weights=$mxhosts=array(); $getmxrr=$this->getmxrr; if(function_exists($getmxrr) && $getmxrr($domain,$hosts,$weights)) { for($host=0;$host<count($hosts);$host++) $mxhosts[$weights[$host]]=$hosts[$host]; KSort($mxhosts); for(Reset($mxhosts),$host=0;$host<count($mxhosts);Next($mxhosts),$host++) $hosts[$host]=$mxhosts[Key($mxhosts)]; } else { if(strcmp(@gethostbyname($domain),$domain)!=0) $hosts[]=$domain; } } else { if(strlen($this->host_name)) $hosts[]=$this->host_name; if(strlen($this->pop3_auth_host)) { $user=$this->user; if(strlen($user)==0) { $this->error="it was not specified the POP3 authentication user"; return(0); } $password=$this->password; if(strlen($password)==0) { $this->error="it was not specified the POP3 authentication password"; return(0); } $domain=$this->pop3_auth_host; $this->error=$this->ConnectToHost($domain, $this->pop3_auth_port, "Resolving POP3 authentication host \"".$domain."\"..."); if(strlen($this->error)) return(0); if(strlen($response=$this->GetLine())==0) return(0); if(strcmp($this->Tokenize($response," "),"+OK")) { $this->error="POP3 authentication server greeting was not found"; return(0); } if(!$this->PutLine("USER ".$this->user) || strlen($response=$this->GetLine())==0) return(0); if(strcmp($this->Tokenize($response," "),"+OK")) { $this->error="POP3 authentication user was not accepted: ".$this->Tokenize("\r\n"); return(0); } if(!$this->PutLine("PASS ".$password) || strlen($response=$this->GetLine())==0) return(0); if(strcmp($this->Tokenize($response," "),"+OK")) { $this->error="POP3 authentication password was not accepted: ".$this->Tokenize("\r\n"); return(0); } fclose($this->connection); $this->connection=0; } } if(count($hosts)==0) { $this->error="could not determine the SMTP to connect"; return(0); } for($host=0, $error="not connected";strlen($error) && $host<count($hosts);$host++) { $domain=$hosts[$host]; $error=$this->ConnectToHost($domain, $this->host_port, "Resolving SMTP server domain \"$domain\"..."); } if(strlen($error)) { $this->error=$error; return(0); } $timeout=($this->data_timeout ? $this->data_timeout : $this->timeout); if($timeout && function_exists("socket_set_timeout")) socket_set_timeout($this->connection,$timeout,0); if($this->debug) $this->OutputDebug("Connected to SMTP server \"".$domain."\"."); if(!strcmp($localhost=$this->localhost,"") && !strcmp($localhost=getenv("SERVER_NAME"),"") && !strcmp($localhost=getenv("HOST"),"")) $localhost="localhost"; $success=0; if($this->VerifyResultLines("220",$responses)>0) { $fallback=1; if($this->esmtp || strlen($this->user)) { if($this->PutLine("EHLO $localhost")) { if(($success_code=$this->VerifyResultLines("250",$responses))>0) { $this->esmtp_host=$this->Tokenize($responses[0]," "); for($response=1;$response<count($responses);$response++) { $extension=strtoupper($this->Tokenize($responses[$response]," ")); $this->esmtp_extensions[$extension]=$this->Tokenize(""); } $success=1; $fallback=0; } else { if($success_code==0) { $code=$this->Tokenize($this->error," -"); switch($code) { case "421": $fallback=0; break; } } } } else $fallback=0; } if($fallback) { if($this->PutLine("HELO $localhost") && $this->VerifyResultLines("250",$responses)>0) $success=1; } if($success && strlen($this->user) && strlen($this->pop3_auth_host)==0) { if(!IsSet($this->esmtp_extensions["AUTH"])) { $this->error="server does not require authentication"; $success=0; } else { if(strlen($this-><API key>)) $mechanisms=array($this-><API key>); else { $mechanisms=array(); for($authentication=$this->Tokenize($this->esmtp_extensions["AUTH"]," ");strlen($authentication);$authentication=$this->Tokenize(" ")) $mechanisms[]=$authentication; } $credentials=array( "user"=>$this->user, "password"=>$this->password ); if(strlen($this->realm)) $credentials["realm"]=$this->realm; if(strlen($this->workstation)) $credentials["workstation"]=$this->workstation; $success=$this->SASLAuthenticate($mechanisms,$credentials,$authenticated,$mechanism); if(!$success && !strcmp($mechanism,"PLAIN")) { $mechanisms=array("PLAIN"); $credentials=array( "user"=>$this->user, "password"=>$this->password ); if(strlen($this->realm)) { $success=$this->SASLAuthenticate($mechanisms,$credentials,$authenticated,$mechanism); } if(!$success) { /* * It was seen an EXIM configuration like this: * user^password^unused */ $credentials["mode"]=<API key>; $success=$this->SASLAuthenticate($mechanisms,$credentials,$authenticated,$mechanism); } if(!$success) { $credentials["mode"]=<API key>; $success=$this->SASLAuthenticate($mechanisms,$credentials,$authenticated,$mechanism); } } if($success && strlen($mechanism)==0) { $this->error="it is not supported any of the authentication mechanisms required by the server"; $success=0; } } } } if($success) { $this->state="Connected"; $this->connected_domain=$domain; } else { fclose($this->connection); $this->connection=0; } return($success); } Function MailFrom($sender) { if($this->direct_delivery) { switch($this->state) { case "Disconnected": $this->direct_sender=$sender; return(1); case "Connected": $sender=$this->direct_sender; break; default: $this->error="direct delivery connection is already established and sender is already set"; return(0); } } else { if(strcmp($this->state,"Connected")) { $this->error="connection is not in the initial state"; return(0); } } $this->error=""; if(!$this->PutLine("MAIL FROM:<$sender>")) return(0); if(!IsSet($this->esmtp_extensions["PIPELINING"]) && $this->VerifyResultLines("250",$responses)<=0) return(0); $this->state="SenderSet"; if(IsSet($this->esmtp_extensions["PIPELINING"])) $this->pending_sender=1; $this->pending_recipients=0; return(1); } Function SetRecipient($recipient) { if($this->direct_delivery) { if(GetType($at=strrpos($recipient,"@"))!="integer") return("it was not specified a valid direct recipient"); $domain=substr($recipient,$at+1); switch($this->state) { case "Disconnected": if(!$this->Connect($domain)) return(0); if(!$this->MailFrom("")) { $error=$this->error; $this->Disconnect(); $this->error=$error; return(0); } break; case "SenderSet": case "RecipientSet": if(strcmp($this->connected_domain,$domain)) { $this->error="it is not possible to deliver directly to recipients of different domains"; return(0); } break; default: $this->error="connection is already established and the recipient is already set"; return(0); } } else { switch($this->state) { case "SenderSet": case "RecipientSet": break; default: $this->error="connection is not in the recipient setting state"; return(0); } } $this->error=""; if(!$this->PutLine("RCPT TO:<$recipient>")) return(0); if(IsSet($this->esmtp_extensions["PIPELINING"])) { $this->pending_recipients++; if($this->pending_recipients>=$this-><API key>) { if(!$this->FlushRecipients()) return(0); } } else { if($this->VerifyResultLines(array("250","251"),$responses)<=0) return(0); } $this->state="RecipientSet"; return(1); } Function StartData() { if(strcmp($this->state,"RecipientSet")) { $this->error="connection is not in the start sending data state"; return(0); } $this->error=""; if(!$this->PutLine("DATA")) return(0); if($this->pending_recipients) { if(!$this->FlushRecipients()) return(0); } if($this->VerifyResultLines("354",$responses)<=0) return(0); $this->state="SendingData"; return(1); } Function PrepareData(&$data,&$output,$preg=1) { if($preg && function_exists("preg_replace")) $output=preg_replace(array("/\n\n|\r\r/","/(^|[^\r])\n/","/\r([^\n]|\$)/D","/(^|\n)\\./"),array("\r\n\r\n","\\1\r\n","\r\n\\1","\\1.."),$data); else $output=ereg_replace("(^|\n)\\.","\\1..",ereg_replace("\r([^\n]|\$)","\r\n\\1",ereg_replace("(^|[^\r])\n","\\1\r\n",ereg_replace("\n\n|\r\r","\r\n\r\n",$data)))); } Function SendData($data) { if(strcmp($this->state,"SendingData")) { $this->error="connection is not in the sending data state"; return(0); } $this->error=""; return($this->PutData($data)); } Function EndSendingData() { if(strcmp($this->state,"SendingData")) { $this->error="connection is not in the sending data state"; return(0); } $this->error=""; if(!$this->PutLine("\r\n.") || $this->VerifyResultLines("250",$responses)<=0) return(0); $this->state="Connected"; return(1); } Function ResetConnection() { switch($this->state) { case "Connected": return(1); case "SendingData": $this->error="can not reset the connection while sending data"; return(0); case "Disconnected": $this->error="can not reset the connection before it is established"; return(0); } $this->error=""; if(!$this->PutLine("RSET") || $this->VerifyResultLines("250",$responses)<=0) return(0); $this->state="Connected"; return(1); } Function Disconnect($quit=1) { if(!strcmp($this->state,"Disconnected")) { $this->error="it was not previously established a SMTP connection"; return(0); } $this->error=""; if(!strcmp($this->state,"Connected") && $quit && (!$this->PutLine("QUIT") || $this->VerifyResultLines("221",$responses)<=0)) return(0); fclose($this->connection); $this->connection=0; $this->state="Disconnected"; if($this->debug) $this->OutputDebug("Disconnected."); return(1); } Function SendMessage($sender,$recipients,$headers,$body) { if(($success=$this->Connect())) { if(($success=$this->MailFrom($sender))) { for($recipient=0;$recipient<count($recipients);$recipient++) { if(!($success=$this->SetRecipient($recipients[$recipient]))) break; } if($success && ($success=$this->StartData())) { for($header_data="",$header=0;$header<count($headers);$header++) $header_data.=$headers[$header]."\r\n"; if(($success=$this->SendData($header_data."\r\n"))) { $this->PrepareData($body,$body_data); $success=$this->SendData($body_data); } if($success) $success=$this->EndSendingData(); } } $error=$this->error; $disconnect_success=$this->Disconnect($success); if($success) $success=$disconnect_success; else $this->error=$error; } return($success); } }; ?>
"""A collection of tokenizers for use with ankura import pipelines""" import re import bs4 # Note: Each tokenizer takes in a string, and returns a list of tokens def split(data): """A tokenizer which does nothing but splitting""" return data.split() def simple(data, splitter=split): """A basic tokenizer which splits and does basic filtering. The included filters and transformations include: * lower case each token * filter out non-alphabetic characters """ tokens = splitter(data) tokens = [token.lower() for token in tokens] tokens = [re.sub(r'[^a-z]', '', token) for token in tokens] tokens = [token for token in tokens if token] return tokens def news(data, tokenizer=simple): """Tokenizes after skipping a file header Using the format from the well-known 20 newsgroups dataset, we consider the header to be everything before the first empty line in the file. The remaining contents of the file are then tokenized. """ match = re.search(r'\n\s*\n', data, re.MULTILINE) if match: data = data[match.end():] return tokenizer(data) def html(data, tokenizer=simple): """Tokenizes by extracting text from an HTML file""" return tokenizer(bs4.BeautifulSoup(data, 'html.parser').get_text()) def noop(data): """A noop tokenizer""" return data
YUI.add('attribute-complex', function(Y) { /** * Adds support for attribute providers to handle complex attributes in the constructor * * @module attribute * @submodule attribute-complex * @for Attribute */ var O = Y.Object, DOT = "."; Y.Attribute.Complex = function() {}; Y.Attribute.Complex.prototype = { /** * Utility method to split out simple attribute name/value pairs ("x") * from complex attribute name/value pairs ("x.y.z"), so that complex * attributes can be keyed by the top level attribute name. * * @method _normAttrVals * @param {Object} valueHash An object with attribute name/value pairs * * @return {Object} An object literal with 2 properties - "simple" and "complex", * containing simple and complex attribute values respectively keyed * by the top level attribute name, or null, if valueHash is falsey. * * @private */ _normAttrVals : function(valueHash) { var vals = {}, subvals = {}, path, attr, v, k; if (valueHash) { for (k in valueHash) { if (valueHash.hasOwnProperty(k)) { if (k.indexOf(DOT) !== -1) { path = k.split(DOT); attr = path.shift(); v = subvals[attr] = subvals[attr] || []; v[v.length] = { path : path, value: valueHash[k] }; } else { vals[k] = valueHash[k]; } } } return { simple:vals, complex:subvals }; } else { return null; } }, /** * Returns the initial value of the given attribute from * either the default configuration provided, or the * over-ridden value if it exists in the set of initValues * provided and the attribute is not read-only. * * @param {String} attr The name of the attribute * @param {Object} cfg The attribute configuration object * @param {Object} initValues The object with simple and complex attribute name/value pairs returned from _normAttrVals * * @return {Any} The initial value of the attribute. * * @method _getAttrInitVal * @private */ _getAttrInitVal : function(attr, cfg, initValues) { var val = cfg.value, valFn = cfg.valueFn, simple, complex, i, l, path, subval, subvals; if (valFn) { if (!valFn.call) { valFn = this[valFn]; } if (valFn) { val = valFn.call(this); } } if (!cfg.readOnly && initValues) { // Simple Attributes simple = initValues.simple; if (simple && simple.hasOwnProperty(attr)) { val = simple[attr]; } // Complex Attributes (complex values applied, after simple, incase both are set) complex = initValues.complex; if (complex && complex.hasOwnProperty(attr)) { subvals = complex[attr]; for (i = 0, l = subvals.length; i < l; ++i) { path = subvals[i].path; subval = subvals[i].value; O.setValue(val, path, subval); } } } return val; } }; Y.mix(Y.Attribute, Y.Attribute.Complex, true, null, 1); }, '3.4.1pr1' ,{requires:['attribute-base']});
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Text; using System.Xml; using System.Windows.Forms; using OpenDentBusiness; using OpenDental.UI; using CodeBase; using System.Text.RegularExpressions; namespace OpenDental { public partial class <API key>:Form { <summary>Name of the wiki list.</summary> public string WikiListCurName; public long ItemNum; public bool IsNew; <summary>Creating a data table containing only one item allows us to use column names.</summary> DataTable TableItem; public <API key>() { InitializeComponent(); Lan.F(this); } private void <API key>(object sender,EventArgs e) { TableItem = WikiLists.GetItem(WikiListCurName,ItemNum); //Show the PK in the title bar for informational purposes. We don't put it in the grid because user can't change it. this.Text=this.Text+" - "+TableItem.Columns[0]+" "+TableItem.Rows[0][0].ToString();//OK to use 0 indices here. If this fails something else is wrong. FillGrid(); } <summary></summary> private void FillGrid() { gridMain.BeginUpdate(); gridMain.Columns.Clear(); ODGridColumn col=new ODGridColumn(Lan.g(this,"Column"),200); gridMain.Columns.Add(col); col=new ODGridColumn(Lan.g(this,"Value"),400); col.IsEditable=true; gridMain.Columns.Add(col); gridMain.Rows.Clear(); ODGridRow row; for(int i=1;i<TableItem.Columns.Count;i++){//Start at 1 since row 0 (PK) goes in the title bar. row=new ODGridRow(); row.Cells.Add(TableItem.Columns[i].ColumnName); row.Cells.Add(TableItem.Rows[0][i].ToString()); if(i==0) { row.ColorBackG=Color.Gray;//darken the PK to imply that it cannot be edited. } gridMain.Rows.Add(row); } gridMain.EndUpdate(); gridMain.Title="Edit List Item"; } private void <API key>(object sender,OpenDental.UI.<API key> e) { //remove this } private void <API key>(object sender,EventArgs e) { } private void gridMain_CellLeave(object sender,<API key> e) { //Save data from grid into table. No call to DB, so this should be safe. for(int i=0;i<gridMain.Rows.Count;i++) { TableItem.Rows[0][i+1]=gridMain.Rows[i].Cells[1].Text.Replace("\r\n","\n").Replace("\n","\r\n");//Column 0 of TableItems.Rows[0] is in the title bar, so it is off from the grid by 1. } //FillGrid();//Causes errors with tabbing between cells. We put the PK in the title bar to fix this (now it doesn't need to be refreshed). } private void butDelete_Click(object sender,EventArgs e) { if(!Security.IsAuthorized(Permissions.WikiListSetup)) { return; } //maybe require all empty or admin priv if(!MsgBox.Show(this,MsgBoxButtons.OKCancel,"Delete this list item and all references to it?")) { return; } WikiLists.DeleteItem(WikiListCurName,ItemNum); DialogResult=DialogResult.OK; } private void butOK_Click(object sender,EventArgs e) { WikiLists.UpdateItem(WikiListCurName,TableItem); DialogResult=DialogResult.OK; } private void butCancel_Click(object sender,EventArgs e) { DialogResult=DialogResult.Cancel; } } }
package main import ( "encoding/json" "fmt" "log" "net/url" "sort" "testing" "github.com/stretchr/testify/assert" ) func <API key>(keyspace string) { fmt.Println("Setting up <API key>.go tests...") point := `[ { "value": 36.5, "metric": "os.cpu", "tags": { "ksid": "` + keyspace + `", "host": "a1-testTsdbMeta" } }, { "value": 54.5, "metric": "os.cpu-_/.%&#;Test", "tags": { "ksid": "` + keyspace + `", "host": "a2-testTsdb-_/.%&#;Meta" }, "timestamp": 1444166564000 }, { "value": 5.4, "metric": "execution.time", "tags": { "ksid": "` + keyspace + `", "host-_/.%&#;Name": "a1-testTsdbMeta" }, "timestamp": 1444166564000 }, { "value": 1.1, "metric": "os.cpu", "tags": { "ksid": "` + keyspace + `", "host": "a2-testTsdb-_/.%&#;Meta" }, "timestamp": 1448315804000 }, { "value": 50.1, "metric": "os.cpu", "tags": { "ksid": "` + keyspace + `", "host": "a1-testTsdbMeta" } }, { "value": 1, "metric": "os.cpu", "tags": { "ksid": "` + keyspace + `", "host": "a1-testTsdbMeta", "cpu": "1" } } ]` code, resp, err := mycenaeTools.HTTP.POST("api/put", []byte(point)) if err != nil || code != 204 { log.Fatal("send points", code, string(resp), err) } } func TestTsdb(t *testing.T) { cases := map[string]struct { url string expected []string size int }{ "Aggregator": { fmt.Sprintf("keyspaces/%s/api/aggregators", ksMycenaeTsdb), []string{"avg", "count", "min", "max", "sum"}, 5, }, "SuggestMetrics": { fmt.Sprintf("keyspaces/%s/api/suggest?type=metrics", ksMycenaeTsdb), []string{"execution.time", "os.cpu", "os.cpu-_/.%&#;Test"}, 3, }, "SuggestTagk": { fmt.Sprintf("keyspaces/%s/api/suggest?type=tagk", ksMycenaeTsdb), []string{"cpu", "host", "host-_/.%&#;Name"}, 3, }, "SuggestTagv": { fmt.Sprintf("keyspaces/%s/api/suggest?type=tagv", ksMycenaeTsdb), []string{"1", "a1-testTsdbMeta", "a2-testTsdb-_/.%&#;Meta"}, 3, }, "SuggestMetricsMax": { fmt.Sprintf("keyspaces/%s/api/suggest?type=metrics&max=1", ksMycenaeTsdb), []string{"execution.time", "os.cpu", "os.cpu-_/.%&#;Test"}, 1, }, "SuggestOverMax": { fmt.Sprintf("keyspaces/%s/api/suggest?type=metrics&max=4", ksMycenaeTsdb), []string{"execution.time", "os.cpu", "os.cpu-_/.%&#;Test"}, 3, }, } for test, data := range cases { code, response, err := mycenaeTools.HTTP.GET(data.url) if err != nil { t.Error(err) t.SkipNow() } assert.Equal(t, 200, code, test) respList := []string{} err = json.Unmarshal(response, &respList) if err != nil { t.Error(err) t.SkipNow() } assert.Equal(t, data.size, len(respList), "the total records are different than expected", test) sort.Strings(data.expected) sort.Strings(respList) if test == "SuggestMetricsMax" { assert.Contains(t, data.expected, respList[0], "the metric is different than expected", test) } else { assert.Equal(t, data.expected, respList, fmt.Sprintf("%s: FOUND: %v, EXPECTED: %v", test, respList, data.expected)) } } } func <API key>(t *testing.T) { var ( lookupExpected1 = `{"type":"LOOKUP","metric":"os.cpu","tags":[],"limit":0,"time":0,"results":[{"tsuid":"2553471299","metric":"os.cpu","tags":{"cpu":"1","host":"a1-testTsdbMeta"}},{"tsuid":"3052027985","metric":"os.cpu","tags":{"host":"a2-testTsdb-_/.%\u0026#;Meta"}},{"tsuid":"1308439016","metric":"os.cpu","tags":{"host":"a1-testTsdbMeta"}}],"startIndex":0,"totalResults":3}` lookupExpected2 = `{"type":"LOOKUP","metric":"os.cpu","tags":[],"limit":0,"time":0,"results":[{"tsuid":"2553471299","metric":"os.cpu","tags":{"cpu":"1","host":"a1-testTsdbMeta"}},{"tsuid":"1308439016","metric":"os.cpu","tags":{"host":"a1-testTsdbMeta"}},{"tsuid":"3052027985","metric":"os.cpu","tags":{"host":"a2-testTsdb-_/.%\u0026#;Meta"}}],"startIndex":0,"totalResults":3}` lookupExpected3 = `{"type":"LOOKUP","metric":"os.cpu","tags":[],"limit":0,"time":0,"results":[{"tsuid":"1308439016","metric":"os.cpu","tags":{"host":"a1-testTsdbMeta"}},{"tsuid":"2553471299","metric":"os.cpu","tags":{"cpu":"1","host":"a1-testTsdbMeta"}},{"tsuid":"3052027985","metric":"os.cpu","tags":{"host":"a2-testTsdb-_/.%\u0026#;Meta"}}],"startIndex":0,"totalResults":3}` lookupExpected4 = `{"type":"LOOKUP","metric":"os.cpu","tags":[],"limit":0,"time":0,"results":[{"tsuid":"1308439016","metric":"os.cpu","tags":{"host":"a1-testTsdbMeta"}},{"tsuid":"3052027985","metric":"os.cpu","tags":{"host":"a2-testTsdb-_/.%\u0026#;Meta"}},{"tsuid":"2553471299","metric":"os.cpu","tags":{"cpu":"1","host":"a1-testTsdbMeta"}}],"startIndex":0,"totalResults":3}` lookupExpected5 = `{"type":"LOOKUP","metric":"os.cpu","tags":[],"limit":0,"time":0,"results":[{"tsuid":"3052027985","metric":"os.cpu","tags":{"host":"a2-testTsdb-_/.%\u0026#;Meta"}},{"tsuid":"2553471299","metric":"os.cpu","tags":{"cpu":"1","host":"a1-testTsdbMeta"}},{"tsuid":"1308439016","metric":"os.cpu","tags":{"host":"a1-testTsdbMeta"}}],"startIndex":0,"totalResults":3}` lookupExpected6 = `{"type":"LOOKUP","metric":"os.cpu","tags":[],"limit":0,"time":0,"results":[{"tsuid":"3052027985","metric":"os.cpu","tags":{"host":"a2-testTsdb-_/.%\u0026#;Meta"}},{"tsuid":"1308439016","metric":"os.cpu","tags":{"host":"a1-testTsdbMeta"}},{"tsuid":"2553471299","metric":"os.cpu","tags":{"cpu":"1","host":"a1-testTsdbMeta"}}],"startIndex":0,"totalResults":3}` ) code, response, err := mycenaeTools.HTTP.GET(fmt.Sprintf("keyspaces/%s/api/search/lookup?m=os.cpu", ksMycenaeTsdb)) if err != nil { t.Error(err) t.SkipNow() } assert.Equal(t, 200, code) assert.Condition( t, func() bool { return (string(response) == lookupExpected1) || (string(response) == lookupExpected2) || (string(response) == lookupExpected3) || (string(response) == lookupExpected4) || (string(response) == lookupExpected5) || (string(response) == lookupExpected6) }, fmt.Sprintf("FOUND: %v, EXPECTED: %v or %v or %v or %v or %v or %v", string(response), lookupExpected1, lookupExpected2, lookupExpected3, lookupExpected4, lookupExpected5, lookupExpected6), ) } func <API key>(t *testing.T) { lookupExpected := `{"type":"LOOKUP","metric":"os.cpu-_/.%\u0026#;Test","tags":[],"limit":0,"time":0,"results":[{"tsuid":"2323443649","metric":"os.cpu-_/.%\u0026#;Test","tags":{"host":"a2-testTsdb-_/.%\u0026#;Meta"}}],"startIndex":0,"totalResults":1}` metricEscape := url.QueryEscape("os.cpu-_/.%\u0026#;Test") code, response, err := mycenaeTools.HTTP.GET(fmt.Sprintf("keyspaces/%s/api/search/lookup?m=%s", ksMycenaeTsdb, metricEscape)) if err != nil { t.Error(err) t.SkipNow() } assert.Equal(t, 200, code) assert.Condition( t, func() bool { return string(response) == lookupExpected }, fmt.Sprintf("FOUND: %v, EXPECTED: %v", string(response), lookupExpected), ) } //func <API key>(t *testing.T) { // lookupList := LookupError{} // code := tsdbLookupTools.HTTP.GETjson(fmt.Sprintf("keyspaces/"+ keyspacetsdbLookup +"/api/search/lookup?m=xxx"), &lookupList) // assert.Equal(t, 400, code) // assert.Equal(t, "no tsuids found", lookupList.Error, "the total records are different than expected") //func <API key>(t *testing.T) { // lookupList := LookupError{} // code := tsdbLookupTools.HTTP.GETjson(fmt.Sprintf("keyspaces/"+ keyspacetsdbLookup +"/api/search/lookup"), &lookupList) // assert.Equal(t, 400, code) // assert.Equal(t, "missing query parameter \"m\"", lookupList.Error, "the total records are different than expected")
<?php namespace Magento\Usps\Helper; use Magento\Framework\App\Helper\AbstractHelper; /** * Usps data helper */ class Data extends AbstractHelper { /** * Available shipping methods * * @var array */ protected $<API key> = [ 'usps_0_FCLE', // First-Class Mail Large Envelope 'usps_1', // Priority Mail 'usps_2', // Priority Mail Express Hold For Pickup 'usps_3', // Priority Mail Express 'usps_4', // Retail Ground 'usps_6', // Media Mail 'usps_INT_1', // Priority Mail Express International 'usps_INT_2', // Priority Mail International 'usps_INT_4', // Global Express Guaranteed (GXG) 'usps_INT_7', // Global Express Guaranteed Non-Document Non-Rectangular 'usps_INT_8', // Priority Mail International Flat Rate Envelope 'usps_INT_9', // Priority Mail International Medium Flat Rate Box 'usps_INT_10', // Priority Mail Express International Flat Rate Envelope 'usps_INT_11', // Priority Mail International Large Flat Rate Box 'usps_INT_12', // USPS GXG Envelopes 'usps_INT_14', // First-Class Mail International Large Envelope 'usps_INT_16', // Priority Mail International Small Flat Rate Box 'usps_INT_20', // Priority Mail International Small Flat Rate Envelope ]; /** * Define if we need girth parameter in the package window * * @param string $shippingMethod * @return bool */ public function displayGirthValue($shippingMethod) { return in_array($shippingMethod, $this-><API key>); } }
package at.pcgamingfreaks.Minepacks.Bukkit.API; import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.Plugin; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @SuppressWarnings("unused") public interface MinepacksPlugin { /** * Gets the instance of the minepacks plugin. * WARNING use this function at your own risk! If the plugin is not installed the MinepacksPlugin class will be unknown! * * @return The instance of the minepacks plugin. */ static @Nullable MinepacksPlugin getInstance() { Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin("Minepacks"); return (plugin instanceof MinepacksPlugin && plugin.isEnabled()) ? (MinepacksPlugin) plugin : null; } /** * Checks if the plugin is running in standalone mode. Some features and API functions are not available in standalone mode! * * @return True if the plugin is running in standalone mode. */ boolean <API key>(); /** * Let a given player open the backpack of an other player. * * @param opener The player who opens the backpack. * @param owner The owner of the backpack that should be opened. * @param editable Defines if the player who has opened the backpack can change the items inside. */ void openBackpack(@NotNull final Player opener, @NotNull final OfflinePlayer owner, final boolean editable); /** * Let a given player open a given {@link Backpack}. * * @param opener The player who opens the backpack. * @param backpack The backpack to be opened. null will result in an error message for the player. * @param editable Defines if the player who has opened the backpack can change the items inside. */ void openBackpack(@NotNull final Player opener, @Nullable final Backpack backpack, boolean editable); /** * Let a given player open the backpack of an other player. * * @param opener The player who opens the backpack. * @param owner The owner of the backpack that should be opened. * @param editable Defines if the player who has opened the backpack can change the items inside. * @param title Custom title for the backpack (will be shown to the player who opened the backpack. */ void openBackpack(@NotNull final Player opener, @NotNull final OfflinePlayer owner, final boolean editable, @Nullable String title); /** * Let a given player open a given {@link Backpack}. * * @param opener The player who opens the backpack. * @param backpack The backpack to be opened. null will result in an error message for the player. * @param editable Defines if the player who has opened the backpack can change the items inside. * @param title Custom title for the backpack (will be shown to the player who opened the backpack. */ void openBackpack(@NotNull final Player opener, @Nullable final Backpack backpack, boolean editable, @Nullable String title); /** * Retrieves the backpack for a given player. * This method only returns a backpack if it is in the cache. * * @param owner The player who's backpack should be retrieved. * @return The backpack of the given player. null if the backpack is in the cache. */ @Nullable Backpack <API key>(@NotNull final OfflinePlayer owner); /** * Retrieves the backpack for a given player. * This method runs async! The result will be delivered with a callback. * If no backpack exists a new one will be created. * * @param owner The player who's backpack should be retrieved. * @param callback The callback delivering the result of the request. */ void getBackpack(@NotNull final OfflinePlayer owner, @NotNull final Callback<Backpack> callback); /** * Retrieves the backpack for a given player. * This method runs async! The result will be delivered with a callback. * * @param owner The player who's backpack should be retrieved. * @param callback The callback delivering the result of the request. * @param <API key> If set to true, a new backpack will be created if there currently is no backpack for this player. */ void getBackpack(@NotNull final OfflinePlayer owner, @NotNull final Callback<Backpack> callback, boolean <API key>); /** * Gets the command manager of the Minepacks plugin. * * @return The command manager instance. null if the plugin is running in standalone mode */ @Nullable <API key> getCommandManager(); boolean <API key>(final @NotNull Player player); /** * Gets the item filter. * * @return The item filter. Null if item filter is disabled */ @Nullable ItemFilter getItemFilter(); /** * Checks if an item is a backpack shortcut item. * * @param itemStack item to check. * @return true if the item is a backpack shortcut item, false if not. */ boolean isBackpackItem(final @Nullable ItemStack itemStack); @NotNull WorldBlacklistMode isDisabled(Player player); }
#ifndef <API key> #define <API key> #include <fstream> #include <sstream> #include <stk/histogram.hpp> #include <stk/vector.hpp> #include <stk/exception.hpp> #include <stk/io/commons.hpp> #include <stk/io/array.hpp> namespace stk { namespace io { template<typename POS, typename VAL> void read(std::string i_filename, Histogram<1, POS, VAL>& o_histo) { std::vector<VAL> data; //Open file std::ifstream file; file.open(i_filename.c_str()); if(!file) throw exception::FileNotFound(i_filename, STK_DBG_INFO); //Read head line POS pos; POS pMin; POS pMax; VAL value; if(file >> pos >> value) { pMin = pos; pMax = pos; do { data.push_back(value); if(pMin > pos) pMin = pos; if(pMax < pos) pMax = pos; } while(file >> pos >> value); } o_histo.resize(data.size()); for(int i=0; i<data.size(); i++) { o_histo[i] = data[i]; } o_histo.setBoundaries(pMin, pMax); } template<int DIM, typename POS, typename VAL> void write( std::string i_filename, const Histogram<DIM, POS, VAL>& i_array, FileType i_type = Dat); template<int DIM, typename POS, typename VAL> void writeDat(std::string i_filename, const Histogram<DIM, POS, VAL>& i_array) { std::ofstream file; file.open(i_filename.c_str()); if(!file) throw stk::exception::FileNotWritable(i_filename, STK_DBG_INFO); file.precision(10); for(int i=0; i < i_array.getArraySize(); i++) { file << i_array.getPosFromIndice(i) << '\t'; file << i_array[i] << std::endl; } file.close(); } } } #endif
package it.cnr.iasi.leks.bedspread.impl.weights.ic; import java.lang.reflect.<API key>; import it.cnr.iasi.leks.bedspread.Node; import it.cnr.iasi.leks.bedspread.config.PropertyUtil; import it.cnr.iasi.leks.bedspread.exceptions.impl.<API key>; import it.cnr.iasi.leks.bedspread.exceptions.impl.<API key>; import it.cnr.iasi.leks.bedspread.rdf.KnowledgeBase; /** * * @author gulyx * */ public class <API key> extends <API key> { private int power; public <API key>(KnowledgeBase kb) throws <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, SecurityException, <API key> { super(kb); PropertyUtil p = PropertyUtil.getInstance(); this.power = p.getProperty(PropertyUtil.<API key>, 1); } public <API key>(KnowledgeBase kb, <API key> ew) { super(kb, ew); } /** * Compute the weight between adjacent nodes, as the maximum information content (IC) of the predicates linking n1 and n2, * and power to ..... such a max value. * The method first finds the predicates from n1 to n2. For each predicate p of such predicates, builds the triple (or edge) <n1, p, n2> and computes the weight of the edge as its IC. * Then the same is performed exchanging n1 and n2. * The result is the maximum computed weight over all the built edges. * The max is then powered by 2 in order to enlarge differences in the computation. * The values range is [0, 1] * param n1 * param n2 * return * @throws <API key> */ @Override public double weight(Node n1, Node n2) throws <API key> { if (this.power <= 0 ){ String message = PropertyUtil.<API key> + "found as: " + this.power + ", but it cannot be less-equal than 1"; throw new <API key>(message); } double result = super.weight(n1, n2); double powerResult = this.power; for (int i = 0; i < this.power; i++) { powerResult = powerResult * result; } return powerResult; } }
// d88b 888b d888 888888888888 // d8888b 8888b d8888 888 // d88''88b 888'8b d8'888 888 // d88' '88b 888 '8b d8' 888 8888888 // d88Y8888Y88b 888 '8b d8' 888 888 // d88""88b 888 '8b d8' 888 888 // d88' '88b 888 '888' 888 888 // d88' '88b 888 '8' 888 888888888888 // This program is free software; you can redistribute it and/or // as published by the Free Software Foundation; either version 3 // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // Include files #include <AME/System/Configuration.hpp> #include <AME/Graphics/GraphicsErrors.hpp> #include <AME/Graphics/PropertyTable.hpp> namespace ame { // Function type: Constructor // Contributors: Pokedude // Last edit by: Pokedude // Date of edit: 6/20/2016 PropertyTable::PropertyTable() { } // Function type: Constructor // Contributors: Pokedude // Last edit by: Pokedude // Date of edit: 6/20/2016 PropertyTable::PropertyTable(const PropertyTable &rvalue) : m_Properties(rvalue.m_Properties) { } // Function type: Constructor // Contributors: Pokedude // Last edit by: Pokedude // Date of edit: 6/20/2016 PropertyTable &PropertyTable::operator=(const PropertyTable &rvalue) { m_Properties = rvalue.m_Properties; return *this; } // Function type: Destructor // Contributors: Pokedude // Last edit by: Pokedude // Date of edit: 6/20/2016 PropertyTable::~PropertyTable() { foreach (Property *prop, m_Properties) delete prop; m_Properties.clear(); } // Function type: I/O // Contributors: Pokedude // Last edit by: Pokedude // Date of edit: 6/20/2016 bool PropertyTable::read(const qboy::Rom &rom, UInt32 offset, Int32 blocks) { if (!rom.seek(offset)) AME_THROW(PPT_ERROR_OFFSET, rom.redirected()); // Reads all properties for (int i = 0; i < blocks; i++) { Property *prop = new Property; if (CONFIG(RomType) == RT_FRLG) { prop->behaviour = rom.readByte(); prop->background = rom.readByte(); } else { prop->behaviour = rom.readHWord(); // Lower -> behaviour prop->background = rom.readHWord(); // Upper -> background } // Adds the property m_Properties.push_back(prop); } m_Offset = offset; return true; } // Function type: Getter // Contributors: Pokedude // Last edit by: Pokedude // Date of edit: 6/20/2016 const QList<Property *> &PropertyTable::properties() const { return m_Properties; } }
<?php /* * @Author Rory Standley <rorystandley@gmail.com> * @Version 1.3 * @Package Database */ class Database{ /* * Create variables for credentials to MySQL database * The variables have been declared as private. This * means that they will only be available with the * Database class */ private $db_host = "localhost"; // Change as required private $db_user = "u453794882_king"; // Change as required private $db_pass = "gamabeta"; // Change as required private $db_name = "u453794882_king"; // Change as required /* * Extra variables that are required by other function such as boolean con variable */ private $con = false; // Check to see if the connection is active private $result = array(); // Any results from a query will be stored here private $myQuery = "";// used for debugging process with SQL return private $numResults = "";// used for returning the number of rows // Function to make connection to database public function connect(){ if(!$this->con){ $myconn = @mysql_connect($this->db_host,$this->db_user,$this->db_pass); // mysql_connect() with variables defined at the start of Database class if($myconn){ $seldb = @mysql_select_db($this->db_name,$myconn); // Credentials have been pass through mysql_connect() now select the database if($seldb){ $this->con = true; return true; // Connection has been made return TRUE }else{ array_push($this->result,mysql_error()); return false; // Problem selecting database return FALSE } }else{ array_push($this->result,mysql_error()); return false; // Problem connecting return FALSE } }else{ return true; // Connection has already been made return TRUE } } // Function to disconnect from the database public function disconnect(){ // If there is a connection to the database if($this->con){ // We have found a connection, try to close it if(@mysql_close()){ // We have successfully closed the connection, set the connection variable to false $this->con = false; // Return true tjat we have closed the connection return true; }else{ // We could not close the connection, return false return false; } } } public function sql($sql){ $query = @mysql_query($sql); $this->myQuery = $sql; // Pass back the SQL if($query){ // If the query returns >= 1 assign the number of rows to numResults $this->numResults = mysql_num_rows($query); // Loop through the query results by the number of rows returned for($i = 0; $i < $this->numResults; $i++){ $r = mysql_fetch_array($query); $key = array_keys($r); for($x = 0; $x < count($key); $x++){ // Sanitizes keys so only alphavalues are allowed if(!is_int($key[$x])){ if(mysql_num_rows($query) >= 1){ $this->result[$i][$key[$x]] = $r[$key[$x]]; }else{ $this->result = null; } } } } return true; // Query was successful }else{ array_push($this->result,mysql_error()); return false; // No rows where returned } } // Function to SELECT from the database public function select($table, $rows = '*', $join = null, $where = null, $order = null, $limit = null){ // Create query from the variables passed to the function $q = 'SELECT '.$rows.' FROM '.$table; if($join != null){ $q .= ' JOIN '.$join; } if($where != null){ $q .= ' WHERE '.$where; } if($order != null){ $q .= ' ORDER BY '.$order; } if($limit != null){ $q .= ' LIMIT '.$limit; } $this->myQuery = $q; // Pass back the SQL // Check to see if the table exists if($this->tableExists($table)){ // The table exists, run the query $query = @mysql_query($q); if($query){ // If the query returns >= 1 assign the number of rows to numResults $this->numResults = mysql_num_rows($query); // Loop through the query results by the number of rows returned for($i = 0; $i < $this->numResults; $i++){ $r = mysql_fetch_array($query); $key = array_keys($r); for($x = 0; $x < count($key); $x++){ // Sanitizes keys so only alphavalues are allowed if(!is_int($key[$x])){ if(mysql_num_rows($query) >= 1){ $this->result[$i][$key[$x]] = $r[$key[$x]]; }else{ $this->result = null; } } } } return true; // Query was successful }else{ array_push($this->result,mysql_error()); return false; // No rows where returned } }else{ return false; // Table does not exist } } // Function to insert into the database public function insert($table,$params=array()){ // Check to see if the table exists if($this->tableExists($table)){ $sql='INSERT INTO `'.$table.'` (`'.implode('`, `',array_keys($params)).'`) VALUES ("' . implode('", "', $params) . '")'; $this->myQuery = $sql; // Pass back the SQL // Make the query to insert to the database if($ins = @mysql_query($sql)){ array_push($this->result,mysql_insert_id()); return true; // The data has been inserted }else{ array_push($this->result,mysql_error()); return false; // The data has not been inserted } }else{ return false; // Table does not exist } } //Function to delete table or row(s) from database public function delete($table,$where = null){ // Check to see if table exists if($this->tableExists($table)){ // The table exists check to see if we are deleting rows or table if($where == null){ $delete = 'DROP TABLE '.$table; // Create query to delete table }else{ $delete = 'DELETE FROM '.$table.' WHERE '.$where; // Create query to delete rows } // Submit query to database if($del = @mysql_query($delete)){ array_push($this->result,mysql_affected_rows()); $this->myQuery = $delete; // Pass back the SQL return true; // The query exectued correctly }else{ array_push($this->result,mysql_error()); return false; // The query did not execute correctly } }else{ return false; // The table does not exist } } // Function to update row in database public function update($table,$params=array(),$where){ // Check to see if table exists if($this->tableExists($table)){ // Create Array to hold all the columns to update $args=array(); foreach($params as $field=>$value){ // Seperate each column out with it's corresponding value $args[]=$field.'="'.$value.'"'; } // Create the query $sql='UPDATE '.$table.' SET '.implode(',',$args).' WHERE '.$where; // Make query to database $this->myQuery = $sql; // Pass back the SQL if($query = @mysql_query($sql)){ array_push($this->result,mysql_affected_rows()); return true; // Update has been successful }else{ array_push($this->result,mysql_error()); return false; // Update has not been successful } }else{ return false; // The table does not exist } } // Private function to check if table exists for use with queries private function tableExists($table){ $tablesInDb = @mysql_query('SHOW TABLES FROM '.$this->db_name.' LIKE "'.$table.'"'); if($tablesInDb){ if(mysql_num_rows($tablesInDb)==1){ return true; // The table exists }else{ array_push($this->result,$table." does not exist in this database"); return false; // The table does not exist } } } // Public function to return the data to the user public function getResult(){ $val = $this->result; $this->result = array(); return $val; } //Pass the SQL back for debugging public function getSql(){ $val = $this->myQuery; $this->myQuery = array(); return $val; } //Pass the number of rows back public function numRows(){ $val = $this->numResults; $this->numResults = array(); return $val; } // Escape your string public function escapeString($data){ return <API key>($data); } }
/** * $Id: org_lwjgl_Sys.c 3616 2011-08-16 22:17:32Z spasi $ * * Windows system library. * * @author cix_foo <cix_foo@users.sourceforge.net> * @version $Revision: 3616 $ */ #include "Window.h" #include "mmsystem.h" #include "<API key>.h" #include "common_tools.h" #include <malloc.h> #include <commctrl.h> JNIEXPORT jlong JNICALL <API key>(JNIEnv * env, jclass unused) { DWORD time; timeBeginPeriod(1); time = timeGetTime(); timeEndPeriod(1); return time; } JNIEXPORT void JNICALL <API key>(JNIEnv * env, jclass unused, jlong hwnd_ptr, jlong title, jlong message) { HWND hwnd = (HWND)(INT_PTR)hwnd_ptr; MessageBox(hwnd, (LPCTSTR)(intptr_t)message, (LPCTSTR)(intptr_t)title, MB_OK | MB_TOPMOST); } JNIEXPORT void JNICALL <API key>(JNIEnv * env, jclass unused) { InitCommonControls(); } JNIEXPORT jstring JNICALL <API key> (JNIEnv * env, jclass unused) { // Check to see if there's text available in the clipboard BOOL textAvailable = <API key>(CF_TEXT); BOOL unicodeAvailable = <API key>(CF_UNICODETEXT); void *clipboard_data; jstring ret; HANDLE hglb; const wchar_t * str; if (unicodeAvailable) { if (!OpenClipboard(NULL)) return NULL; hglb = GetClipboardData(CF_UNICODETEXT); if (hglb == NULL) { CloseClipboard(); return NULL; } clipboard_data = GlobalLock(hglb); if (clipboard_data == NULL) { CloseClipboard(); return NULL; } str = (const wchar_t *)clipboard_data; ret = (*env)->NewString(env, str, wcslen(str)); } else if (textAvailable) { if (!OpenClipboard(NULL)) return NULL; hglb = GetClipboardData(CF_TEXT); if (hglb == NULL) { CloseClipboard(); return NULL; } clipboard_data = GlobalLock(hglb); if (clipboard_data == NULL) { CloseClipboard(); return NULL; } ret = <API key>(env, (const char *) clipboard_data, strlen(clipboard_data)); } else { return NULL; } GlobalUnlock(hglb); CloseClipboard(); return ret; }
<?php if (!defined('_SECURE')) die ("No direct access to configuration file"); // Sphider-plus version $plus_nr = '3.2014a'; // Original Sphider version $version_nr = '1.3.5'; // IDS impact warn level $ids_warn = '14'; // IDS impact stop traffic level $ids_stop = '25'; //Standard charset of your location (e.g. ISO-8859-1) $home_charset = 'utf-8'; //Administrators email address (logs and info emails will be sent there) $admin_email = 'admin@localhost'; //Dispatcher email address (info emails will be sent from this account) $dispatch_email = 'postmaster@localhost'; //Address to localhost document root $local = 'http://localhost/publizieren/'; //Folder for thumbnails during search procedure $thumb_dir = './include/thumbs'; //Folder for thumbnails during index procedure $thumb_folder = './admin/thumbs'; //Folder for XML results $xml_dir = './xml'; //Delimiter to separate real tile and transliterated part of media titles $delim = ' _-_- '; //Folder relative to .../admin/ where all the files for URL import / export will be handled $url_path = './urls/'; //latest implemented field in db $latest_field = 'webshot'; //involved table for the latest field $latest_table = 'links'; //Delimiter to separate arguments in text file for URL import & export $arg_delim = '|'; //Titel for category0 $group_name_0 = ''; //Titel for category1 $group_name_1 = ''; //Titel for category2 $group_name_2 = ''; //Titel for category3 $group_name_3 = ''; //Titel for category4 $group_name_4 = ''; // Accept non-ASCII URLS to be added $idna = 1; // Show complete list of URLs during import and export $show_url = 1; // Default for number of sites per page in Admin backend $sites_per_page = 20; // Sort Sites table in Admin section in alphabetic order $sites_alpha = 1; // Sort Sites table in Admin section in index priority order $sites_prior = 0; // Sort Sites table in Admin section by indexdate, latest on top $sites_latest = 0; // Sort Sites table in Admin section by indexdate, oldest on top $sites_oldest = 0; // Sort Sites table in Admin section by title $sites_title = 0; // Show cat titles in Sites view $cat_title = 1; // MySQL query cache $qcache = 1; // Don't erase URLs containing 'Must Not include' words $not_erase = 1; // .htaccess protection for admin folder $htaccess = 0; // Admin debug mode - Show details from index / re-index procedure, MySQL and PHP error messages $debug = 2; // User debug mode - Show details concerning database and cache activity $debug_user = 0; // Use 'Intrusion Detection System' $use_ids = 0; // Block Internet traffic of IP's detected by 'Intrusion Detection System' $ids_blocked = 0; // Free resources when indexing large amount of URLs $clear = 0; // Reset query log during erase and index procedures $clear_query = 1; // Remember new domains found during index procedure $auto_add = 0; // Delete related keywords and links after site delete $del_related = 1; // Template directory $templ_dir = 'templates'; // Temporary directory, this should be readable and writable $tmp_dir = 'tmp'; // Name of search script $search_script = 'search.php'; // Embedded application of Sphider-plus HTML code $embedded = ''; // Operating System $op_system = 'lin'; // Availability of cURL library $curl = '1'; // Disable output of logging data during index / re-index $no_log = 0; // Enable real-time output of logging data $real_log = 0; // Interval for real-time Log file update [seconds] $refresh = 5; // Interval until next click will be accepted to increase popularity of a link [seconds] $click_wait = 60; // Should log files be kept $keep_log = 1; //Log directory, this should be readable and writable $log_dir = 'log'; // Log format $log_format = 'html'; // Send log file by email $email_log = 0; // Separate between upper- and lower-case queries $case_sensitive = 0; // Sitemap directory, this should be readable and writable $smap_dir = 'sitemaps'; // Count of threads for indexing $multi_indexer = '1'; // Max. links to be followed per site $max_links = '1000'; // Interrupt indexer each x links $interrupt = '&nbsp;&nbsp; // Min words per page required for indexing $min_words_per_page = 5; // Words shorter than this will not be indexed $min_word_length = 3; // Keyword weight depending on the number of times it appears in a page is capped at this value $word_upper_bound = 10; // The length of full text, indexed at each page [0=unlimeted]. $text_length = 0; // If available follow 'sitemap.xml' $follow_sitemap = 0; // Create sitemap.xml file of each indexed site $create_sitemap = 0; // Sitemap name unique for all .xml files $smap_unique = '0'; // Convert UTF-16 coded sites into UTF-8 $utf_16 = '0'; // Create a thumbnail of Internet URLs $webshot = '0'; // The individual code for webshots $shot_code = '0'; // The individual key for webshots $shot_key = '0'; // Verify all URLs by Google safe browsing API $google_sb = '0'; // Individual API key for Google save browsing $g_api_key = ''; // Crawler can leave domain during indexing $domaincb = 0; // Use preferred charset for indexing $use_prefcharset = 0; // Indexing depth $depth = -1; // Index numbers as well $index_numbers = 0; // if this value is set to 1, word in domain name and url path are also indexed, // if the word is not included in the page itself. $index_host = 0; // Whether to index the Meta tag: Title $index_meta_title = 1; // Whether to index the Meta tag: Keywords $index_meta_keywords = 1; // Whether to index the Meta tag: Description $<API key> = 1; // Do not index the full text $ignore_fulltxt = 0; // Do not index HTML comments and scripts outside the html tags $ignore_comment = 1; // Index PDF files $index_pdf = 0; // Index DOC files $index_doc = 0; // Index RTF files $index_rtf = 0; // Index XLS files $index_xls = 0; // Index XLSX files $index_xlsx = 0; // Index CSV files $index_csv = 0; // Index DOCX files $index_docx = 0; // Index meta content in DOCX files $index_xmeta = 0; // Index PPT files $index_ppt = 0; // Index ODS files $index_ods = 0; // Index ODT files $index_odt = 0; //Path to PDF converter $pdftotext_path = '..\converter\pdftotext'; //Path to DOC converter $catdoc_path = '..\converter\catdoc.exe'; //Path to PPT converter $catppt_path = ''; //Multibyte extention of PHP $mb = '1'; // Index media files (general selection) $index_media = '0'; // Index image files $index_image = '0'; // Minimum size for image files (width) $min_image_x = '50'; // Minimum size for image files (height) $min_image_y = '50'; // Index audio files $index_audio = '0'; // Index video files $index_video = '0'; // Index embeded media files $index_embeded = '1'; // Index alt tag of images $index_alt = '0'; // Suppress file suffix from image names $suppress_suffix = '0'; // Index ID3 tags $index_id3 = '1'; // Index duplicate media on different pages $dup_media = '1'; // Index external hosted media content $ex_media = '1'; // Index RSS and Atom feeds $index_rss = '1'; // Follow CDATA tags in feeds $cdata = '1'; // Index Dublin Core tags in RDF feeds $dc = '1'; // Follow PREFERRED directive in RSD feeds $preferred = '1'; // Index RAR files and archives $index_rar = '0'; // Index ZIP files and archives $index_zip = '0'; // Index framesets $index_framesets = '1'; // Index iframes $index_iframes = '1'; // Jump to iframe directly $iframe_link = '1'; // Index media conent with respect toframe/iframe position $abslinks = '0'; // Time interval for auto re-index $interval = 'never'; // Auto re-index counter $intv_count = '9999'; // Language of 'common word' list $use_common = 'en'; // Use any word in whitelist to enable page indexing $use_white1 = '0'; // Use all words of whitelist to enable page indexing $use_white2 = '0'; // Use blacklist to prevent page indexing $use_black = '0'; // Use blacklist to delete query input $kill_query = '1'; // Trim words in white- and blacklist $trim_words = '1'; // Use div-list to ignore some divs $not_divs = '1'; // Use div-list to index only div content $use_divs = '0'; // Use element-list to ignore some HTML elements $not_elems = '0'; // Use element-list to index only HTML element content $use_elems = '0'; // Delete HTML elements defined like & l t ; element & g t ; $del_elems = '0'; // Convert punycode URLs in full text into readable $conv_puny = '0'; // Delete duplicate characters in page contnets $del_dups = '1'; // Delete secondary characters at the beginning and end of words $del_secchars = '1'; // Delete secondary characters inside of words $del_seccharin = '1'; // Use simple quotes $quotes = '1'; // Convert double quotes $dup_quotes = '1'; // Convert accents into their basic vowels $vowels = '1'; // User agent string $user_agent = 'Sphider-plus'; // Browser http_agent_string $browser_string = '1'; // Always use Firefox HTTP_USER_AGENT $default_agent = '0'; // Verify the charset after converting into UTF-8 $utf8_verify = '0'; // Use charset as supplied by the server $server_char = '1'; // Minimal delay between page downloads $min_delay = 0; // Use word stemming for language $stem_words = 'en'; // Count of redirections to be followed $redir_count = 5; // Folow returnURL links immediately $return_url = 1; // Convert link URLs to lower case $lower_links = 0; // Convert link URLs to UTF-8 $utf8_links = 0; // Strip session ids (PHPSESSID, JSESSIONID, ASPSESSIONID, sid) $strip_sessids = 1; // additionally strip session id: s $strip_s_sessids = 0; // Add a final slash to pth in all detected links $wfs = 1; $other_host = 0; $redir_host = 1; // Crawler can leave domain, but only for canonical links. $cano_leave = 0; // Follow redirections found in JavaScript. $js_reloc = 0; // Obay refresh delay directives, placed in meta tags. $refresh_delay = 0; // Delete duplicates in link path. $dup_path = 0; // Index only documents $only_docs = 0; // Index only links and their titles $only_links = 0; // Enable link-check instead of reindex $link_check = 0; // Enable index and re-index for pages with duplicate content $dup_content = 0; // Split words into their basic parts, separated at hyphens, dots and commas $div_all = 1; // Split words into their basic parts, separated only at hyphens $div_hyphen = 0; // Decode BBcode during index $bb_decode = 0; // Decode UTF-8 HTML entities during index $ent_decode = 1; // Support Greek language $greek = 0; // Support Cyrillic language $cyrillic = 0; // Perform a segmentation of Chinese text during index $cn_seg = 0; // Perform a segmentation of Japanese text during index $jp_seg = 0; // User name1 for password protected pages $user1 = '0'; // Password1 for password protected pages $pwd1 = '0'; // User name2 for password protected pages $user2 = '0'; // Password2 for password protected pages $pwd2 = '0'; // User name3 for password protected pages $user3 = '0'; // Password3 for password protected pages $pwd3 = '0'; //Language of the search page $language = 'en'; //Auto detect client language $auto_lng = '1'; // Prevent queries from harvester, bots and known evial user-agents $kill_black_uas = 1; // Prevent queries from Meta search engines like Google $kill_black_ips = 1; // Prevent queries causing XSS attacks, Tag inclusions, Shell and JavaScript exec. $block_attacks = 1; //Use cache for search results $use_cache = '1'; //Cache size [MB] for text search results $tcache_size = '2'; //Cache size [MB] for media search results $mcache_size = '2'; //Max results/links per query in text cache $max_ctresults = '9999'; //Max results/links per query in media cache $max_cmresults = '9999'; //Clear text and media cache during re-index procedure $clear_cache = '1'; // Template design/Directory in templates dir $template = 'Sphider-plus'; // Title for Results Page $mytitle = 'RACHEL Results'; //Type of highlighting for found keywords $mark = 'markbold'; // Default for number of results per page $results_per_page = 10; // Can speed up searches on large database (should be 0) $bound_search_result = 100; // Number of links shown to next pages $links_to_next = 9; // Show elapsed time in result header $elapsed = 1; // Show meta description in results page if it exists, otherwise show an extract from the page text. $<API key> = 0; // Show warning message if search string was found only in title or url. $show_warning = 1; // Advanced query form, shows and/or buttons $advanced_search = 1; // Show actual result number for each result $show_res_num = 0; // Query scores are not shown if set to 0 $show_query_scores = 0; // Show the URL of each result $show_res_url = 1; // Search without quotes $no_quotes= 1; // Search with/without ligatures $liga= 0; // Highlight search results strictly $strict_high= 1; // Queries with numbers become wildsearch $wild_num= 0; // Translitate queries from Latin characters to Greek $translit_el= 0; //Accept Greek vowels without accents $noacc_el= 0; // Display category list $show_categories = 1; // Display category selection at each result $more_catres = 0; // Max length of page title given in results page $title_length = 80; // Max length of URL given in results page $url_length = 80; // Length of page description given in results page $desc_length = 250; // Max hits shown per link in results page $max_hits = 3; // Show order of result listing as headline $show_sort = 0; // Show media results as well as text results in result page $show_media = 0; // Limit media results, if presented togetherr with text results in result page $limit_media = 8; // Search for media results also in EXIF and ID3 info $search_id3 = 0; // Chronological order of media result listing $sort_media = 1; // Show separate search field for media queries $sep_media = 0; // Show 'Most popular searches' at the bottom of result pages $most_pop = 1; // Suppress zero results in 'Most popular searches' $no_zeros = 1; // Show 3D tag cloud in 'Most popular searches' $tag_cloud = 0; // Show 3D tag cloud in differernt colors for each query hit $color_cloud = 0; // Number of rows for 'Most popular searches' $pop_rows = 5; // Min. relevance level (%) to be shown at result pages $relevance = 0; // Max. quantity of results for result listing $max_results = 999; // Show db content at the bottom of result listing $db_content = 0; // Show 'User may suggest a Url' at the bottom of result pages' $add_url = 0; // Use authentification for suggested URLs $add_auth = 0; // Inform about user suggestion by e-mail $addurl_info = 1; // Perform a WHOIS check for suggested URLs $whois_user = 0; // Perform a WHOIS check for suggested URLs in Admin backend $whois_admin = 0; // Use extended suffix list for WHOIS checks $whois_ext = 0; // Use Captcha for Addurl-form $captcha = 0; // Enable spelling suggestions (Did you mean...) $<API key> = 1; // Define min. character input for suggestion $min_sug_chars = 1; // Search for suggestions in query log $suggest_history = 0; // Search for suggestions in keywords $suggest_keywords = 1; // Build suggestions also for phrases $suggest_phrases = 1; // Search for suggestions in id3 tags $suggest_id3 = 0; // Limit count of suggestions $suggest_rows = 20; // Relative weight of a word in the title of a webpage $title_weight = 20; // Relative weight of a word in the domain name $domain_weight = 60; // Relative weight of a word in the path name $path_weight = 10; // Relative weight of a word in meta_keywords $meta_weight = 5; // Defines multiplier for words in main URLs (domains) $domain_mul = 1; // Defines method of chronological order for result listing $sort_results = 1; // Name of promoted domain $dompromo = ''; // Name of promoted catchword $keypromo = ''; // Max results per domain in result listing $dom_count = '2'; ?>
<!DOCTYPE HTML PUBLIC "- <!--NewPage <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_65) on Fri Nov 01 09:18:13 CDT 2013 --> <TITLE> KetaiNet </TITLE> <META NAME="date" CONTENT="2013-11-01"> <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="KetaiNet"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <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="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/KetaiNet.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-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 CLASS&nbsp; &nbsp;<A HREF="../../ketai/net/KetaiOSCMessage.html" title="class in ketai.net"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../index.html?ketai/net/KetaiNet.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="KetaiNet.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> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <HR> <H2> <FONT SIZE="-1"> ketai.net</FONT> <BR> Class KetaiNet</H2> <PRE> java.lang.Object <IMG SRC="../../resources/inherit.gif" ALT="extended by "><B>ketai.net.KetaiNet</B> </PRE> <HR> <DL> <DT><PRE>public class <B>KetaiNet</B><DT>extends java.lang.Object</DL> </PRE> <P> The Class KetaiNet. <P> <P> <HR> <P> <A NAME="constructor_summary"></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Constructor Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><B><A HREF="../../ketai/net/KetaiNet.html#KetaiNet()">KetaiNet</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <A NAME="method_summary"></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Method Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;java.lang.String</CODE></FONT></TD> <TD><CODE><B><A HREF="../../ketai/net/KetaiNet.html#getIP()">getIP</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Gets the ip address of our device.</TD> </TR> </TABLE> &nbsp;<A NAME="<API key>.lang.Object"></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="<API key>"> <TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE>equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD> </TR> </TABLE> &nbsp; <P> <A NAME="constructor_detail"></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Constructor Detail</B></FONT></TH> </TR> </TABLE> <A NAME="KetaiNet()"></A><H3> KetaiNet</H3> <PRE> public <B>KetaiNet</B>()</PRE> <DL> </DL> <A NAME="method_detail"></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Method Detail</B></FONT></TH> </TR> </TABLE> <A NAME="getIP()"></A><H3> getIP</H3> <PRE> public static java.lang.String <B>getIP</B>()</PRE> <DL> <DD>Gets the ip address of our device. This IP may vary depending on the network configuration (mobile data vs. wifi). <P> <DD><DL> <DT><B>Returns:</B><DD>the ip</DL> </DD> </DL> <HR> <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="<API key>"></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="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/KetaiNet.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-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 CLASS&nbsp; &nbsp;<A HREF="../../ketai/net/KetaiOSCMessage.html" title="class in ketai.net"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../index.html?ketai/net/KetaiNet.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="KetaiNet.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> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <HR> </BODY> </HTML>
<?php class Change<API key> extends LinkActionElement { public function getActionType() { return 'Edit'; } protected function getDefaultLabel() { return Yii::t('Default', 'Change Password'); } protected function getDefaultRoute() { return Yii::app()->createUrl($this->moduleId . '/' . $this->controllerId . '/changePassword/', array('id' => $this->modelId)); } } ?>
package org.jaffa.util; import org.apache.log4j.*; import java.io.*; import java.util.*; /** An instance of this class can represent a node in a tree. * Each node will have a system generated unique identifier. * It may have a name (which can be non-unique). * It can be linked to a Parent node or be the Root of the tree. * It can have child nodes. * It will have a value Object. * Additionally it can have a map of attributes. */ public class Node { private static Logger log = Logger.getLogger(Node.class); private static long c_nextId = 0; /** A unique identifier for a node which is system-generated */ private String m_id = null; /** Name for a node. Multiple Nodes can share the same name. Can be null */ private String m_name = null; /** Value for a node. Can be null */ private Object m_value = null; /** Parent node. Can be null if no parent exists */ private Node m_parent = null; /** Root node. Will have the same value as m_id if the node is a root */ private Node m_root = null; /** This will maintain name-value pairs for the node */ private Map m_attributes = null; /** This will maintain the child nodes */ private Collection m_children = null; /** This will maintain the child nodes, grandchildren, <API key> & so on... * as id-node pairs in the root node only */ private Map m_family = null; /** A temporary field */ private transient Collection m_childrenCol = null; /** Creates new Node */ public Node() { this(null); } /** Creates new Node specifying a name. * @param name The node name. */ public Node(String name) { m_id = Node.getNextId(); m_name = name; // treat the node as a ROOT initially m_root = this; } /** Returns the unique identifier of the node. * @return the unique identifier of the node. */ public String getId() { return m_id; } /** Returns the Parent node, or null if this node has no parent. * @return the Parent node, or null if this node has no parent. */ public Node getParent() { return m_parent; } /** Returns the root node of the tree to which this node belongs. * @return the root node of the tree to which this node belongs. */ public Node getRoot() { return m_root; } /** Returns a collection of child nodes. * @return a collection of child nodes. */ public Collection getChildren() { if (m_children == null) m_childrenCol = null; else if (m_childrenCol == null) m_childrenCol = new Node.Children(); return m_childrenCol; } /** Returns the 1st child which matches the name. * @param name The node name. * @return the 1st child which matches the name. */ public Node getChildByName(String name) { Node node = null; if ( m_children != null && !m_children.isEmpty() ) { for (Iterator itr = m_children.iterator(); itr.hasNext();) { node = (Node) itr.next(); if ( node.getName() == null ? name == null : node.getName().equals(name) ) break; else node = null; } } return node; } /** Returns the child by id. * @param id The node identifier. * @return the child by id. */ public Node getChildById(String id) { Node node = getFromFamilyById(id); if (node == null || m_children == null || m_children.isEmpty() || !m_children.contains(node) ) node = null; return node; } /** Returns a node from the family by id. * @param id The node identifier. * @return a node from the family by id. */ public Node getFromFamilyById(String id) { if (id != null && m_root!= null && m_root.m_family != null) return (Node) m_root.m_family.get(id); else return null; } /** Getter for property name. * @return Value of property name. */ public String getName() { return m_name; } /** Setter for property name. * @param name New value of property name. */ public void setName(String name) { m_name = name; } /** Getter for property value. * @return Value of property value. */ public Object getValue() { return m_value; } /** Setter for property value. * @param value New value of property value. */ public void setValue(Object value) { m_value = value; } /** Getter for property attributes. * @return Value of property attributes. */ public Map getAttributes() { return m_attributes; } /** Setter for property attributes. * @param attributes New value of property attributes. */ public void setAttributes(Map attributes) { m_attributes = attributes; } /** Returns the attribute for the specified key. * @param key The attribute key. * @return the attribute for the specified key. */ public Object getAttribute(Object key) { if (m_attributes != null) return m_attributes.get(key); else return null; } /** Adds an attribute. Will replace an existing attribute having the same key. * @param key The attribute key. * @param value The attribute value. * @return previous value associated with specified key, or null if there was no attribute for key. */ public Object setAttribute(Object key, Object value) { if (m_attributes == null) m_attributes = new ListMap(); return m_attributes.put(key, value); } /** Removes an attribute . * @param key The attribute key. * @return the attribute that was removed, or null if there was no such attribute. */ public Object removeAttribute(Object key) { if (m_attributes != null) return m_attributes.remove(key); else return null; } /** Returns true if the node is its own root. * @return true if the node is its own root. */ public boolean isRoot() { return this == m_root; } /** Returns true if the node has childen. * @return true if the node has childen. */ public boolean hasChildren() { return m_children != null && !m_children.isEmpty() ; } /** Returns true if the parent node has any more child nodes after the current node. * @return true if the parent node has any more child nodes after the current node. */ public boolean <API key>() { boolean result = false; Node parent = getParent(); if (parent != null) { int i = ( (List) parent.m_children ).indexOf(this); if (i < (parent.m_children.size() - 1) ) result = true; } return result; } /** Makes the node its own root. Will remove links from existing parent node, if any. */ public void makeRoot() { if ( !isRoot() ) { // set the new root for this node as well all its children setRoot(m_root, this); // remove this node from the old Parent node's childList if (m_parent != null) m_parent.removeFromChildren(this); // reset the parent m_parent = null; } } /** Adds a child node. Will add a link both ways. * @param node The child node. */ public void addChild(Node node) { if (node != null) { Node oldParentNode = node.getParent(); Node oldRootNode = node.getRoot(); // take care of the parent references if (oldParentNode != null) oldParentNode.removeFromChildren(node); node.m_parent = this; // reset the family, in case 'node' is a root node.m_family = null; // add the 'node' to the children collection addToChildren(node); // reset the root refernces if (m_root != oldRootNode) node.setRoot(oldRootNode, m_root); } } /** Removes a child node. Will add a link both ways. * @param node The child node. * @return true if the child node was removed. */ public boolean removeChild(Node node) { boolean result = false; if (node != null) { result = removeFromChildren(node); // just make the node a Root. This will remove all old links node.makeRoot(); } return result; } /** Removes the 1st child that matches the name * @param name The node name. * @return true if the child node was removed. */ public boolean removeChild(String name) { boolean result = false; Node node = getChildByName(name); if (node != null) result = removeChild(node); return result; } /** Remove all children. * @return true if any child node was removed. */ public boolean removeChildren() { Collection col = getChildren(); if ( col != null && !col.isEmpty() ) { int i = m_children.size(); for (Iterator itr = col.iterator(); itr.hasNext();) { itr.next(); itr.remove(); } return i != m_children.size(); } else return false; } /** A helper routine to print the contents of a node. * @param writer The writer to which the node contents will be printed. * @throws IOException if any I/O error occurs. */ public void printNode(java.io.Writer writer) throws java.io.IOException { printNode(writer, null, " "); } /** A helper routine to print the contents of a node. * @param writer The writer to which the node contents will be printed. * @param pad The pad string to be used. * @param padIncrement The increment string to be appended to the pad string at each successive level of child nodes. * @throws IOException if any I/O error occurs. */ public void printNode(java.io.Writer writer, String pad, String padIncrement) throws java.io.IOException { pad = (pad == null ? "" : pad) + (padIncrement == null ? "" : padIncrement); // print the main fields writer.write( pad + "Id=" + getId() + ", Name=" + getName() + ", Value=" + getValue() + ", Root=" + ( getRoot() == null ? "null" : getRoot().getId().toString() ) + ", Parent=" + ( getParent() == null ? "null" : getParent().getId().toString() ) ); // add the attributes, if any if ( getAttributes() != null && !(getAttributes().isEmpty()) ) { writer.write(", Attributes="); for (Iterator itr = getAttributes().entrySet().iterator(); itr.hasNext();) { Map.Entry me = (Map.Entry) itr.next(); writer.write(me.getKey() + "=" + me.getValue() + (itr.hasNext() ? ", " : "") ); } } writer.write('\n'); // print the family, if any if ( m_family != null && !m_family.isEmpty() ) { writer.write(pad + "Family="); for (Iterator itr = m_family.keySet().iterator(); itr.hasNext();) { writer.write( itr.next() + (itr.hasNext() ? ", " : "") ); } writer.write('\n'); } // recursively print the children if ( getChildren() != null && !(getChildren().isEmpty()) ) { for (Iterator itr = getChildren().iterator(); itr.hasNext(); ) ( (Node) itr.next() ).printNode(writer, pad, padIncrement ); } } /** Returns true if the iteration has more elements. * @return true if the iteration has more elements. */ public boolean hasNext() { return m_iterator.hasNext(); } /** Returns the next element in the iteration. * @return the next element in the iteration. */ public Object next() { m_lastReturned = m_iterator.next(); return m_lastReturned; } /** Removes from the underlying collection the last element returned by the iterator. */ public void remove() { m_iterator.remove(); Node.this.removeChild( (Node) m_lastReturned ); } } private class Children extends AbstractCollection { /** Returns the number of elements in this collection. * @return the number of elements in this collection. */ public int size() { return Node.this.m_children.size(); } /** Returns true if this collection contains the specified element. * @param o element whose presence in this collection is to be tested. * @return true if this collection contains the specified element. */ public boolean contains(Object o) { return Node.this.m_children.contains(o); } /** Removes all of the elements from this collection. */ public void clear() { Node.this.removeChildren(); } /** Returns an iterator over the elements in this collection. * @return an iterator over the elements in this collection. */ public Iterator iterator() { return Node.this.getIterator(); } } /** Test rig * @param args The arguments. Not used. */ public static void main(String[] args) { try { StringWriter sWriter = new StringWriter(); Node node1 = new Node("Node1"); Node node2 = new Node("Node2"); Node node3 = new Node("Node3"); Node node4 = new Node("Node4"); node4.setValue("Value for node4"); node4.setAttribute("key1", "key1Value"); node4.setAttribute("key2", "key2Value"); node4.setAttribute("key3", "key3Value"); node1.addChild(node2); node1.addChild(node3); node1.addChild(node4); Node node5 = new Node("Node5"); Node node6 = new Node("Node6"); Node node7 = new Node("Node7"); Node node8 = new Node("Node8"); node2.addChild(node5); node3.addChild(node6); node6.addChild(node7); node3.addChild(node8); node1.printNode(sWriter); sWriter.write('\n'); sWriter.write("Make Node3 a root\n"); node3.makeRoot(); sWriter.write("Contents of Node1\n"); node1.printNode(sWriter); sWriter.write('\n'); sWriter.write("Contents of Node3\n"); node3.printNode(sWriter); sWriter.write('\n'); sWriter.write("Add Node3 to Node2, Remove node5 from node2, Remove an attribute\n"); node2.addChild(node3); node4.removeAttribute("key2"); node2.removeChild(node5); sWriter.write("Contents of Node1\n"); node1.printNode(sWriter); sWriter.write('\n'); sWriter.write("Removing the children from node1\n"); node1.removeChildren(); sWriter.write("Contents of Node1\n"); node1.printNode(sWriter); sWriter.write('\n'); sWriter.write("Contents of Node2\n"); node2.printNode(sWriter); sWriter.write('\n'); sWriter.write("Contents of Node3\n"); node3.printNode(sWriter); sWriter.write('\n'); System.out.println( sWriter.toString() ); } catch(Exception e) { e.printStackTrace(); } } }
// Little Color Management System // a copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // and/or sell copies of the Software, and to permit persons to whom the Software // is furnished to do so, subject to the following conditions: // all copies or substantial portions of the Software. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #include "lcms2_internal.h" // Read tags using low-level functions, provides necessary glue code to adapt versions, etc. // LUT tags static const cmsTagSignature Device2PCS16[] = {cmsSigAToB0Tag, // Perceptual cmsSigAToB1Tag, // Relative colorimetric cmsSigAToB2Tag, // Saturation cmsSigAToB1Tag }; // Absolute colorimetric static const cmsTagSignature Device2PCSFloat[] = {cmsSigDToB0Tag, // Perceptual cmsSigDToB1Tag, // Relative colorimetric cmsSigDToB2Tag, // Saturation cmsSigDToB3Tag }; // Absolute colorimetric static const cmsTagSignature PCS2Device16[] = {cmsSigBToA0Tag, // Perceptual cmsSigBToA1Tag, // Relative colorimetric cmsSigBToA2Tag, // Saturation cmsSigBToA1Tag }; // Absolute colorimetric static const cmsTagSignature PCS2DeviceFloat[] = {cmsSigBToD0Tag, // Perceptual cmsSigBToD1Tag, // Relative colorimetric cmsSigBToD2Tag, // Saturation cmsSigBToD3Tag }; // Absolute colorimetric // Factors to convert from 1.15 fixed point to 0..1.0 range and vice-versa #define InpAdj (1.0/MAX_ENCODEABLE_XYZ) // (65536.0/(65535.0*2.0)) #define OutpAdj (MAX_ENCODEABLE_XYZ) // ((2.0*65535.0)/65536.0) // Several resources for gray conversions. static const cmsFloat64Number GrayInputMatrix[] = { (InpAdj*cmsD50X), (InpAdj*cmsD50Y), (InpAdj*cmsD50Z) }; static const cmsFloat64Number <API key>[] = { 1, 1, 1 }; static const cmsFloat64Number PickYMatrix[] = { 0, (OutpAdj*cmsD50Y), 0 }; static const cmsFloat64Number PickLstarMatrix[] = { 1, 0, 0 }; // Get a media white point fixing some issues found in certain old profiles cmsBool <API key>(cmsCIEXYZ* Dest, cmsHPROFILE hProfile) { cmsCIEXYZ* Tag; _cmsAssert(Dest != NULL); Tag = (cmsCIEXYZ*) cmsReadTag(hProfile, <API key>); // If no wp, take D50 if (Tag == NULL) { *Dest = *cmsD50_XYZ(); return TRUE; } // V2 display profiles should give D50 if (<API key>(hProfile) < 0x4000000) { if (cmsGetDeviceClass(hProfile) == cmsSigDisplayClass) { *Dest = *cmsD50_XYZ(); return TRUE; } } // All seems ok *Dest = *Tag; return TRUE; } // Chromatic adaptation matrix. Fix some issues as well cmsBool _cmsReadCHAD(cmsMAT3* Dest, cmsHPROFILE hProfile) { cmsMAT3* Tag; _cmsAssert(Dest != NULL); Tag = (cmsMAT3*) cmsReadTag(hProfile, <API key>); if (Tag != NULL) { *Dest = *Tag; return TRUE; } // No CHAD available, default it to identity _cmsMAT3identity(Dest); // V2 display profiles should give D50 if (<API key>(hProfile) < 0x4000000) { if (cmsGetDeviceClass(hProfile) == cmsSigDisplayClass) { cmsCIEXYZ* White = (cmsCIEXYZ*) cmsReadTag(hProfile, <API key>); if (White == NULL) { _cmsMAT3identity(Dest); return TRUE; } return <API key>(Dest, NULL, White, cmsD50_XYZ()); } } return TRUE; } // Auxiliar, read colorants as a MAT3 structure. Used by any function that needs a matrix-shaper static cmsBool <API key>(cmsMAT3* r, cmsHPROFILE hProfile) { cmsCIEXYZ *PtrRed, *PtrGreen, *PtrBlue; _cmsAssert(r != NULL); PtrRed = (cmsCIEXYZ *) cmsReadTag(hProfile, <API key>); PtrGreen = (cmsCIEXYZ *) cmsReadTag(hProfile, <API key>); PtrBlue = (cmsCIEXYZ *) cmsReadTag(hProfile, <API key>); if (PtrRed == NULL || PtrGreen == NULL || PtrBlue == NULL) return FALSE; _cmsVEC3init(&r -> v[0], PtrRed -> X, PtrGreen -> X, PtrBlue -> X); _cmsVEC3init(&r -> v[1], PtrRed -> Y, PtrGreen -> Y, PtrBlue -> Y); _cmsVEC3init(&r -> v[2], PtrRed -> Z, PtrGreen -> Z, PtrBlue -> Z); return TRUE; } // Gray input pipeline static cmsPipeline* <API key>(cmsHPROFILE hProfile) { cmsToneCurve *GrayTRC; cmsPipeline* Lut; cmsContext ContextID = <API key>(hProfile); GrayTRC = (cmsToneCurve *) cmsReadTag(hProfile, cmsSigGrayTRCTag); if (GrayTRC == NULL) return NULL; Lut = cmsPipelineAlloc(ContextID, 1, 3); if (Lut == NULL) return NULL; if (cmsGetPCS(hProfile) == cmsSigLabData) { // In this case we implement the profile as an identity matrix plus 3 tone curves cmsUInt16Number Zero[2] = { 0x8080, 0x8080 }; cmsToneCurve* EmptyTab; cmsToneCurve* LabCurves[3]; EmptyTab = <API key>(ContextID, 2, Zero); if (EmptyTab == NULL) { cmsPipelineFree(Lut); return NULL; } LabCurves[0] = GrayTRC; LabCurves[1] = EmptyTab; LabCurves[2] = EmptyTab; <API key>(Lut, cmsAT_END, cmsStageAllocMatrix(ContextID, 3, 1, <API key>, NULL)); <API key>(Lut, cmsAT_END, <API key>(ContextID, 3, LabCurves)); cmsFreeToneCurve(EmptyTab); } else { <API key>(Lut, cmsAT_END, <API key>(ContextID, 1, &GrayTRC)); <API key>(Lut, cmsAT_END, cmsStageAllocMatrix(ContextID, 3, 1, GrayInputMatrix, NULL)); } return Lut; } // RGB Matrix shaper static cmsPipeline* <API key>(cmsHPROFILE hProfile) { cmsPipeline* Lut; cmsMAT3 Mat; cmsToneCurve *Shapes[3]; cmsContext ContextID = <API key>(hProfile); int i, j; if (!<API key>(&Mat, hProfile)) return NULL; // XYZ PCS in encoded in 1.15 format, and the matrix output comes in 0..0xffff range, so // we need to adjust the output by a factor of (0x10000/0xffff) to put data in // a 1.16 range, and then a >> 1 to obtain 1.15. The total factor is (65536.0)/(65535.0*2) for (i=0; i < 3; i++) for (j=0; j < 3; j++) Mat.v[i].n[j] *= InpAdj; Shapes[0] = (cmsToneCurve *) cmsReadTag(hProfile, cmsSigRedTRCTag); Shapes[1] = (cmsToneCurve *) cmsReadTag(hProfile, cmsSigGreenTRCTag); Shapes[2] = (cmsToneCurve *) cmsReadTag(hProfile, cmsSigBlueTRCTag); if (!Shapes[0] || !Shapes[1] || !Shapes[2]) return NULL; Lut = cmsPipelineAlloc(ContextID, 3, 3); if (Lut != NULL) { <API key>(Lut, cmsAT_END, <API key>(ContextID, 3, Shapes)); <API key>(Lut, cmsAT_END, cmsStageAllocMatrix(ContextID, 3, 3, (cmsFloat64Number*) &Mat, NULL)); } return Lut; } // Read the DToAX tag, adjusting the encoding of Lab or XYZ if neded static cmsPipeline* <API key>(cmsHPROFILE hProfile, cmsTagSignature tagFloat) { cmsContext ContextID = <API key>(hProfile); cmsPipeline* Lut = cmsPipelineDup((cmsPipeline*) cmsReadTag(hProfile, tagFloat)); <API key> spc = cmsGetColorSpace(hProfile); if (Lut == NULL) return NULL; // If PCS is Lab or XYZ, the floating point tag is accepting data in the space encoding, // and since the formatter has already accomodated to 0..1.0, we should undo this change if ( spc == cmsSigLabData) { <API key>(Lut, cmsAT_END, <API key>(ContextID)); } else if (spc == cmsSigXYZData) { <API key>(Lut, cmsAT_END, <API key>(ContextID)); } return Lut; } // Read and create a BRAND NEW MPE LUT from a given profile. All stuff dependent of version, etc // is adjusted here in order to create a LUT that takes care of all those details cmsPipeline* _cmsReadInputLUT(cmsHPROFILE hProfile, int Intent) { cmsTagTypeSignature OriginalType; cmsTagSignature tag16 = Device2PCS16[Intent]; cmsTagSignature tagFloat = Device2PCSFloat[Intent]; cmsContext ContextID = <API key>(hProfile); // On named color, take the appropiate tag if (cmsGetDeviceClass(hProfile) == <API key>) { cmsPipeline* Lut; cmsNAMEDCOLORLIST* nc = (cmsNAMEDCOLORLIST*) cmsReadTag(hProfile, <API key>); if (nc == NULL) return NULL; Lut = cmsPipelineAlloc(ContextID, 0, 0); if (Lut == NULL) { <API key>(nc); return NULL; } <API key>(Lut, cmsAT_BEGIN, <API key>(nc, TRUE)); <API key>(Lut, cmsAT_END, <API key>(ContextID)); return Lut; } if (cmsIsTag(hProfile, tagFloat)) { // Float tag takes precedence // Floating point LUT are always V4, but the encoding range is no // longer 0..1.0, so we need to add an stage depending on the color space return <API key>(hProfile, tagFloat); } // Revert to perceptual if no tag is found if (!cmsIsTag(hProfile, tag16)) { tag16 = Device2PCS16[0]; } if (cmsIsTag(hProfile, tag16)) { // Is there any LUT-Based table? // Check profile version and LUT type. Do the necessary adjustments if needed // First read the tag cmsPipeline* Lut = (cmsPipeline*) cmsReadTag(hProfile, tag16); if (Lut == NULL) return NULL; // After reading it, we have now info about the original type OriginalType = _cmsGetTagTrueType(hProfile, tag16); // The profile owns the Lut, so we need to copy it Lut = cmsPipelineDup(Lut); // We need to adjust data only for Lab16 on output if (OriginalType != cmsSigLut16Type || cmsGetPCS(hProfile) != cmsSigLabData) return Lut; // If the input is Lab, add also a conversion at the begin if (cmsGetColorSpace(hProfile) == cmsSigLabData) <API key>(Lut, cmsAT_BEGIN, <API key>(ContextID)); // Add a matrix for conversion V2 to V4 Lab PCS <API key>(Lut, cmsAT_END, <API key>(ContextID)); return Lut; } // Lut was not found, try to create a matrix-shaper // Check if this is a grayscale profile. if (cmsGetColorSpace(hProfile) == cmsSigGrayData) { // if so, build appropiate conversion tables. // The tables are the PCS iluminant, scaled across GrayTRC return <API key>(hProfile); } // Not gray, create a normal matrix-shaper return <API key>(hProfile); } // Gray output pipeline. // XYZ -> Gray or Lab -> Gray. Since we only know the GrayTRC, we need to do some assumptions. Gray component will be // given by Y on XYZ PCS and by L* on Lab PCS, Both across inverse TRC curve. // The complete pipeline on XYZ is Matrix[3:1] -> Tone curve and in Lab Matrix[3:1] -> Tone Curve as well. static cmsPipeline* <API key>(cmsHPROFILE hProfile) { cmsToneCurve *GrayTRC, *RevGrayTRC; cmsPipeline* Lut; cmsContext ContextID = <API key>(hProfile); GrayTRC = (cmsToneCurve *) cmsReadTag(hProfile, cmsSigGrayTRCTag); if (GrayTRC == NULL) return NULL; RevGrayTRC = cmsReverseToneCurve(GrayTRC); if (RevGrayTRC == NULL) return NULL; Lut = cmsPipelineAlloc(ContextID, 3, 1); if (Lut == NULL) { cmsFreeToneCurve(RevGrayTRC); return NULL; } if (cmsGetPCS(hProfile) == cmsSigLabData) { <API key>(Lut, cmsAT_END, cmsStageAllocMatrix(ContextID, 1, 3, PickLstarMatrix, NULL)); } else { <API key>(Lut, cmsAT_END, cmsStageAllocMatrix(ContextID, 1, 3, PickYMatrix, NULL)); } <API key>(Lut, cmsAT_END, <API key>(ContextID, 1, &RevGrayTRC)); cmsFreeToneCurve(RevGrayTRC); return Lut; } static cmsPipeline* <API key>(cmsHPROFILE hProfile) { cmsPipeline* Lut; cmsToneCurve *Shapes[3], *InvShapes[3]; cmsMAT3 Mat, Inv; int i, j; cmsContext ContextID = <API key>(hProfile); if (!<API key>(&Mat, hProfile)) return NULL; if (!_cmsMAT3inverse(&Mat, &Inv)) return NULL; // XYZ PCS in encoded in 1.15 format, and the matrix input should come in 0..0xffff range, so // we need to adjust the input by a << 1 to obtain a 1.16 fixed and then by a factor of // (0xffff/0x10000) to put data in 0..0xffff range. Total factor is (2.0*65535.0)/65536.0; for (i=0; i < 3; i++) for (j=0; j < 3; j++) Inv.v[i].n[j] *= OutpAdj; Shapes[0] = (cmsToneCurve *) cmsReadTag(hProfile, cmsSigRedTRCTag); Shapes[1] = (cmsToneCurve *) cmsReadTag(hProfile, cmsSigGreenTRCTag); Shapes[2] = (cmsToneCurve *) cmsReadTag(hProfile, cmsSigBlueTRCTag); if (!Shapes[0] || !Shapes[1] || !Shapes[2]) return NULL; InvShapes[0] = cmsReverseToneCurve(Shapes[0]); InvShapes[1] = cmsReverseToneCurve(Shapes[1]); InvShapes[2] = cmsReverseToneCurve(Shapes[2]); if (!InvShapes[0] || !InvShapes[1] || !InvShapes[2]) { return NULL; } Lut = cmsPipelineAlloc(ContextID, 3, 3); if (Lut != NULL) { <API key>(Lut, cmsAT_END, cmsStageAllocMatrix(ContextID, 3, 3, (cmsFloat64Number*) &Inv, NULL)); <API key>(Lut, cmsAT_END, <API key>(ContextID, 3, InvShapes)); } <API key>(InvShapes); return Lut; } // Change CLUT interpolation to trilinear static void <API key>(cmsPipeline* Lut) { cmsStage* Stage; for (Stage = <API key>(Lut); Stage != NULL; Stage = cmsStageNext(Stage)) { if (cmsStageType(Stage) == cmsSigCLutElemType) { _cmsStageCLutData* CLUT = (_cmsStageCLutData*) Stage ->Data; CLUT ->Params->dwFlags |= <API key>; <API key>(CLUT ->Params); } } } // Read the DToAX tag, adjusting the encoding of Lab or XYZ if neded static cmsPipeline* <API key>(cmsHPROFILE hProfile, cmsTagSignature tagFloat) { cmsContext ContextID = <API key>(hProfile); cmsPipeline* Lut = cmsPipelineDup((cmsPipeline*) cmsReadTag(hProfile, tagFloat)); <API key> PCS = cmsGetPCS(hProfile); if (Lut == NULL) return NULL; // If PCS is Lab or XYZ, the floating point tag is accepting data in the space encoding, // and since the formatter has already accomodated to 0..1.0, we should undo this change if ( PCS == cmsSigLabData) { <API key>(Lut, cmsAT_BEGIN, <API key>(ContextID)); } else if (PCS == cmsSigXYZData) { <API key>(Lut, cmsAT_BEGIN, <API key>(ContextID)); } return Lut; } // Create an output MPE LUT from agiven profile. Version mismatches are handled here cmsPipeline* _cmsReadOutputLUT(cmsHPROFILE hProfile, int Intent) { cmsTagTypeSignature OriginalType; cmsTagSignature tag16 = PCS2Device16[Intent]; cmsTagSignature tagFloat = PCS2DeviceFloat[Intent]; cmsContext ContextID = <API key>(hProfile); if (cmsIsTag(hProfile, tagFloat)) { // Float tag takes precedence // Floating point LUT are always V4 return <API key>(hProfile, tagFloat); } // Revert to perceptual if no tag is found if (!cmsIsTag(hProfile, tag16)) { tag16 = PCS2Device16[0]; } if (cmsIsTag(hProfile, tag16)) { // Is there any LUT-Based table? // Check profile version and LUT type. Do the necessary adjustments if needed // First read the tag cmsPipeline* Lut = (cmsPipeline*) cmsReadTag(hProfile, tag16); if (Lut == NULL) return NULL; // After reading it, we have info about the original type OriginalType = _cmsGetTagTrueType(hProfile, tag16); // The profile owns the Lut, so we need to copy it Lut = cmsPipelineDup(Lut); if (Lut == NULL) return NULL; // Now it is time for a controversial stuff. I found that for 3D LUTS using // Lab used as indexer space, trilinear interpolation should be used if (cmsGetPCS(hProfile) == cmsSigLabData) <API key>(Lut); // We need to adjust data only for Lab and Lut16 type if (OriginalType != cmsSigLut16Type || cmsGetPCS(hProfile) != cmsSigLabData) return Lut; // Add a matrix for conversion V4 to V2 Lab PCS <API key>(Lut, cmsAT_BEGIN, <API key>(ContextID)); // If the output is Lab, add also a conversion at the end if (cmsGetColorSpace(hProfile) == cmsSigLabData) <API key>(Lut, cmsAT_END, <API key>(ContextID)); return Lut; } // Lut not found, try to create a matrix-shaper // Check if this is a grayscale profile. if (cmsGetColorSpace(hProfile) == cmsSigGrayData) { // if so, build appropiate conversion tables. // The tables are the PCS iluminant, scaled across GrayTRC return <API key>(hProfile); } // Not gray, create a normal matrix-shaper return <API key>(hProfile); } // Read the AToD0 tag, adjusting the encoding of Lab or XYZ if neded static cmsPipeline* <API key>(cmsHPROFILE hProfile, cmsTagSignature tagFloat) { cmsContext ContextID = <API key>(hProfile); cmsPipeline* Lut = cmsPipelineDup((cmsPipeline*) cmsReadTag(hProfile, tagFloat)); <API key> PCS = cmsGetPCS(hProfile); <API key> spc = cmsGetColorSpace(hProfile); if (Lut == NULL) return NULL; if (spc == cmsSigLabData) { <API key>(Lut, cmsAT_BEGIN, <API key>(ContextID)); } else if (spc == cmsSigXYZData) { <API key>(Lut, cmsAT_BEGIN, <API key>(ContextID)); } if (PCS == cmsSigLabData) { <API key>(Lut, cmsAT_END, <API key>(ContextID)); } else if (PCS == cmsSigXYZData) { <API key>(Lut, cmsAT_END, <API key>(ContextID)); } return Lut; } // This one includes abstract profiles as well. Matrix-shaper cannot be obtained on that device class. The // tag name here may default to AToB0 cmsPipeline* <API key>(cmsHPROFILE hProfile, int Intent) { cmsPipeline* Lut; cmsTagTypeSignature OriginalType; cmsTagSignature tag16 = Device2PCS16[Intent]; cmsTagSignature tagFloat = Device2PCSFloat[Intent]; cmsContext ContextID = <API key>(hProfile); // On named color, take the appropiate tag if (cmsGetDeviceClass(hProfile) == <API key>) { cmsNAMEDCOLORLIST* nc = (cmsNAMEDCOLORLIST*) cmsReadTag(hProfile, <API key>); if (nc == NULL) return NULL; Lut = cmsPipelineAlloc(ContextID, 0, 0); if (Lut == NULL) { <API key>(nc); return NULL; } <API key>(Lut, cmsAT_BEGIN, <API key>(nc, FALSE)); if (cmsGetColorSpace(hProfile) == cmsSigLabData) <API key>(Lut, cmsAT_END, <API key>(ContextID)); return Lut; } if (cmsIsTag(hProfile, tagFloat)) { // Float tag takes precedence // Floating point LUT are always V return <API key>(hProfile, tagFloat); } tagFloat = Device2PCSFloat[0]; if (cmsIsTag(hProfile, tagFloat)) { return cmsPipelineDup((cmsPipeline*) cmsReadTag(hProfile, tagFloat)); } if (!cmsIsTag(hProfile, tag16)) { // Is there any LUT-Based table? tag16 = Device2PCS16[0]; if (!cmsIsTag(hProfile, tag16)) return NULL; } // Check profile version and LUT type. Do the necessary adjustments if needed // Read the tag Lut = (cmsPipeline*) cmsReadTag(hProfile, tag16); if (Lut == NULL) return NULL; // The profile owns the Lut, so we need to copy it Lut = cmsPipelineDup(Lut); if (Lut == NULL) return NULL; // Now it is time for a controversial stuff. I found that for 3D LUTS using // Lab used as indexer space, trilinear interpolation should be used if (cmsGetColorSpace(hProfile) == cmsSigLabData) <API key>(Lut); // After reading it, we have info about the original type OriginalType = _cmsGetTagTrueType(hProfile, tag16); // We need to adjust data for Lab16 on output if (OriginalType != cmsSigLut16Type) return Lut; // Here it is possible to get Lab on both sides if (cmsGetPCS(hProfile) == cmsSigLabData) { <API key>(Lut, cmsAT_BEGIN, <API key>(ContextID)); } if (cmsGetColorSpace(hProfile) == cmsSigLabData) { <API key>(Lut, cmsAT_END, <API key>(ContextID)); } return Lut; } // Returns TRUE if the profile is implemented as matrix-shaper cmsBool CMSEXPORT cmsIsMatrixShaper(cmsHPROFILE hProfile) { switch (cmsGetColorSpace(hProfile)) { case cmsSigGrayData: return cmsIsTag(hProfile, cmsSigGrayTRCTag); case cmsSigRgbData: return (cmsIsTag(hProfile, <API key>) && cmsIsTag(hProfile, <API key>) && cmsIsTag(hProfile, <API key>) && cmsIsTag(hProfile, cmsSigRedTRCTag) && cmsIsTag(hProfile, cmsSigGreenTRCTag) && cmsIsTag(hProfile, cmsSigBlueTRCTag)); default: return FALSE; } } // Returns TRUE if the intent is implemented as CLUT cmsBool CMSEXPORT cmsIsCLUT(cmsHPROFILE hProfile, cmsUInt32Number Intent, cmsUInt32Number UsedDirection) { const cmsTagSignature* TagTable; // For devicelinks, the supported intent is that one stated in the header if (cmsGetDeviceClass(hProfile) == cmsSigLinkClass) { return (<API key>(hProfile) == Intent); } switch (UsedDirection) { case LCMS_USED_AS_INPUT: TagTable = Device2PCS16; break; case LCMS_USED_AS_OUTPUT:TagTable = PCS2Device16; break; // For proofing, we need rel. colorimetric in output. Let's do some recursion case LCMS_USED_AS_PROOF: return <API key>(hProfile, Intent, LCMS_USED_AS_INPUT) && <API key>(hProfile, <API key>, LCMS_USED_AS_OUTPUT); default: cmsSignalError(<API key>(hProfile), cmsERROR_RANGE, "Unexpected direction (%d)", UsedDirection); return FALSE; } return cmsIsTag(hProfile, TagTable[Intent]); } // Return info about supported intents cmsBool CMSEXPORT <API key>(cmsHPROFILE hProfile, cmsUInt32Number Intent, cmsUInt32Number UsedDirection) { if (cmsIsCLUT(hProfile, Intent, UsedDirection)) return TRUE; // Is there any matrix-shaper? If so, the intent is supported. This is a bit odd, since V2 matrix shaper // does not fully support relative colorimetric because they cannot deal with non-zero black points, but // many profiles claims that, and this is certainly not true for V4 profiles. Lets answer "yes" no matter // the accuracy would be less than optimal in rel.col and v2 case. return cmsIsMatrixShaper(hProfile); } // Read both, profile sequence description and profile sequence id if present. Then combine both to // create qa unique structure holding both. Shame on ICC to store things in such complicated way. cmsSEQ* <API key>(cmsHPROFILE hProfile) { cmsSEQ* ProfileSeq; cmsSEQ* ProfileId; cmsSEQ* NewSeq; cmsUInt32Number i; // Take profile sequence description first ProfileSeq = (cmsSEQ*) cmsReadTag(hProfile, <API key>); // Take profile sequence ID ProfileId = (cmsSEQ*) cmsReadTag(hProfile, <API key>); if (ProfileSeq == NULL && ProfileId == NULL) return NULL; if (ProfileSeq == NULL) return <API key>(ProfileId); if (ProfileId == NULL) return <API key>(ProfileSeq); // We have to mix both together. For that they must agree if (ProfileSeq ->n != ProfileId ->n) return <API key>(ProfileSeq); NewSeq = <API key>(ProfileSeq); // Ok, proceed to the mixing if (NewSeq != NULL) { for (i=0; i < ProfileSeq ->n; i++) { memmove(&NewSeq ->seq[i].ProfileID, &ProfileId ->seq[i].ProfileID, sizeof(cmsProfileID)); NewSeq ->seq[i].Description = cmsMLUdup(ProfileId ->seq[i].Description); } } return NewSeq; } // Dump the contents of profile sequence in both tags (if v4 available) cmsBool <API key>(cmsHPROFILE hProfile, const cmsSEQ* seq) { if (!cmsWriteTag(hProfile, <API key>, seq)) return FALSE; if (<API key>(hProfile) >= 4.0) { if (!cmsWriteTag(hProfile, <API key>, seq)) return FALSE; } return TRUE; } // Auxiliar, read and duplicate a MLU if found. static cmsMLU* GetMLUFromProfile(cmsHPROFILE h, cmsTagSignature sig) { cmsMLU* mlu = (cmsMLU*) cmsReadTag(h, sig); if (mlu == NULL) return NULL; return cmsMLUdup(mlu); } // Create a sequence description out of an array of profiles cmsSEQ* <API key>(cmsContext ContextID, cmsUInt32Number nProfiles, cmsHPROFILE hProfiles[]) { cmsUInt32Number i; cmsSEQ* seq = <API key>(ContextID, nProfiles); if (seq == NULL) return NULL; for (i=0; i < nProfiles; i++) { cmsPSEQDESC* ps = &seq ->seq[i]; cmsHPROFILE h = hProfiles[i]; <API key>* techpt; <API key>(h, &ps ->attributes); <API key>(h, ps ->ProfileID.ID8); ps ->deviceMfg = <API key>(h); ps ->deviceModel = cmsGetHeaderModel(h); techpt = (<API key>*) cmsReadTag(h, cmsSigTechnologyTag); if (techpt == NULL) ps ->technology = (<API key>) 0; else ps ->technology = *techpt; ps ->Manufacturer = GetMLUFromProfile(h, <API key>); ps ->Model = GetMLUFromProfile(h, <API key>); ps ->Description = GetMLUFromProfile(h, <API key>); } return seq; } static const cmsMLU* GetInfo(cmsHPROFILE hProfile, cmsInfoType Info) { cmsTagSignature sig; switch (Info) { case cmsInfoDescription: sig = <API key>; break; case cmsInfoManufacturer: sig = <API key>; break; case cmsInfoModel: sig = <API key>; break; case cmsInfoCopyright: sig = cmsSigCopyrightTag; break; default: return NULL; } return (cmsMLU*) cmsReadTag(hProfile, sig); } cmsUInt32Number CMSEXPORT cmsGetProfileInfo(cmsHPROFILE hProfile, cmsInfoType Info, const char LanguageCode[3], const char CountryCode[3], wchar_t* Buffer, cmsUInt32Number BufferSize) { const cmsMLU* mlu = GetInfo(hProfile, Info); if (mlu == NULL) return 0; return cmsMLUgetWide(mlu, LanguageCode, CountryCode, Buffer, BufferSize); } cmsUInt32Number CMSEXPORT <API key>(cmsHPROFILE hProfile, cmsInfoType Info, const char LanguageCode[3], const char CountryCode[3], char* Buffer, cmsUInt32Number BufferSize) { const cmsMLU* mlu = GetInfo(hProfile, Info); if (mlu == NULL) return 0; return cmsMLUgetASCII(mlu, LanguageCode, CountryCode, Buffer, BufferSize); }
import serial import time ser = serial.Serial( port = "/dev/ttyACM0", baudrate = 9600, bytesize = serial.EIGHTBITS ) time.sleep(2) ser.write("\x36\x20\x00") print(hex(ord(ser.read(1)))) print(hex(ord(ser.read(1)))) print(hex(ord(ser.read(1)))) print(hex(ord(ser.read(1)))) print(hex(ord(ser.read(1)))) print(hex(ord(ser.read(1)))) print(hex(ord(ser.read(1)))) print(hex(ord(ser.read(1)))) print(hex(ord(ser.read(1)))) print(hex(ord(ser.read(1)))) print(hex(ord(ser.read(1)))) print(hex(ord(ser.read(1)))) print(hex(ord(ser.read(1))))
<?php // This is a SPIP language file -- Ceci est un fichier langue de SPIP // ** ne pas modifier le fichier ** if (!defined('_ECRIRE_INC_VERSION')) { return; } $GLOBALS[$GLOBALS['idx_lang']] = array( 'action_patienter' => 'اقدام‌هاي در دست انجام. لطفاً صبر كنيد...', 'actions_a_faire' => 'اقدام‌هايي براي انجام دادن', 'actions_demandees' => 'اقدام‌هاي درخواست شده:', 'actions_en_erreur' => 'خطاهاي سرور', 'actions_necessaires' => 'اقدام‌هاي تكميلي زير انچام خواهد شد: ', '<API key>' => 'اقدام‌هاي انجام نشده ', 'actions_realises' => 'اقدام‌هاي انجام شده ', '<API key>' => 'نمايش پلاگين‌هاي ناسازگار', 'bouton_activer' => 'فعال سازي ', 'bouton_actualiser' => 'عملي سازي', '<API key>' => 'عملي سازي مخازن', 'bouton_appliquer' => 'كاربرد', 'bouton_confirmer' => 'تأييد', 'bouton_desactiver' => 'غيرفعال‌سازي', 'bouton_desinstaller' => 'نصب زدايي', 'bouton_installer' => 'بارگذاري و فعال‌سازي ', '<API key>' => 'اصلاح مخزن', 'bouton_supprimer' => 'حذف ', 'bouton_up' => 'به هنگام سازي ', '<API key>' => 'فعال سازي پاكت‌هاي مخزن', '<API key>' => 'فعال سازي پاكت‌هاي تمام مخزن‌ها', '<API key>' => 'مفاد پرونده‌ي ايكس.ام.ال پلاگين', '<API key>' => 'افزودن مخزن SPIP-Zone', 'bulle_aller_depot' => 'برو به صفحه‌ي اين مخزن ', '<API key>' => 'برو به صفحه‌ي مستندسازي ', 'bulle_aller_plugin' => 'برو به صفحه‌ي پلاگين', '<API key>' => 'حذف مخزن و پاكت‌هاي آن', '<API key>' => 'بارگذاري آرشيو', '<API key>' => 'بارگذاري پرونده ايكس.ام.ال مخزن', '<API key>' => 'بارگذاري آرشيو', '<API key>' => 'پنهان ساختن پلاگين‌هاي ناسازگار ', 'categorie_aucune' => 'بدون مقوله', 'categorie_auteur' => 'تأييد، نويسنده، اختيار', '<API key>' => 'ارتباط، تعامل، پيك', 'categorie_date' => 'يادداشت‌ها، تقويم، تاريخ', 'categorie_divers' => 'چيزهاي نو، خدمات داخلي', 'categorie_edition' => 'نشر، پرينت، نگارش', '<API key>' => 'پيكربندي، نگهداري', '<API key>' => 'تصويرها، گالري، چندرسانه', '<API key>' => 'ناوبري، جستجو، سازماندهي', 'categorie_outil' => 'ابزار توسعه', '<API key>' => 'بهينه سازي، عملكرد، امنيت', 'categorie_squelette' => 'اسكلت', '<API key>' => 'ارجاع، آمارها', 'categorie_theme' => 'تم ', '<API key>' => 'فعال‌سازي ثبت‌هاي طولاني؟', '<API key>' => 'اين گزينه‌ ثبت‌ اس.وي.پي را بسيار طولاني مي‌سازد...', '<API key>' => 'فعال سازي حالت گام به گام؟', '<API key>' => 'فعال‌سازي اين حالت يك بيلان را بعد از هر اقدام انجام شده نشان خواهد داد، به جاي آنكه فقط يك بيلان كلي از تمام اقدام‌هاي انجام شده در پايان پروسه داشته باشيد. ', '<API key>' => 'فعال سازي حالت زمان اجرا؟ ', '<API key>' => 'حالت زمان‌اجرا (بله) فقط پلاگين‌هاي غيرفعال سازگار با نسخه‌ي فعالي اسپيپ شما را بارگذاري مي‌كند، كه براي بيشتر استفاده‌ها به شدت توصيه مي‌شود. در حالت غير زمان اجرا (نه)، تمام پلاگين‌هاي يك مخزن بارگذاري مي‌شوند، بي‌توجه به اينكه نسخه‌ي اسپيپ چه باشد. اين حالت فقط هنگامي مفيد است كه اس.وي.پي براي ارايه‌ي تمام پلاگين‌هاي موجود مورد استفاده قرار بگيرد آنطور كه اسپيپ مي‌كند (plugins.spip.net) ', '<API key>' => 'اجازه‌ي فعال‌ سازي پاكت‌هاي كهنه؟', '<API key>' => 'پاكت‌هاي (بسته‌هاي) كهنه پاكت‌هاي محلي هستند كه قديمي‌تر از ساير پاكت‌هاي قديمي هستند. كهنگي بر مبناي وضعيت پاكت‌ها (استقرار، آزمون، توسعه) و بر مبناي نسخه تعيين مي‌شود. اگر هنوز مايليد اين پلاگين‌هاي تاريخ گذشته را فعال كنيد اين گزينه را توانا سازيد. ', '<API key>' => 'اجازه‌ي ويرايش سپرده‌ها؟', '<API key>' => 'اين اطلاعات ذخيره را ويرايش‌پذير مي‌سازد و همچنين به آن‌ها اجازه مي‌هد تا به كليد واژه‌ها يا سندها وصل شوند. اين گزينه نبايد مورد علاقه كسي باشد! بهتر است بگذاريد «نه» باشد!', '<API key>' => 'اين پلاگين در پوشه‌ي (@dir@)كه فعلاً موجود است بارگذاري خواهد شد. اين كار مطلب آن پوشه را از بين خواهد برد. يك كپي از مطلب قديمي در «@dir_backup@» ذخيره خواهد شد. شما بايد اين عمل را تأييد كنيد. ', '<API key>' => 'بعضي از اقدام‌ها انجام نشده است. اين مي‌تواند ناشي از بروز خطا،حين پردازش آن اقدام‌ها، يا ناشي از نمايش اين صفحه هنگامي كه آن اقدام‌ها در دست پردازش بوده‌اند، باشد. اقدام‌ها به وسيله‌ي @auteur@در تاريخ @date@شروع شده‌اند. ', '<API key>' => 'پوشه‌ي آرشيو‌هاي @dir@ قابل نوشتن نيستب. بارگذاري يك آرشيو ممكن نيست. ', '<API key>' => 'پوشه‌ي _DIR_LIB تعريف نشده. بارگذاري يك آرشيو ممكن نيست.', '<API key>' => 'پوشه‌ي «plugins/auto» كه اجازه‌ي بارگذاري پاكت‌ها را مي‌دهد ايجاد نشده يا در دسترس نوشتن نيست. <strong>براي آنكه بتوانيد پلاگين‌هاي جديد را از طريق اين واسطه بارگذاري كنيد بايد آن پوشه را بسازيد.</strong>', '<API key>' => 'پوشه‌ي پاكت‌هاي @dir@ قابل نوشتن نيست. بارگذاري يك پاكت مقدور نيست.', '<API key>' => 'پوشيه‌ي _DIR_PLUGIN_AUTO تعريف نشده. جستجوي يك پاكت ممكن نيست. ', '<API key>' => '« plugins/auto »غيرقابل دسترس !', '<API key>' => 'بارگذاري اين منبع @source@ ممكن نيست', '<API key>' => 'پوشه‌ي @dir@ براي انتقال دردسترس نيست', '<API key>' => 'خالي كردن @fichier@ ممكن نيست', '<API key>' => ' فرمت @extension@ توسط انتقال دهنده پشتيباني نمي‌شود', '<API key>' => 'روش @methode@ براي انتقال ناشناخته است', '<API key>' => 'نوع پرونده‌‌ي ناشناخته براي منبع @source@', '<API key>' => 'اگر اين را پر نكنيد مسير با نام آرشيوي محاسبه خواهد شد. ', 'fieldset_debug' => 'خطازدايي', 'fieldset_edition' => 'ويرايش ', '<API key>' => 'روش كار', 'info_1_depot' => '1 مخزن', 'info_1_paquet' => '1 پاكت (بسته)', 'info_1_plugin' => '1 پلاگين', '<API key>' => 'اين صفحه پلاگين‌هاي غيرفعال را فهرست مي‌كند. اين پلاگين‌ها الزاماً قفل نشده‌اند. ', '<API key>' => 'اين صفحه پلاگين‌هاي غيرفعال سايت را فهرست مي‌كند. اين پلاگين‌ها الزاماً قفل نشده هستند. ', '<API key>' => 'اين صفحه تمام پلگين‌هاي فعال و قفل نشده‌ي سايت را فهرست مي‌كند. ', '<API key>' => 'اين صفحه تمام پلاگين‌هاي فعال سايت، قفل شده يا نشده را فهرست مي‌كند. ', '<API key>' => 'اين صفحه تمام پلاگين‌هاي قفل‌نشده‌ي سايت، فعال يا غيرفعال را فهرست مي‌كند. ', '<API key>' => 'اين صفحه تمام پلاگين‌هاي سايت را فهرست مي‌كند.', '<API key>' => 'اين صفحه پلاگين‌هاي فعال و قفل شده را فهرست مي‌كند (قرار گرفته در پوشه‌ي <code>@dir_plugins_dist@</code>). اگر مايليد آن‌ها را غيرفعال كنيد لطفاً با وب مستر سايت تماس بگيريد، يا به <a href="http://programmer.spip.org/<API key>">à la documentation</a> گزارش كنيد. ', # MODIF '<API key>' => 'SPIP-Zone - Plugins', 'info_ajouter_depot' => 'در جريان افزودن مخازن به پايگاه خود، امكان كسب اطلاعات و جستجو روي تمام پاكت‌هاي ذخيره شده به وسيله‌ي مخازن افزوده شده را خواهيد داشت. يك مخزن به وسيله‌ي يك پرونده‌ي ايكس.ام.ال نوشته شده كه شامل تمام اطلاعات در مورد مخزن و تمام پاكت‌هاي آن است. ‌ ', 'info_aucun_depot' => 'هيچ مخزن', '<API key>' => 'هيچ مخزني در دسترس نيست.<br /> از فرم زير براي افزودن مخزني «SPIP-Zone - Plugins»كه يو.آر.ال آن از پيش داده شده استفاده كنيد يا مخزن ديگري را انتخاب نماييد ', 'info_aucun_paquet' => 'هيچ پاكت', 'info_aucun_plugin' => 'هيچ پلاگين', '<API key>' => '<strong>اين صفحه انحصاراً در دسترس وب‌مستر‌هاي سايت قرار دارد.</strong><p>اين صفحه به شما اجازه خواهد داد تا پلاگين‌هاي قابل دسترس در مخازن ذخيره شده در پيكربندي خود را جستجو كنيد و آن‌ها به صورت فيزيكي روي سرور خود بارگذاري نماييد. </p> ', '<API key>' => '<strong>اين صفحه انحصاراً در دسترس وب مسترهاي سايت قرار دارد.</strong><p>اين صفحه اجازه‌ي افزودن و به هنگام سازي مخازن پلاگين‌ها را مي‌هد.</p>', 'info_charger_plugin' => 'براي افزودن يك يا چند پلاگين، پيشاپيش يك جستجوي چند معياره روي پلاگين‌هاي كهشكان اسپيپ انجام دهيد. اين جستجو فقط شامل پلاگين‌هاي سازگار با نسخه‌ي اسپيپ نصب شده است و پلاگين‌هاي جخ فعال شده روي اين سايت را گزارش مي‌دهد. ', '<API key>' => ' براي @compatibilite@:', '<API key>' => '@total_autres@ ساير كمك‌هاي پذيرش شده ', 'info_critere_phrase' => 'كليدواژه‌ها را باري جستجو در پيشوند،‌نام، شعار،‌ توصيف و پلاگين‌هاي ديگر تايپ كنيد ', '<API key>' => '@total_depots@ مخزن', 'info_fichier_depot' => 'يو.آر.ال پرونده‌ي توصيف مخزن را براي اضافه شدن تايپ كنيد. <br />براي افزودن مخزن "SPIP-Zone - Plugins" اين پيوند را كليك كنيد: ', 'info_nb_depots' => '@nb@ مخزن', 'info_nb_paquets' => '@nb@پاكت ', 'info_nb_plugins' => '@nb@ پلاگين', '<API key>' => '@total_paquets@ پاكت در دسترس', '<API key>' => 'وابسته‌هاي گم شده ', '<API key>' => 'نسخه‌ي ناسازگار ', '<API key>' => 'جخ نصب شده ', '<API key>' => 'نسخه‌ي كهنه', '<API key>' => '@total_plugins@ پلاگين در دسترس ', '<API key>' => '@total_plugins@ پلاگين پذيرش شده', 'info_tri_nom' => 'دسته بندي شده بر اساس الفبا', 'info_tri_score' => 'دسته‌بندي شده بر اساس كاهش تناسب آن‌ها', 'info_type_depot_git' => 'مخزن مديريت شده تحت جي.آي.تي', '<API key>' => 'مخزن مديريت شده با دست', 'info_type_depot_svn' => 'مخزن مديريت شده تحت اس.وي.ان', 'info_verrouille' => 'غيرفعال‌ سازي يا نصب زدايي اين پلاگين ممكن نيست', '<API key>' => 'اقدام‌هاي درخواستي در دست اجراست', '<API key>' => 'كمك ديگر', 'label_actualise_le' => 'فعال‌سازي شده', 'label_archive' => 'يو.آر.ال آرشيو', 'label_branches_spip' => 'سازگار', 'label_categorie' => 'مقوله', '<API key>' => 'سازگاري', '<API key>' => 'مقوله‌ها', 'label_critere_depot' => 'مخازن', '<API key>' => 'سازگاري', 'label_critere_etat' => 'حالت‌ها', '<API key>' => 'جستجو در پلاگين‌ها', 'label_destination' => 'مسير از پوشه‌ي «auto» كه پلاگين در آن ذخيره مي‌شود', 'label_modifie_le' => 'اصلاح ...', '<API key>' => 'كمك‌هاي ديگر', 'label_prefixe' => 'پيشوند', '<API key>' => 'انتخاب اين پلاگين', 'label_tags' => 'برچسب‌ها: ', 'label_type_depot' => 'نوع مخزن:', '<API key>' => 'مخزن تحت جي.آي.تي ', '<API key>' => 'مخزن دستي', '<API key>' => 'مخزن تحت اس.وي.ان ', 'label_url_archives' => 'يو.آر.ال بسته‌ي آرشيوها', 'label_url_brouteur' => 'يو.آر.ال ريشه منابع ', 'label_url_serveur' => 'يو.آر.ال سرور', 'label_version' => 'نسخه', 'label_xml_depot' => 'پرونده ايكس.ام.ال مخزن', 'label_xml_plugin' => 'ايكس.ام.ال', '<API key>' => 'نصب پلاگين‌ها', '<API key>' => 'جستجوي پلاگين‌ها', '<API key>' => 'پلاگين «@plugin@»(نسخه:@version@) نمي‌تواند به خوبي بارگذاري شود', '<API key>' => 'پلاگين «@plugin@» (نسخه:@version@) به خوبي بارگذاري شده ', '<API key>' => 'نصب آرشيو «@plugin@» نا موفق بوده ', '<API key>' => 'آرشيو «@plugin@» نصب شده ', '<API key>' => 'بارگذاري يا فعال‌سازي پلاگين «@plugin@» (نسخه:@version@) به خوبي انجام نشده', '<API key>' => 'بارگذاري و فعال‌سازي پلاگين «@plugin@»(نسخه:@version@) به خوبي انجام شده ', '<API key>' => 'نصب پلاگين «@plugin@» (نسخه: @version@) موفق نبوده ', '<API key>' => 'نصب پلاگين «@plugin@» (نسخه: @version@) به خوبي انجام شده', '<API key>' => 'پرونده‌هاي پلاگين «@plugin@» (نسخه: @version@) به خوبي حذف نشده‌اند', '<API key>' => 'پرونده‌هاي پلاگين «@plugin@» (نسخه: @version@) به خوبي حذف شده‌اند', '<API key>' => 'غيرفعال‌سازي پلاگين «@plugin@» (نسخه: @version@) به خوبي انجام نشده', '<API key>' => 'فعال سازي پلاگين «@plugin@»(نسخه: @version@) به خبوبي انچام شده ', '<API key>' => 'فعال سازي پلاگين «@plugin@» (نسخه: @version@) به خوبي انجام نشده', '<API key>' => 'فعال‌سازي پلاگين «@plugin@» (نسخه: @version@) به خوبي انجام شده ', '<API key>' => 'نصب زدايي پلاگين «@plugin@»(نسخه: @version@) به خوبي انجام نشده ', '<API key>' => 'نصب‌ زدايي پلاگين «@plugin@» (نسخه: @version@) به خوبي انجام شده', '<API key>' => 'به هنگام سازي پلاگين «@plugin@» (از نسخه‌ي: @version@ تا @version_maj@) به خوبي انجام نشده', '<API key>' => 'به هنگام سازي پلاگين «@plugin@» (از نسخه‌ي:@version@ تا @version_maj@) به خوبي انجام شده', '<API key>' => 'به هنگام سازي و فعال‌سازي پلاگين « @plugin@ » (از نسخه‌‌ي: de la version : @version@ تا @version_maj@) به خوبي انجام نشده ', '<API key>' => 'به هنگام‌سازي و فعال‌سازي پلاگين « @plugin@ » (از نسخه: @version@ تا @version_maj@) به خوبي انجام شده', 'message_action_get' => 'بارگذاري پلاگين «@plugin@» (نسخه: @version@)', '<API key>' => 'بارگذاري آرشيو « <a href="@version@" class="spip_out">@plugin@</a> »', '<API key>' => 'بارگذاري و فعال‌ساز پلاگين «@plugin@» (نسخه: @version@)', '<API key>' => 'پلاگين «@plugin@»(نسخه:@version@) نصب شد', 'message_action_kill' => 'حذف پرونده‌هاي پلاگين «@plugin@» (نسخه: @version@)', 'message_action_off' => 'غيرفعال‌سازي پلاگين «@plugin@» (نسخه:@version@)', 'message_action_on' => 'فعال‌سازي «@plugin@» (نسخه: @version@)', 'message_action_stop' => 'نصب زدايي پلاگين «@plugin@» (نسخه: @version@)', 'message_action_up' => 'به هنگام سازي پلاگين «@plugin@» (از نسخه @version@ تا @version_maj@)', 'message_action_upon' => 'به هنگام سازي و فعال سازي پلاگين «@plugin@»(نسخه:@version@)', '<API key>' => 'اين پلاگثن @plugin@ بستگي دارد به @dependance@.', '<API key>' => 'پلاگين @plugin@ بستگي به @dependance@ @version@دارد ', '<API key>' => 'هيچ پلاگيني انتخاب نشده.', '<API key>' => '@plugin@ مستلزم آن است كه آرشيو <a href="@lib_url@">@lib@</a> در پرونده‌ي <var>lib/</var> در ريشه‌ي سايت شما قرار بگيرد. با اين حال، اين پوشه غيرقابل نگارش است. شما بايد آن را به صورت دستي نصب كنيد يا مجوز نوشتن در آن پوشه را بدهيد. ', # MODIF '<API key>' => 'به هنگام سازي پلاگين ناشناخته ممكن نسيت. ', '<API key>' => 'يافتن پلاگين @plugin@ براي@action@ ممكن نيست. ', '<API key>' => 'غيرفعال كردن پلاگيني كه فعال نيست ممكن نيست. ', '<API key>' => '@plugin@ با نسخه‌ي اسپيپي كه مي‌خواهيد استفاده كنيد جور نيست.', '<API key>' => 'هيچ پلاگيني در دسترس نيست! لطفاً براي افزودن فهرست‌هاي پلاگين‌ها به صفحه‌ي مديريت مخازن تشريف ببريد. ', '<API key>' => 'اين مخزن «@url@» هيچ پاكت جديدي كه با پايگاه الأن ثبت شده سازگار باشد ارايه نمي‌كند. در نتيجه اين مخزن افزوده نشده است. ', '<API key>' => 'پلاگيني براي نصب نيست. لطفاً پلاگين‌ها را براي نصب انتخاب كنيد.', '<API key>' => 'اين ميدان اجباري است', '<API key>' => 'نشاني «@url@» سازگار با مخزني كه الأن افزوده شده', '<API key>' => 'به هنگام سازي پلاگين @plugin@(@id@).يافت نمي‌شود', '<API key>' => 'پلاگين درخواست شده موجود نيست (@plugin@).', '<API key>' => 'خطاي اس‌.كيو.ال وقتي مخزن @objet@افزوده مي‌شود ', '<API key>' => ' نشاني«@url@» درست نيست', '<API key>' => 'پرونده ايكس.ام.ال «@fichier@»در توصيف مخزن تأييد نمي‌شود. ', '<API key>' => 'هيچ پلاگيني با معيار‌هاي منتخب جور نيست.', '<API key>' => 'مخزن «@url@» افزوده شده.', '<API key>' => '@nb_plugins@.در زير پلاگين‌هايي را كه مي‌خواهيد بارگذاري كرده و در سرور خود فعال كنيد، انتخاب نماييد. پلاگين با معيارهاي منتخب(@tri@) جور است ', '<API key>' => 'آرشيو به درستي به @dir@ استخراج شد.', 'nettoyer_actions' => 'حذف اين اقدام‌ها! اين كار فهرست اقدام‌هاي مانده براي اجرا را پاك مي‌كند. ', 'onglet_depots' => 'مديريت مخازن', '<API key>' => 'تمام مقوله‌ها', 'option_depot_tout' => 'تمام مخازن', 'option_doublon_non' => 'آخرين نسخه', 'option_doublon_oui' => 'تمام نسخه‌هاي در دسترس', 'option_etat_tout' => 'تمام حالت‌ها', 'placeholder_phrase' => 'پيشوند،‌اسم، شعار، توصيف يا ديگر', 'plugin_info_actif' => 'پلاگين فعال ', 'plugin_info_up' => ' يك به‌ هنگام سازي شده‌ از اين پلاگين در دسترس است (نسخه@version@‌ )', '<API key>' => 'پلاگين قفل شده ', '<API key>' => 'غيرفعال‌ها', '<API key>' => 'قفل نشده‌ها', '<API key>' => 'قفل‌شده‌ها', 'resume_table_depots' => 'فهرست مخازن افزوده شده', '<API key>' => 'فهرست پاكت‌ها', '<API key>' => 'فهرست پلاگين‌ها @categorie@', '<API key>' => 'مي‌توانيد آرشيوي را كه در پوشه‌ي شما بارگذاشته خواهد شد، با نوشتن يو.آر.ال اين پوشه در مدخل ميدان، بارگذاري كنيد. ', 'titre_depot' => 'مخزن', 'titre_depots' => 'مخزن‌ها', '<API key>' => 'افزودن يك سپرده ', '<API key>' => 'جستجو و افزودن پلاگين‌ها', '<API key>' => 'بارگذاري يك پلاگين از پوشه‌اش', '<API key>' => 'پيكربندي سرور پلاگين‌ها', '<API key>' => 'اسكلت‌ها، كتابخانه‌ها، سري آيكون‌ها', # MODIF '<API key>' => 'سپرده‌هاي ديگر', 'titre_liste_depots' => 'فهرست مخازن در دسترس', '<API key>' => 'فهرست پاكت‌هاي پلاگين', 'titre_liste_plugins' => 'فهرست پلاگين‌ها', 'titre_logo_depot' => 'لوگوي سپرده', 'titre_logo_plugin' => 'لوگوي پلاگين', 'titre_nouveau_depot' => 'سپرده‌ي جديد', '<API key>' => 'سرور پلاگين‌ها', 'titre_paquet' => 'پاكت ', 'titre_paquets' => 'پاكت‌ها', 'titre_plugin' => 'ويرايش مستقيم', 'titre_plugins' => 'پلاگين‌ها', 'tout_cocher' => 'علامت زدن همه', 'tout_cocher_up' => 'علامت زدن به‌ هنگام‌سازي‌ها', 'tout_decocher' => 'رها كردن همه' ); ?>
# photomapping-utils Utilities for mass-creating, -processing and -uploading geotagged photos ## Directories - `chdk`: Software for usage on Canon cameras that support the CHDK software - `general`: Vendor-agnostic software for processing images - `mapillary`: Software in context with Mapillary - `raspi`: Software to be run on Raspberry Pi - `stats`: Software for generating statistics over images ## My workflow - Start GPS logger(s) - Take pictures - Canon S100: `chdk/mpllry.lua` - Raspberry Pi: `raspi/autocapture.py` - Retreive pictures: - Canon S100: If there was an overflow in the filename's counter: `general/prepend_filename.txt` - Retreive GPX data - Canon S100: `general/pics2gpx/<API key>.sh` - Combine GPX tracks: `general/merge_gpx.py` - Rasperry Pi: Repair pictures whose geotagging can't be displayed by JOSM: `general/repair.sh` - Geotag pictures using JOSM - Canon S100: Determine offset statistically by looking at pictures and comparing them to aerial imagery - Remove duplicate pictures that were automatically shot when standing still: `general/<API key>.sh` (this will give an error when called for nested directories) - Raspberry Pi: To prevent silent failing of <API key>.sh, call `general/repair.sh` - Optional: Split into multiple tracks: `general/time_split.py` or manually - Generate viewing direction: `general/<API key>.sh` - Remove non-EXIF metainformation and thumbnails, add GPSVersionID=2.3.0.0: `general/<API key>.sh` - Upload pictures: - Mapillary: `mapillary/my_upload.sh` or `mapillary/my_folders_upload.sh` - OpenStreetCam: Generally according to: <https://github.com/openstreetcam/upload-scripts> - `cd $checked_out_dir` - `source bin/activate` - Test: `find /home/bozo/mypics -mindepth 1 -type d` - `find /home/bozo/mypics -mindepth 1 -type d -print0 | xargs -L 1 --null ./upload_exif.py -p` ## time_split.py Syntax: python time_split.py path/to/images [cutoff-time] ## <API key>.py Syntax: python <API key>.py path/to/images direction_of_camera Install requirements (Ubuntu): sudo apt-get install python-pyexiv2 ## remove_duplicates.py Syntax: remove_duplicates.py -d 2 /path/to/pics /path/to/dup_pics
#include "shapefil.h" #include "asf_vector.h" #include "meta_project.h" #include "asf.h" #include <assert.h> #include <ctype.h> #include "asf_nan.h" #include "dateUtil.h" #include "float_image.h" #include "ceos_io.h" #include "libasf_proj.h" #include <stdio.h> #include <math.h> int point2kml(char *inFile, char *outFile) { char id[255], line[1024]; double lat, lon; FILE *fpIn = FOPEN(inFile, "r"); FILE *fpOut = FOPEN(outFile, "w"); kml_header(fpOut); fgets(line, 1024, fpIn); // header line while (fgets(line, 1024, fpIn)) { chomp(line); sprintf(id, "%s", get_str(line, 0)); lat = atof(get_str(line, 1)); lon = atof(get_str(line, 2)); // Write information in kml file fprintf(fpOut, "<Placemark>\n"); fprintf(fpOut, " <name>%s</name>\n", id); fprintf(fpOut, " <description>\n"); fprintf(fpOut, " <![CDATA[\n"); fprintf(fpOut, "<!-- Format: POINT (generated by %s) -->", <API key>); fprintf(fpOut, " <strong>ID</strong>: %s <br>\n", id); fprintf(fpOut, " <strong>Latitude</strong>: %12.5f <br>\n", lat); fprintf(fpOut, " <strong>Longitude</strong>: %12.5f <br>\n", lon); fprintf(fpOut, " ]]>\n"); fprintf(fpOut, " </description>\n"); fprintf(fpOut, " <LookAt>\n"); fprintf(fpOut, " <longitude>%12.5f</longitude>\n", lon); fprintf(fpOut, " <latitude>%12.5f</latitude>\n", lat); fprintf(fpOut, " <range>400000</range>\n"); fprintf(fpOut, " </LookAt>\n"); fprintf(fpOut, " <Point>\n"); fprintf(fpOut, " <coordinates>%f,%f,0</coordinates>\n", lon, lat); fprintf(fpOut, " </Point>\n"); fprintf(fpOut, "</Placemark>\n"); } kml_footer(fpOut); FCLOSE(fpOut); FCLOSE(fpIn); return TRUE; } void kml_header(FILE *kml_file) { fprintf(kml_file, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); fprintf(kml_file, "<kml xmlns=\"http://earth.google.com/kml/2.2\">\n"); fprintf(kml_file, "<Document>\n"); } void kml_footer(FILE *kml_file) { fprintf(kml_file, "</Document>\n"); fprintf(kml_file, "</kml>\n"); } void <API key>(FILE *kml_file, c2v_config *cfg) { // so all of our methods use the same "look" for the // boxes/lines. fprintf(kml_file, " <Style>\n"); fprintf(kml_file, " <LineStyle>\n"); if (cfg) { fprintf(kml_file, " <color>%s</color>\n", cfg->color); fprintf(kml_file, " <width>%d</width>\n", cfg->width); } else { fprintf(kml_file, " <color>ffff9900</color>\n"); fprintf(kml_file, " <width>5</width>\n"); } fprintf(kml_file, " </LineStyle>\n"); fprintf(kml_file, " <PolyStyle>\n"); fprintf(kml_file, " <color>1fff5500</color>\n"); fprintf(kml_file, " </PolyStyle>\n"); fprintf(kml_file, " </Style>\n"); } void <API key>(FILE *kml_file) { <API key>(kml_file, NULL); } void <API key>(FILE *kml_file, int nAttr, dbf_header_t *dbf) { int ii; fprintf(kml_file, " <description><![CDATA[\n"); fprintf(kml_file, " <table width=\"400\"><tr><td>\n"); // Write fields into the KML file for (ii=0; ii<nAttr; ii++) { if (dbf[ii].format == DBF_STRING) { //printf("STR ii=%d nAttr=%d def=%s val=%s\n", ii, nAttr, dbf[ii].definition, dbf[ii].sValue); fprintf(kml_file, " <strong>%s</strong>: %s <br>\n", dbf[ii].definition, dbf[ii].sValue ? dbf[ii].sValue : ""); } else if (dbf[ii].format == DBF_INTEGER) { //printf("INT ii=%d nAttr=%d val=%s\n", ii, nAttr, dbf[ii].definition); fprintf(kml_file, " <strong>%s</strong>: %d <br>\n", dbf[ii].definition, dbf[ii].nValue); } else if (dbf[ii].format == DBF_DOUBLE) { //printf("DBL ii=%d nAttr=%d val=%s\n", ii, nAttr, dbf[ii].definition); fprintf(kml_file, " <strong>%s</strong>: %f <br>\n", dbf[ii].definition, dbf[ii].fValue); } } fprintf(kml_file, " </td></tr></table>\n"); fprintf(kml_file, " ]]></description>\n"); } void write_kml_object(FILE *kml_file, c2v_config *cfg, char *png_filename, int start, int end, double *lat, double *lon) { int ii; if (cfg) { if (strcmp_case(cfg->boundary, "POLYGON") != 0 && strcmp_case(cfg->boundary, "LINE") != 0) strcpy(cfg->boundary, "POLYGON"); if (strcmp_case(cfg->altitude, "RELATIVETOGROUND") != 0 && strcmp_case(cfg->altitude, "CLAMPTOGROUND") != 0 && strcmp_case(cfg->altitude, "ABSOLUTE") != 0) strcpy(cfg->altitude, "absolute"); } if (cfg && strcmp_case(cfg->boundary, "LINE") == 0) { <API key>(kml_file, cfg); fprintf(kml_file, " <LineString>\n"); fprintf(kml_file, " <altitudeMode>%s</altitudeMode>\n", cfg->altitude); fprintf(kml_file, " <extrude>1</extrude>\n"); fprintf(kml_file, " <tesselate>1</tesselate>\n"); } else { <API key>(kml_file, cfg); fprintf(kml_file, " <Polygon>\n"); fprintf(kml_file, " <extrude>%d</extrude>\n", png_filename ? 0 : 1); fprintf(kml_file, " <altitudeMode>%s</altitudeMode>\n", cfg ? cfg->altitude : "3000"); fprintf(kml_file, " <outerBoundaryIs>\n"); fprintf(kml_file, " <LinearRing>\n"); } fprintf(kml_file, " <coordinates>\n"); int height = cfg && cfg->height > 0 ? cfg->height : 7000; for (ii=start; ii<end; ii++) fprintf(kml_file, " %.6f,%.6f,%d\n", lon[ii], lat[ii], height); fprintf(kml_file, " </coordinates>\n"); if (cfg && strcmp_case(cfg->boundary, "LINE") == 0) fprintf(kml_file, " </LineString>\n"); else { fprintf(kml_file, " </LinearRing>\n"); fprintf(kml_file, " </outerBoundaryIs>\n"); fprintf(kml_file, " </Polygon>\n"); } } void write_kml_placemark(FILE *kml_file, char *name, double center_lat, double center_lon, char *png_filename, dbf_header_t *dbf, int nAttr, double *lat, double *lon, int nCoords, c2v_config *cfg) { fprintf(kml_file, "<Placemark>\n"); <API key>(kml_file, nAttr, dbf); fprintf(kml_file, " <name>%s</name>\n", name); fprintf(kml_file, " <LookAt>\n"); fprintf(kml_file, " <longitude>%.6f</longitude>\n", center_lon); fprintf(kml_file, " <latitude>%.6f</latitude>\n", center_lat); fprintf(kml_file, " <range>%d</range>\n", cfg ? cfg->range : 400000); fprintf(kml_file, " </LookAt>\n"); // Check whether we need to split up the polygon if (crosses_dateline(lon, 0, nCoords)) { int *start = (int *) MALLOC(sizeof(int)*2); double *mLat = (double *) MALLOC(sizeof(double)*(nCoords+5)); double *mLon = (double *) MALLOC(sizeof(double)*(nCoords+5)); split_polygon(lat, lon, 5, start, mLat, mLon, 60); fprintf(kml_file, " <MultiGeometry>\n"); write_kml_object(kml_file, cfg, png_filename, 0, start[1], mLat, mLon); write_kml_object(kml_file, cfg, png_filename, start[1], 10, mLat, mLon); fprintf(kml_file, " </MultiGeometry>\n"); FREE(mLat); FREE(mLon); FREE(start); } else write_kml_object(kml_file, cfg, png_filename, 0, 5, lat, lon); fprintf(kml_file, "</Placemark>\n"); if (png_filename) { fprintf(kml_file, "<GroundOverlay>\n"); fprintf(kml_file, " <name>%s</name>\n", name); if (cfg) fprintf(kml_file, " <color>%xffffff</color>\n", (int)((100 - cfg->transparency) * 2.55 + 0.5)); fprintf(kml_file, " <Icon>\n"); fprintf(kml_file, " <href>%s</href>\n", png_filename); fprintf(kml_file, " <viewBoundScale>0.75</viewBoundScale>\n"); fprintf(kml_file, " </Icon>\n"); if (cfg) { fprintf(kml_file, " <LatLonBox>\n"); fprintf(kml_file, " <north>%.4f</north>\n", cfg->north); fprintf(kml_file, " <south>%.4f</south>\n", cfg->south); fprintf(kml_file, " <east>%.4f</east>\n", cfg->east); fprintf(kml_file, " <west>%.4f</west>\n", cfg->west); fprintf(kml_file, " </LatLonBox>\n"); } fprintf(kml_file, "</GroundOverlay>\n"); } } void csv2kml(char *inFile, char *outFile, char *format, c2v_config *cfg) { // Read header information FILE *fpIn; dbf_header_t *header; int ii, kk, nCols; char shape_type[25], **cols, str[10], line[1024]; if (strcmp_case(format, "CSV") == 0) { fpIn = FOPEN(inFile, "r"); fgets(line, 1024, fpIn); // header line chomp(line); split_into_array(line, ',', &nCols, &cols); header = (dbf_header_t *) MALLOC(sizeof(dbf_header_t)*nCols); strcpy(shape_type, "polygon"); for (ii=0; ii<nCols; ii++) { header[ii].meta = STRDUP(cols[ii]); header[ii].shape = STRDUP(cols[ii]); header[ii].format = DBF_STRING; header[ii].length = 50; header[ii].decimals = 0; header[ii].definition = STRDUP(cols[ii]); header[ii].column = ii; } FREE(cols); } else read_header_config(format, &header, &nCols, shape_type); // Figure out how many vertices we got int nColumns, nVertices = 0, nLat = 0, nLon = 0; fpIn = FOPEN(inFile, "r"); fgets(line, 1024, fpIn); // header line chomp(line); split_into_array(line, ',', &nColumns, &cols); for (ii=0; ii<nCols; ii++) { // Assign the column we need to read from for (kk=0; kk<nColumns; kk++) { if (strcmp_case(header[ii].meta, cols[kk]) == 0) header[ii].column = kk; } // Assuming that we don't have more than 12 vertices for (kk=1; kk<13; kk++) { sprintf(str, "LAT%d", kk); if (strcmp_case(header[ii].shape, str) == 0) nLat++; sprintf(str, "LON%d", kk); if (strcmp_case(header[ii].shape, str) == 0) nLon++; } // Alternative column names - only things that we already know if (strcmp_case(header[ii].shape, "NEAR START LAT") == 0 || strcmp_case(header[ii].shape, "NEAR_START_LAT") == 0) nLat++; else if (strcmp_case(header[ii].shape, "NEAR START LON") == 0 || strcmp_case(header[ii].shape, "NEAR_START_LON") == 0) nLon++; else if (strcmp_case(header[ii].shape, "FAR START LAT") == 0 || strcmp_case(header[ii].shape, "FAR_START_LAT") == 0) nLat++; else if (strcmp_case(header[ii].shape, "FAR START LON") == 0 || strcmp_case(header[ii].shape, "FAR_START_LON") == 0) nLon++; else if (strcmp_case(header[ii].shape, "NEAR END LAT") == 0 || strcmp_case(header[ii].shape, "NEAR_END_LAT") == 0) nLat++; else if (strcmp_case(header[ii].shape, "NEAR END LON") == 0 || strcmp_case(header[ii].shape, "NEAR_END_LON") == 0) nLon++; else if (strcmp_case(header[ii].shape, "FAR END LAT") == 0 || strcmp_case(header[ii].shape, "FAR_END_LAT") == 0) nLat++; else if (strcmp_case(header[ii].shape, "FAR END LON") == 0 || strcmp_case(header[ii].shape, "FAR_END_LON") == 0) nLon++; } if (nLat != nLon) asfPrintError("Found %d latitude and %d longitude columns.\n" "Can't convert this information properly!\n", nLat, nLon); else { nVertices = nLat; asfPrintStatus("Found %d vertices of a polygon.\n", nVertices); } // Open KML file FILE *kml_file = FOPEN(outFile, "w"); kml_header(kml_file); fprintf(kml_file, "<!-- Format: %s (generated by %s) -->\n", format, <API key>); // Read polygon information double *lat = (double *) MALLOC(sizeof(double)*(nVertices+1)); double *lon = (double *) MALLOC(sizeof(double)*(nVertices+1)); int column; char name[100]; double center_lat = 0.0, center_lon = 0.0; while (fgets(line, 1024, fpIn)) { chomp(line); split_into_array(line, ',', &nColumns, &cols); for (ii=0; ii<nCols; ii++) { column = header[ii].column; if (header[ii].format == DBF_STRING) header[ii].sValue = STRDUP(cols[column]); else if (header[ii].format == DBF_INTEGER) header[ii].nValue = atoi(cols[column]); else if (header[ii].format == DBF_DOUBLE) header[ii].fValue = atof(cols[column]); // Standard LAT/LON columns - mentioned in the documentation for (kk=0; kk<nVertices; kk++) { sprintf(str, "LAT%d", kk+1); if (strcmp_case(header[ii].shape, str) == 0) lat[kk] = atof(cols[column]); sprintf(str, "LON%d", kk+1); if (strcmp_case(header[ii].shape, str) == 0) lon[kk] = atof(cols[column]); } // Alternative column names - only things that we already know if (strcmp_case(header[ii].shape, "NEAR START LAT") == 0 || strcmp_case(header[ii].shape, "NEAR_START_LAT") == 0) lat[0] = atof(cols[column]); else if (strcmp_case(header[ii].shape, "NEAR START LON") == 0 || strcmp_case(header[ii].shape, "NEAR_START_LON") == 0) lon[0] = atof(cols[column]); else if (strcmp_case(header[ii].shape, "FAR START LAT") == 0 || strcmp_case(header[ii].shape, "FAR_START_LAT") == 0) lat[1] = atof(cols[column]); else if (strcmp_case(header[ii].shape, "FAR START LON") == 0 || strcmp_case(header[ii].shape, "FAR_START_LON") == 0) lon[1] = atof(cols[column]); else if (strcmp_case(header[ii].shape, "NEAR END LAT") == 0 || strcmp_case(header[ii].shape, "NEAR_END_LAT") == 0) lat[3] = atof(cols[column]); else if (strcmp_case(header[ii].shape, "NEAR END LON") == 0 || strcmp_case(header[ii].shape, "NEAR_END_LON") == 0) lon[3] = atof(cols[column]); else if (strcmp_case(header[ii].shape, "FAR END LAT") == 0 || strcmp_case(header[ii].shape, "FAR_END_LAT") == 0) lat[2] = atof(cols[column]); else if (strcmp_case(header[ii].shape, "FAR END LON") == 0 || strcmp_case(header[ii].shape, "FAR_END_LON") == 0) lon[2] = atof(cols[column]); } lat[nVertices] = lat[0]; lon[nVertices] = lon[0]; FREE(cols); // Writing KML placemark sprintf(name, "%s", inFile); for (ii=0; ii<nVertices; ii++) { center_lat += lat[ii]; center_lon += lon[ii]; } center_lat /= nVertices; center_lon /= nVertices; write_kml_placemark(kml_file, name, center_lat, center_lon, NULL, header, nCols, lat, lon, nVertices+1, cfg); } kml_footer(kml_file); FCLOSE(kml_file); } // Convert to KML file int convert2kml(char *inFile, char *outFile, char *format, int list, c2v_config *cfg) { FILE *kml_file; dbf_header_t *dbf = NULL; char line[1024]; int ii, n = 0, nAttr = 0, nCoords = 0; double *lat = NULL, *lon = NULL, center_lat = 0.0, center_lon = 0.0; meta_parameters *meta = NULL; char name[512]; if (list) { FILE *fpIn = FOPEN(inFile, "r"); kml_file = FOPEN(outFile, "w"); kml_header(kml_file); while (fgets(line, 1024, fpIn)) { chomp(line); if (strcmp_case(format, "META") == 0) { meta = meta2vector(line, &dbf, &nAttr, &lat, &lon, &nCoords); sprintf(name, "%s", meta->general->basename); center_lat = meta->general->center_latitude; center_lon = meta->general->center_longitude; fprintf(kml_file, "<!-- Format: META (generated by %s) -->\n", <API key>); write_kml_placemark(kml_file, name, center_lat, center_lon, NULL, dbf, nAttr, lat, lon, nCoords, cfg); meta_free(meta); } else if (strcmp_case(format, "GEOTIFF") == 0) { geotiff2vector(inFile, &dbf, &nAttr, &lat, &lon, &nCoords); sprintf(name, "%s", inFile); for (ii=0; ii<nCoords; ii++) { center_lat += lat[ii]; center_lon += lon[ii]; } center_lat /= nCoords; center_lon /= nCoords; fprintf(kml_file, "<!-- Format: GeoTIFF (generated by %s) -->\n", <API key>); write_kml_placemark(kml_file, name, center_lat, center_lon, NULL, dbf, nAttr, lat, lon, nCoords, cfg); } else if (strcmp_case(format, "POLYGON") == 0) { polygon2vector(inFile, &dbf, &nAttr, &lat, &lon, &nCoords); sprintf(name, "%s", inFile); for (ii=0; ii<nCoords; ii++) { center_lat += lat[ii]; center_lon += lon[ii]; } center_lat /= nCoords; center_lon /= nCoords; kml_file = FOPEN(outFile, "w"); kml_header(kml_file); fprintf(kml_file, "<!-- Format: Polygon (generated by %s) -->\n", <API key>); write_kml_placemark(kml_file, name, center_lat, center_lon, NULL, dbf, nAttr, lat, lon, nCoords, cfg); kml_footer(kml_file); } else asfPrintError("List option for %s format not supported\n", format); n++; } FCLOSE(fpIn); kml_footer(kml_file); FCLOSE(kml_file); } else { if (strcmp_case(format, "META") == 0) { meta = meta2vector(inFile, &dbf, &nAttr, &lat, &lon, &nCoords); sprintf(name, "%s", meta->general->basename); center_lat = meta->general->center_latitude; center_lon = meta->general->center_longitude; kml_file = FOPEN(outFile, "w"); kml_header(kml_file); fprintf(kml_file, "<!-- Format: META (generated by %s) -->\n", <API key>); if (strlen(cfg->overlay) > 0) write_kml_placemark(kml_file, name, center_lat, center_lon, cfg->overlay, dbf, nAttr, lat, lon, nCoords, cfg); else write_kml_placemark(kml_file, name, center_lat, center_lon, NULL, dbf, nAttr, lat, lon, nCoords, cfg); kml_footer(kml_file); meta_free(meta); FCLOSE(kml_file); } else if (strcmp_case(format, "GEOTIFF") == 0) { geotiff2vector(inFile, &dbf, &nAttr, &lat, &lon, &nCoords); sprintf(name, "%s", inFile); for (ii=0; ii<nCoords; ii++) { center_lat += lat[ii]; center_lon += lon[ii]; } center_lat /= nCoords; center_lon /= nCoords; kml_file = FOPEN(outFile, "w"); kml_header(kml_file); fprintf(kml_file, "<!-- Format: GEOTIFF (generated by %s) -->\n", <API key>); write_kml_placemark(kml_file, name, center_lat, center_lon, NULL, dbf, nAttr, lat, lon, nCoords, cfg); kml_footer(kml_file); FCLOSE(kml_file); } else if (strcmp_case(format, "POLYGON") == 0) { polygon2vector(inFile, &dbf, &nAttr, &lat, &lon, &nCoords); sprintf(name, "%s", inFile); for (ii=0; ii<nCoords; ii++) { center_lat += lat[ii]; center_lon += lon[ii]; } center_lat /= nCoords; center_lon /= nCoords; kml_file = FOPEN(outFile, "w"); kml_header(kml_file); fprintf(kml_file, "<!-- Format: POLYGON (generated by %s) -->\n", <API key>); write_kml_placemark(kml_file, name, center_lat, center_lon, NULL, dbf, nAttr, lat, lon, nCoords, cfg); kml_footer(kml_file); FCLOSE(kml_file); } else // must be some CSV type file csv2kml(inFile, outFile, format, cfg); } FREE(lat); FREE(lon); return TRUE; }
#include "impl.h" #include "stubs.h" #include "fdinfo.h" #include "fdtable.h" #include "utils.h" #include <stdio.h> #include <signal.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <pthread.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/un.h> #include <sys/syscall.h> #include <sys/wait.h> #include <poll.h> #define unlikely(x) __builtin_expect(!!(x), 0) #ifndef SYS_accept4 #ifdef ARCH64BIT #define SYS_accept4 (288) #elif ARCH32BIT #define SYS_accept4 (0x40000000 + 288) #else #error "Unknown architecture?" #endif #endif typedef enum { FORK = 1, EXEC = 2, } exit_strategy_t; typedef enum { FALSE = 0, TRUE = 1, } bool_t; /* Copy of execution environment. */ static char **environ_copy = NULL; static char **args_copy = NULL; static char *exe_copy = NULL; static char *cwd_copy = NULL; /* Whether or not we are currently exiting. */ static bool_t is_exiting = FALSE; /* Our exit strategy (set on startup). */ static exit_strategy_t exit_strategy = FORK; /* Files to unlink? */ static char *to_unlink = NULL; /* Multi mode? */ static bool_t multi_mode = FALSE; /* Revive mode? */ static bool_t revive_mode = FALSE; /* Wait mode? */ static bool_t wait_mode = FALSE; /* Whether or not our HUP handler will exit or restart. */ static pid_t master_pid = (pid_t)-1; /* Debug hook. */ static bool_t debug_enabled = FALSE; #define DEBUG(fmt, args...) \ do { \ if( debug_enabled == TRUE ) \ { \ pid_t pid = getpid(); \ fprintf(stderr, "huptime %d: " fmt "\n", pid, ## args); \ fflush(stderr); \ } \ } while(0) /* Lock (for thread-safe fd tracking). */ static pthread_mutex_t mutex; #define L() \ do { \ DEBUG("-wait- %d", __LINE__); \ pthread_mutex_lock(&mutex); \ DEBUG("-acquired- %d", __LINE__); \ } while(0) #define U() \ do { \ DEBUG("-release- %d", __LINE__); \ <API key>(&mutex); \ } while(0) /* Our restart signal pipe. */ static int restart_pipe[2] = { -1, -1 }; /* Our core signal handlers. */ static void* impl_restart_thread(void*); void sighandler(int signo) { /* Notify the restart thread. * We have to do this in a separate thread, because * we have no guarantees about which thread has been * interrupted in order to execute this signal handler. * Because this could have happened during a critical * section (i.e. locks held) we have no choice but to * fire the restart asycnhronously so that it too can * grab locks appropriately. */ if( restart_pipe[1] == -1 ) { /* We've already run. */ return; } while( 1 ) { char go = 'R'; int rc = write(restart_pipe[1], &go, 1); if( rc == 0 ) { /* Wat? Try again. */ continue; } else if( rc == 1 ) { /* Done. */ libc.close(restart_pipe[1]); restart_pipe[1] = -1; break; } else if( rc < 0 && (errno == EAGAIN || errno == EINTR) ) { /* Go again. */ continue; } else { /* Shit. */ DEBUG("Restart pipe fubared!? Sorry."); break; } } } static int do_dup(int fd) { int rval = -1; fdinfo_t *info = NULL; if( fd < 0 ) { errno = EINVAL; return -1; } DEBUG("do_dup(%d, ...) ...", fd); L(); info = fd_lookup(fd); if( info == NULL ) { U(); rval = libc.dup(fd); DEBUG("do_dup(%d) => %d (no info)", fd, rval); return rval; } rval = libc.dup(fd); if( rval >= 0 ) { inc_ref(info); fd_save(rval, info); } U(); DEBUG("do_dup(%d) => %d (with info)", fd, rval); return rval; } void impl_exec(void) { DEBUG("Preparing for exec..."); /* Reset our signal masks. * We intentionally mask SIGHUP here so that * it can't be called prior to us installing * our signal handlers. */ sigset_t set; sigemptyset(&set); sigaddset(&set, SIGHUP); sigprocmask(SIG_BLOCK, &set, NULL); /* Encode extra information. * * This includes information about sockets which * are in the BOUND or SAVED state. Note that we * can't really do anything with these *now* as * there are real threads running rampant -- so * we encode things for the exec() and take care * of it post-exec(), where we know we're solo. * * This information is encoded into a pipe which * is passed as an extra environment variable into * the next child. Although there is a limit on the * amount of data that can be stuffed into a pipe, * past Linux 2.6.11 (IIRC) this is 65K. */ int pipes[2]; if( pipe(pipes) < 0 ) { DEBUG("Unable to create pipes?"); libc.exit(1); } /* Stuff information into the pipe. */ for( int fd = 0; fd < fd_limit(); fd += 1 ) { fdinfo_t *info = fd_lookup(fd); int to_be_saved = (info != NULL && (info->type == BOUND || info->type == SAVED)); if( fd == 2 || to_be_saved ) { /* I can't believe this is necessary. * When node.js starts up, it seems to run over * an arbitrary number of file descriptors and * mark them all CLO_EXEC. That is so messed up. * That's some seriously broken behaviour. */ fcntl(fd, F_SETFD, 0); } if( to_be_saved ) { if( info_encode(pipes[1], fd, info) < 0 ) { DEBUG("Error encoding fd %d: %s", fd, strerror(errno)); } else { DEBUG("Encoded fd %d (type %d).", fd, info->type); } } } libc.close(pipes[1]); DEBUG("Finished encoding."); /* Prepare our environment variable. */ char pipe_env[32]; snprintf(pipe_env, 32, "HUPTIME_PIPE=%d", pipes[0]); /* Mask the existing environment variable. */ char **environ = environ_copy; int environ_len = 0; for( environ_len = 0; environ[environ_len] != NULL; environ_len += 1 ) { if( !strncmp("HUPTIME_PIPE=", environ[environ_len], strlen("HUPTIME_PIPE=")) ) { environ[environ_len] = pipe_env; break; } } /* Do we need to extend the environment? */ if( environ[environ_len] == NULL ) { char** new_environ = malloc(sizeof(char*) * (environ_len + 2)); memcpy(new_environ, environ, sizeof(char*) * (environ_len)); new_environ[environ_len] = pipe_env; new_environ[environ_len + 1] = NULL; environ = new_environ; } /* Execute in the same environment, etc. */ chdir(cwd_copy); DEBUG("Doing exec()... bye!"); execve(exe_copy, args_copy, environ); /* Bail. Should never reach here. */ DEBUG("Things went horribly wrong!"); libc.exit(1); } void impl_exit_check(void) { if( is_exiting == TRUE && total_tracked == 0 ) { if( wait_mode == TRUE ) { /* Check for any active child processes. * NOTE: Because we are using waitid() here, and * that allows us to specify WNOWAIT, the child * will stay in a waitable state for to be reaped * whenever the actual program wants to. */ do { siginfo_t info; int rval = waitid(P_ALL, 0, &info, WNOHANG|WNOWAIT); if( rval < 0 && errno == EINTR ) { continue; } if( rval >= 0 || (rval < 0 && errno != ECHILD) ) { /* There are still active child processes. */ return; } break; } while( 1 ); } DEBUG("No active connections, finishing exit."); switch( exit_strategy ) { case FORK: /* We're done. * No more connections are active, and there's * presumably already a child process handling * new incoming connections. */ DEBUG("Goodbye!"); libc.exit(0); break; case EXEC: /* Let's do the exec. * We're wrapped up existing connections, we can * re-execute the application to start handling new * incoming connections. */ DEBUG("See you soon..."); impl_exec(); break; } } } static int info_close(int fd, fdinfo_t* info) { int rval = -1; switch( info->type ) { case BOUND: case TRACKED: case EPOLL: if( info->type == BOUND && revive_mode == TRUE ) { /* We don't close bound sockets in revive mode. * This allows the program to exit "cleanly" and * we will preserve the socket for the next run. */ rval = 0; break; } dec_ref(info); fd_delete(fd); rval = libc.close(fd); break; case SAVED: case DUMMY: /* Woah, their program is most likely either messed up, * or it's going through and closing all descriptors * prior to an exec. We're just going to ignore this. */ break; } return rval; } static int do_dup3(int fd, int fd2, int flags) { int rval = -1; fdinfo_t *info = NULL; fdinfo_t *info2 = NULL; if( fd < 0 || fd2 < 0 ) { errno = EINVAL; return -1; } DEBUG("do_dup3(%d, %d, ...) ...", fd, fd2); L(); if( fd == fd2 ) { U(); DEBUG("do_dup3(%d, %d, ...) => 0", fd, fd2); return fd2; } info = fd_lookup(fd); info2 = fd_lookup(fd2); if( info2 != NULL ) { rval = info_close(fd2, info2); if( rval < 0 ) { U(); DEBUG("do_dup3(%d, %d, ...) => %d (close failed)", fd, fd2, rval); return rval; } } rval = libc.dup3(fd, fd2, flags); if( rval < 0 ) { U(); DEBUG("do_dup3(%d, %d, ...) => %d (dup3 failed)", fd, fd2, rval); return rval; } if( info != NULL ) { inc_ref(info); fd_save(fd2, info); } U(); DEBUG("do_dup3(%d, %d, ...) => %d", fd, fd2, rval); return rval; } static int do_dup2(int fd, int fd2) { return do_dup3(fd, fd2, 0); } static int do_close(int fd) { int rval = -1; fdinfo_t *info = NULL; if( fd < 0 ) { errno = EINVAL; return -1; } DEBUG("do_close(%d, ...) ...", fd); L(); info = fd_lookup(fd); if( info == NULL ) { U(); rval = libc.close(fd); DEBUG("do_close(%d) => %d (no info)", fd, rval); return rval; } rval = info_close(fd, info); impl_exit_check(); U(); DEBUG("do_close(%d) => %d (%d tracked)", fd, rval, total_tracked); return rval; } static void impl_init_lock(void) { /* Initialize our lock. * This is a recursive lock simply for convenience. * There are a few calls (i.e. bind) which leverage * other unlock internal calls (do_dup2), so we make * the lock recursive. This could easily be eliminated * with a little bit of refactoring. */ pthread_mutexattr_t mutex_attr; <API key>(&mutex_attr); <API key>(&mutex_attr, <API key>); pthread_mutex_init(&mutex, &mutex_attr); } static void impl_init_thread(void) { if( restart_pipe[0] != -1 ) { libc.close(restart_pipe[0]); } if( restart_pipe[1] != -1 ) { libc.close(restart_pipe[1]); } /* Create our restart thread. * * See the note in sighandler() for an explanation * of why the restart must be done in a separate thread. * * We do the thread creation here instead of in the * handler because pthread_create() is not a signal-safe * function to call from the handler. */ if( pipe(restart_pipe) < 0 ) { DEBUG("Error creating restart pipes: %s", strerror(errno)); libc.exit(1); } /* Ensure that we have cloexec. */ if( fcntl(restart_pipe[0], F_SETFD, FD_CLOEXEC) < 0 || fcntl(restart_pipe[1], F_SETFD, FD_CLOEXEC) < 0 ) { DEBUG("Can't set restart pipe to cloexec?"); libc.exit(1); } pthread_t thread; pthread_attr_t thread_attr; pthread_attr_init(&thread_attr); <API key>(&thread_attr, 1); if( pthread_create(&thread, &thread_attr, impl_restart_thread, NULL) < 0 ) { DEBUG("Error creating restart thread: %s", strerror(errno)); libc.exit(1); } } static void <API key>(void) { struct sigaction action; struct sigaction old_action; action.sa_handler = sighandler; action.sa_flags = SA_RESTART; sigaction(SIGHUP, &action, &old_action); if( old_action.sa_handler != sighandler ) { DEBUG("Signal handler installed."); } } void impl_init(void) { const char* mode_env = getenv("HUPTIME_MODE"); const char* multi_env = getenv("HUPTIME_MULTI"); const char* revive_env = getenv("HUPTIME_REVIVE"); const char* debug_env = getenv("HUPTIME_DEBUG"); const char* pipe_env = getenv("HUPTIME_PIPE"); const char* wait_env = getenv("HUPTIME_WAIT"); if( debug_env != NULL && strlen(debug_env) > 0 ) { debug_enabled = !strcasecmp(debug_env, "true") ? TRUE: FALSE; } DEBUG("Initializing..."); /* Initialize our lock. */ impl_init_lock(); /* Save this pid as our master pid. * This is done to handle processes that use * process pools. We remember the master pid and * will do the full fork()/exec() only when we are * the master. Otherwise, we will simply shutdown * gracefully, and all the master to restart. */ master_pid = getpid(); /* Grab our exit strategy. */ if( mode_env != NULL && strlen(mode_env) > 0 ) { if( !strcasecmp(mode_env, "fork") ) { exit_strategy = FORK; DEBUG("Exit strategy is fork."); } else if( !strcasecmp(mode_env, "exec") ) { exit_strategy = EXEC; DEBUG("Exit strategy is exec."); } else { fprintf(stderr, "Unknown exit strategy."); libc.exit(1); } } /* Check if we have something to unlink. */ to_unlink = getenv("HUPTIME_UNLINK"); if( to_unlink != NULL && strlen(to_unlink) > 0 ) { DEBUG("Unlink is '%s'.", to_unlink); } /* Clear up any outstanding child processes. * Because we may have exited before the process * could do appropriate waitpid()'s, we try to * clean up children here. Note that we may have * some zombies that hang around during the life * of the program, but at every restart they will * be cleaned up (so at least they won't grow * without bound). */ int status = 0; while( waitpid((pid_t)-1, &status, WNOHANG) > 0 ); /* Check if we're in multi mode. */ if( multi_env != NULL && strlen(multi_env) > 0 ) { multi_mode = !strcasecmp(multi_env, "true") ? TRUE: FALSE; } #ifndef SO_REUSEPORT if( multi_mode == TRUE ) { fprintf(stderr, "WARNING: Multi mode not supported.\n"); fprintf(stderr, "(Requires at least Linux 3.9 and recent headers).\n"); } #endif /* Check if we're in revive mode. */ if( revive_env != NULL && strlen(revive_env) > 0 ) { revive_mode = !strcasecmp(revive_env, "true") ? TRUE : FALSE; } /* Check if we are in wait mode. */ if( wait_env != NULL && strlen(wait_env) > 0 ) { wait_mode = !strcasecmp(wait_env, "true") ? TRUE : FALSE; } /* Check if we're a respawn. */ if( pipe_env != NULL && strlen(pipe_env) > 0 ) { int fd = -1; fdinfo_t *info = NULL; int pipefd = strtol(pipe_env, NULL, 10); DEBUG("Loading all file descriptors."); /* Decode all passed information. */ while( !info_decode(pipefd, &fd, &info) ) { fd_save(fd, info); DEBUG("Decoded fd %d (type %d).", fd, info->type); info = NULL; } if( info != NULL ) { dec_ref(info); } /* Finished with the pipe. */ libc.close(pipefd); unsetenv("HUPTIME_PIPE"); DEBUG("Finished decoding."); /* Close all non-encoded descriptors. */ for( fd = 0; fd < fd_max(); fd += 1 ) { info = fd_lookup(fd); if( info == NULL ) { DEBUG("Closing fd %d.", fd); libc.close(fd); } } /* Restore all given file descriptors. */ for( fd = 0; fd < fd_limit(); fd += 1 ) { info = fd_lookup(fd); if( info != NULL && info->type == SAVED ) { fdinfo_t *orig_info = fd_lookup(info->saved.fd); if( orig_info != NULL ) { /* Uh-oh, conflict. Move the original (best effort). */ do_dup(info->saved.fd); do_close(info->saved.fd); } /* Return the offset (ignore failure). */ if( info->saved.offset != (off_t)-1 ) { lseek(fd, info->saved.offset, SEEK_SET); } /* Move the SAVED fd back. */ libc.dup2(fd, info->saved.fd); DEBUG("Restored fd %d.", info->saved.fd); } } } else { DEBUG("Saving all initial file descriptors."); /* Save all of our initial files. These are used * for re-execing the process. These are persisted * effectively forever, and on restarts we close * everything that is not a BOUND socket or a SAVED * file descriptor. */ for( int fd = 0; fd < fd_max(); fd += 1 ) { fdinfo_t *info = fd_lookup(fd); if( info != NULL ) { /* Encoded earlier. */ continue; } /* Make a new SAVED FD. */ int newfd = libc.dup(fd); if( newfd >= 0 ) { fdinfo_t *saved_info = alloc_info(SAVED); if( saved_info != NULL ) { saved_info->saved.fd = fd; saved_info->saved.offset = lseek(fd, 0, SEEK_CUR); fd_save(newfd, saved_info); DEBUG("Saved fd %d (offset %lld).", fd, (long long int)saved_info->saved.offset); } } } } /* Save the environment. * * NOTE: We reserve extra space in the environment * for our special start-up parameters, which will be added * in impl_exec() below. (The encoded BOUND/SAVED sockets). * * We also filter out the special variables above that were * used to pass in information about sockets that were bound. */ free(environ_copy); environ_copy = (char**)read_nul_sep("/proc/self/environ"); DEBUG("Saved environment."); /* Save the arguments. */ free(args_copy); args_copy = (char**)read_nul_sep("/proc/self/cmdline"); DEBUG("Saved args."); for( int i = 0; args_copy[i] != NULL; i += 1 ) { DEBUG(" arg%d=%s", i, args_copy[i]); } /* Save the cwd & exe. */ free(cwd_copy); cwd_copy = (char*)read_link("/proc/self/cwd"); DEBUG("Saved cwd."); free(exe_copy); exe_copy = (char*)read_link("/proc/self/exe"); DEBUG("Saved exe."); /* Install our signal handlers. */ <API key>(); /* Initialize our thread. */ impl_init_thread(); /* Unblock our signals. * Note that we have specifically masked the * signals prior to the exec() below, to cover * the race between program start and having * installed the appropriate handlers. */ sigset_t set; sigemptyset(&set); sigaddset(&set, SIGHUP); sigprocmask(SIG_UNBLOCK, &set, NULL); /* Done. */ DEBUG("Initialization complete."); } static int impl_dummy_server(void) { int dummy_server = -1; /* Create our dummy sock. */ struct sockaddr_un dummy_addr; char *socket_path = tempnam("/tmp", ".huptime"); memset(&dummy_addr, 0, sizeof(struct sockaddr_un)); dummy_addr.sun_family = AF_UNIX; strncpy(dummy_addr.sun_path, socket_path, sizeof(dummy_addr.sun_path)-1); /* Create a dummy server. */ dummy_server = socket(AF_UNIX, SOCK_STREAM, 0); if( dummy_server < 0 ) { fprintf(stderr, "Unable to create unix socket?"); return -1; } if( fcntl(dummy_server, F_SETFD, FD_CLOEXEC) < 0 ) { close(dummy_server); fprintf(stderr, "Unable to set cloexec?"); return -1; } if( libc.bind( dummy_server, (struct sockaddr*)&dummy_addr, sizeof(struct sockaddr_un)) < 0 ) { close(dummy_server); fprintf(stderr, "Unable to bind unix socket?"); return -1; } if( libc.listen(dummy_server, 1) < 0 ) { close(dummy_server); fprintf(stderr, "Unable to listen on unix socket?"); return -1; } /* Connect a dummy client. */ int dummy_client = socket(AF_UNIX, SOCK_STREAM, 0); if( dummy_client < 0 ) { close(dummy_server); fprintf(stderr, "Unable to create unix socket?"); return -1; } if( fcntl(dummy_client, F_SETFD, FD_CLOEXEC) < 0 ) { close(dummy_server); close(dummy_client); fprintf(stderr, "Unable to set cloexec?"); return -1; } if( connect( dummy_client, (struct sockaddr*)&dummy_addr, sizeof(struct sockaddr_un)) < 0 ) { close(dummy_server); close(dummy_client); fprintf(stderr, "Unable to connect dummy client?"); return -1; } /* Put the client into an error state. */ int dummy_fd = libc.accept(dummy_server, NULL, 0); if( dummy_fd < 0 ) { fprintf(stderr, "Unable to accept internal client?"); close(dummy_server); close(dummy_client); return -1; } close(dummy_fd); /* Save the dummy info. */ fdinfo_t* dummy_info = alloc_info(DUMMY); if( dummy_info == NULL ) { fprintf(stderr, "Unable to allocate dummy info?"); return -1; } dummy_info->dummy.client = dummy_client; fd_save(dummy_server, dummy_info); inc_ref(dummy_info); fd_save(dummy_client, dummy_info); /* Ensure that it's unlinked. */ unlink(socket_path); free(socket_path); return dummy_server; } void impl_exit_start(void) { if( is_exiting == TRUE ) { return; } /* We are now exiting. * After this point, all calls to various sockets, * (i.e. accept(), listen(), etc. will result in stalls. * We are just waiting until existing connections have * finished and then we will be either exec()'ing a new * version or exiting this process. */ is_exiting = TRUE; /* Get ready to restart. * We only proceed with actual restart actions * if we are the master process, otherwise we will * simply prepare to shutdown cleanly once all the * current active connections have finished. */ if( master_pid == getpid() ) { pid_t child; DEBUG("Exit started -- this is the master."); /* Unlink files (e.g. pidfile). */ if( to_unlink != NULL && strlen(to_unlink) > 0 ) { DEBUG("Unlinking '%s'...", to_unlink); unlink(to_unlink); } /* Neuter this process. */ for( int fd = 0; fd < fd_limit(); fd += 1 ) { fdinfo_t* info = fd_lookup(fd); if( exit_strategy == FORK && info != NULL && info->type == SAVED ) { /* Close initial files. Since these * are now passed on to the child, we * ensure that the parent won't mess * with them anymore. Note that we still * have a copy as all SAVED descriptors. */ if( info->saved.fd == 2 ) { /* We treat stderr special. * Assuming logging will go here, we * allow the parent process to continue * writing to this file (and hope that * it's open in APPEND mode, etc.). */ continue; } int nullfd = open("/dev/null", O_RDWR); do_dup2(nullfd, info->saved.fd); libc.close(nullfd); } if( info != NULL && info->type == BOUND && !info->bound.is_ghost ) { /* Change BOUND sockets to dummy sockets. * This will allow select() and poll() to * operate as you expect, and never give * back new clients. */ int newfd = do_dup(fd); if( newfd >= 0 ) { int dummy_server = impl_dummy_server(); if( dummy_server >= 0 ) { /* Remove the descriptor in any epoll FDs. */ for( int efd = 0; efd < fd_limit(); efd += 1 ) { fdinfo_t* einfo = fd_lookup(efd); if( einfo != NULL && einfo->type == EPOLL ) { struct epoll_event no_event; epoll_ctl(efd, EPOLL_CTL_DEL, fd, &no_event); } } info->bound.is_ghost = 1; do_dup2(dummy_server, fd); DEBUG("Replaced FD %d with dummy.", fd); } else { do_close(newfd); } } } } switch( exit_strategy ) { case FORK: /* Start the child process. * We will exit gracefully when the tracked * connection count reaches zero. */ DEBUG("Exit strategy is fork."); child = libc.fork(); if( child == 0 ) { DEBUG("I'm the child."); impl_exec(); } else { DEBUG("I'm the parent."); } break; case EXEC: /* Nothing necessary beyond the above. */ DEBUG("Exit strategy is exec."); break; } } else { /* Force our strategy to fork, though we haven't forked. * This will basically just have this process exit cleanly * once all the current active connections have finished. */ DEBUG("Exit started -- this is the child."); exit_strategy = FORK; } } void impl_restart(void) { /* Indicate that we are now exiting. */ L(); impl_exit_start(); impl_exit_check(); U(); } void* impl_restart_thread(void* arg) { /* Wait for our signal. */ while( 1 ) { char go = 0; int rc = read(restart_pipe[0], &go, 1); if( rc == 1 ) { break; } else if( rc == 0 ) { /* Wat? Restart. */ DEBUG("Restart pipe closed?!"); break; } else if( rc < 0 && (errno == EAGAIN || errno == EINTR) ) { /* Keep trying. */ continue; } else { /* Real error. Let's restart. */ DEBUG("Restart pipe fubared?!"); break; } } libc.close(restart_pipe[0]); restart_pipe[0] = -1; /* See note above in sighandler(). */ impl_restart(); return arg; } static pid_t do_fork(void) { pid_t res = (pid_t)-1; /* We block SIGHUP during fork(). * This is because we communicate our restart * intention via a pipe, and it's conceivable * that between the fork() and impl_init_thread() * the signal handler will be triggered and we'll * end up writing to the restart pipe that is * still connected to the master process. */ sigset_t set; sigemptyset(&set); sigaddset(&set, SIGHUP); sigprocmask(SIG_BLOCK, &set, NULL); DEBUG("do_fork() ..."); L(); res = libc.fork(); if( res == 0 ) { if( total_bound == 0 ) { /* We haven't yet bound any sockets. This is * a common pattern where the process may be * daemonizing. We reset the master_pid so that * the initalization routine will actually reset * and treat this new process as a master. * The reason we don't do this if sockets are * already bound, is that if master_pid != getpid(), * i.e. for process pools, then we neither fork() * nor exec(), but simply go into a normal exit. */ master_pid = getpid(); } impl_init_lock(); impl_init_thread(); } else { U(); } sigprocmask(SIG_UNBLOCK, &set, NULL); DEBUG("do_fork() => %d", res); return res; } static int do_bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen) { fdinfo_t *info = NULL; int rval = -1; if( sockfd < 0 ) { errno = EINVAL; return -1; } /* At this point, we can reasonably assume * the program has started up and has installed * whatever signal handlers it wants. We check * that our own signal handler is installed. * If the user doesn't want us to override the * built-in signal handlers, they shouldn't use * huptime. */ <API key>(); DEBUG("do_bind(%d, ...) ...", sockfd); L(); /* See if this socket already exists. */ for( int fd = 0; fd < fd_limit(); fd += 1 ) { fdinfo_t *info = fd_lookup(fd); if( info != NULL && info->type == BOUND && info->bound.addrlen == addrlen && !memcmp(addr, (void*)info->bound.addr, addrlen) ) { DEBUG("Found ghost %d, cloning...", fd); /* Give back a duplicate of this one. */ int rval = do_dup2(fd, sockfd); if( rval < 0 ) { /* Dup2 failed? */ DEBUG("Failed."); continue; } if( info->bound.is_ghost ) { /* Close the original (not needed). */ info->bound.is_ghost = 0; do_close(fd); } /* Success. */ U(); DEBUG("do_bind(%d, ...) => 0 (ghosted)", sockfd); return 0; } } #ifdef SO_REUSEPORT /* Multi mode? Set socket options. */ if( multi_mode == TRUE ) { int optval = 1; if( setsockopt(sockfd, SOL_SOCKET, SO_REUSEPORT, &optval, sizeof(optval)) < 0 ) { U(); DEBUG("do_bind(%d, ...) => -1 (no multi?)", sockfd); return -1; } DEBUG("Multi mode enabled."); } #endif /* Try a real bind. */ info = alloc_info(BOUND); if( info == NULL ) { U(); DEBUG("do_bind(%d, ...) => -1 (alloc error?)", sockfd); return -1; } rval = libc.bind(sockfd, addr, addrlen); if( rval < 0 ) { dec_ref(info); U(); DEBUG("do_bind(%d, ...) => %d (error)", sockfd, rval); return rval; } /* Ensure that this socket is non-blocking, * this is because we override the behavior * for accept() and we require non-blocking * behavior. We deal with the consequences. */ rval = fcntl(sockfd, F_SETFL, O_NONBLOCK); if( rval < 0 ) { dec_ref(info); U(); DEBUG("do_bind(%d, ...) => %d (fcntl error)", sockfd, rval); return -1; } /* Save a refresh bound socket info. */ info->bound.stub_listened = 0; info->bound.real_listened = 0; info->bound.addr = (struct sockaddr*)malloc(addrlen); info->bound.addrlen = addrlen; memcpy((void*)info->bound.addr, (void*)addr, addrlen); fd_save(sockfd, info); /* Success. */ U(); DEBUG("do_bind(%d, ...) => %d", sockfd, rval); return rval; } static int do_listen(int sockfd, int backlog) { int rval = -1; fdinfo_t *info = NULL; if( sockfd < 0 ) { errno = EINVAL; return -1; } DEBUG("do_listen(%d, ...) ...", sockfd); L(); info = fd_lookup(sockfd); if( info == NULL || info->type != BOUND ) { U(); DEBUG("do_listen(%d, %d) => -1 (not BOUND)", sockfd, backlog); errno = EINVAL; return -1; } /* Check if we can short-circuit this. */ if( info->bound.real_listened ) { info->bound.stub_listened = 1; U(); DEBUG("do_listen(%d, %d) => 0 (stub)", sockfd, backlog); return 0; } /* Can we really call listen() ? */ if( is_exiting == TRUE ) { info->bound.stub_listened = 1; U(); DEBUG("do_listen(%d, %d) => 0 (is_exiting)", sockfd, backlog); return 0; } /* We largely ignore the backlog parameter. People * don't really use sensible values here for the most * part. Hopefully (as is default on some systems), * tcp syn cookies are enabled, and there's no real * limit for this queue and this parameter is silently * ignored. If not, then we use the largest value we * can sensibly use. */ (void)backlog; rval = libc.listen(sockfd, SOMAXCONN); if( rval < 0 ) { U(); DEBUG("do_listen(%d, %d) => %d", sockfd, backlog, rval); return rval; } /* We're done. */ info->bound.real_listened = 1; info->bound.stub_listened = 1; U(); DEBUG("do_listen(%d, %d) => %d", sockfd, backlog, rval); return rval; } static int do_accept4(int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags) { int rval = -1; fdinfo_t *info = NULL; if( sockfd < 0 ) { errno = EINVAL; return -1; } DEBUG("do_accept4(%d, ...) ...", sockfd); L(); info = fd_lookup(sockfd); if( info == NULL || (info->type != BOUND && info->type != DUMMY) ) { U(); /* Should return an error. */ rval = libc.accept4(sockfd, addr, addrlen, flags); DEBUG("do_accept4(%d, ...) => %d (no info)", sockfd, rval); return rval; } /* Check that they've called listen. */ if( info->type == BOUND && !info->bound.stub_listened ) { U(); DEBUG("do_accept4(%d, ...) => -1 (not listened)", sockfd); errno = EINVAL; return -1; } /* Check if this is a dummy. * There's no way that they should be calling accept(). * The dummy FD will never trigger a poll, select, epoll, * etc. So we just act as a socket with no clients does -- * either return immediately or block forever. NOTE: We * still return in case of EINTR or other suitable errors. */ if( info->type == DUMMY && info->dummy.client >= 0 ) { rval = info->dummy.client; info->dummy.client = -1; U(); DEBUG("do_accept4(%d, ...) => %d (dummy client)", sockfd, rval); return rval; } U(); if( !(flags & SOCK_NONBLOCK) ) { /* Wait for activity on the socket. */ struct pollfd poll_info; poll_info.fd = sockfd; poll_info.events = POLLIN; poll_info.revents = 0; if( poll(&poll_info, 1, -1) < 0 ) { return -1; } } L(); /* Check our status. */ if( is_exiting == TRUE ) { /* We've transitioned from not exiting * to exiting in this period. This will * circle around a return a dummy descriptor. */ U(); DEBUG("do_accept4(%d, ...) => -1 (interrupted)", sockfd); errno = flags & SOCK_NONBLOCK ? EAGAIN : EINTR; return -1; } /* Do the accept for real. */ fdinfo_t *new_info = alloc_info(TRACKED); if( new_info == NULL ) { U(); DEBUG("do_accept4(%d, ...) => -1 (alloc error?)", sockfd); return -1; } inc_ref(info); new_info->tracked.bound = info; rval = libc.accept4(sockfd, addr, addrlen, flags); if( rval >= 0 ) { /* Save the reference to the socket. */ fd_save(rval, new_info); } else { /* An error occured, nothing to track. */ dec_ref(new_info); } U(); DEBUG("do_accept4(%d, ...) => %d (tracked %d) %s", sockfd, rval, total_tracked, rval == -1 ? strerror(errno) : ""); return rval; } static int do_accept4_retry(int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags) { while (1) { int rval = do_accept4(sockfd, addr, addrlen, flags); if( rval < 0 && (errno == EAGAIN || errno == EINTR) ) { /* Signal interrupted the system call. * Many programs cannot handle this cleanly, * (hence why they are using huptime). So we * simply absorb this error and continue. */ if( (flags & SOCK_NONBLOCK) && errno == EAGAIN ) { return rval; } continue; } /* Otherwise, give the error back. */ return rval; } } static int do_accept_retry(int sockfd, struct sockaddr *addr, socklen_t *addrlen) { return do_accept4_retry(sockfd, addr, addrlen, 0); } static void do_exit(int status) { if( revive_mode == TRUE ) { DEBUG("Reviving..."); impl_exec(); } libc.exit(status); } static pid_t do_wait(void *status) { pid_t rval = libc.wait(status); L(); impl_exit_check(); U(); return rval; } static pid_t do_waitpid(pid_t pid, int *status, int options) { pid_t rval = libc.waitpid(pid, status, options); L(); impl_exit_check(); U(); return rval; } static long do_syscall(long number, long a1, long a2, long a3, long a4, long a5, long a6) { /* This is very annoying. * Unfortunately, it looks like uv in nodejs uses * the syscall() function to directly call accept4. * Why? I don't know. * Anyways, this function is used internally within * libc, but we won't intercept any of those calls. * So performance isn't a critical concern here, but * we need to intercept syscall() for node.js. */ if( unlikely(number == SYS_accept4) ) { return do_accept4((int)a1, (struct sockaddr*)a2, (socklen_t*)a3, (int)a4); } return libc.syscall(number, a1, a2, a3, a4, a5, a6); } static int do_epoll_create1(int flags) { int rval = libc.epoll_create1(flags); if( rval >= 0 ) { fdinfo_t* info = alloc_info(EPOLL); fd_save(rval, info); } return rval; } static int do_epoll_create(int size) { return do_epoll_create1(0); } funcs_t impl = { .bind = do_bind, .listen = do_listen, .accept = do_accept_retry, .accept4 = do_accept4_retry, .close = do_close, .fork = do_fork, .dup = do_dup, .dup2 = do_dup2, .dup3 = do_dup3, .exit = do_exit, .wait = do_wait, .waitpid = do_waitpid, .syscall = (syscall_t)do_syscall, .epoll_create = do_epoll_create, .epoll_create1 = do_epoll_create1, }; funcs_t libc;
#include "Abs.h" //#include "yaafe-core/NumericUtils.h" #include <Eigen/Dense> #define EPS 2.220446049250313e-16 using namespace std; //using namespace blitz; using namespace Eigen; namespace YAAFE { Abs::Abs() { } Abs::~Abs() { } StreamInfo Abs::init(const ParameterMap& params, const StreamInfo& in) { if (in.size%2 != 0) { cerr << "ERROR: Abs input size should be even" << endl; return StreamInfo(); } return StreamInfo(in, in.size/2); } inline double nonZeroNorm(double r, double i) { double n = std::sqrt(r*r + i*i); return n ? n : EPS; } void Abs::processToken(double* inData, const int inSize, double* outData, const int outSize) { for (int i=0;i<outSize;++i) outData[i] = nonZeroNorm(inData[2*i],inData[2*i+1]); } }
// This file is part of the ClearCanvas RIS/PACS open source project. // The ClearCanvas RIS/PACS open source project is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public // The ClearCanvas RIS/PACS open source project is distributed in the hope that it // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General // the ClearCanvas RIS/PACS open source project. If not, see #endregion using System.Collections.Generic; using NUnit.Framework; #if UNIT_TESTS namespace Macro.Dicom.Utilities.Tests { internal class PathTest : DicomTagPath { public PathTest() : base() { } public void SetPath(string path) { base.Path = path; } public void SetPath(IList<DicomTag> tags) { base.TagsInPath = tags; } } [TestFixture] public class DicomTagPathTests { [TestFixtureSetUp] public void Init() { } [TestFixtureTearDown] public void Dispose() { } [Test] public void Test() { DicomTagPath path = new PathTest(); ((PathTest)path).SetPath("(0010,0010)"); Assert.AreEqual(path, "(0010,0010)"); Assert.AreEqual(path, (uint)0x00100010); Assert.AreEqual(path, NewDicomTag(0x00100010)); Assert.IsTrue(path.Equals("(0010,0010)")); Assert.IsTrue(path.Equals((uint)0x00100010)); Assert.IsTrue(path.Equals(NewDicomTag(0x00100010))); ((PathTest)path).SetPath("(0054,0220)\\(0054,0222)"); Assert.AreEqual(path, "(0054,0220)\\(0054,0222)"); Assert.IsFalse(path.Equals("(0054,0220)")); Assert.IsFalse(path.Equals((uint)0x00540220)); Assert.IsFalse(path.Equals(NewDicomTag(0x00540220))); ((PathTest)path).SetPath("(0054,0220)\\(0054,0222)\\(0010,0022)"); Assert.AreEqual(path.ToString(), "(0054,0220)\\(0054,0222)\\(0010,0022)"); path = new PathTest(); ((PathTest)path).SetPath(new List<DicomTag>(new DicomTag[] { NewDicomTag(0x00540220) })); Assert.AreEqual(path.ToString(), "(0054,0220)"); ((PathTest)path).SetPath(new List<DicomTag>(new DicomTag[] { NewDicomTag(0x00540220), NewDicomTag(0x00540222) })); Assert.AreEqual(path.ToString(), "(0054,0220)\\(0054,0222)"); ((PathTest)path).SetPath(new List<DicomTag>(new DicomTag[] { NewDicomTag(0x00540220), NewDicomTag(0x00540222), NewDicomTag(0x00100022) })); Assert.AreEqual(path.ToString(), "(0054,0220)\\(0054,0222)\\(0010,0022)"); path = new DicomTagPath(new uint[] { 0x00540220, 0x00540222 }); Assert.AreEqual(path.ToString(), "(0054,0220)\\(0054,0222)"); path = new DicomTagPath(new uint[] { 0x00540220, 0x00540222, 0x00100010 }); Assert.AreEqual(path.ToString(), "(0054,0220)\\(0054,0222)\\(0010,0010)"); } private DicomTag NewDicomTag(ushort group, ushort element) { return new DicomTag(DicomTag.GetTagValue(group, element), "Throwaway Tag", "ThrowawayTag", DicomVr.UNvr, false, 1, uint.MaxValue, false); } private DicomTag NewDicomTag(uint tag) { return new DicomTag(tag, "Throwaway Tag", "ThrowawayTag", DicomVr.UNvr, false, 1, uint.MaxValue, false); } } } #endif
Ext.define("Compass.ErpApp.Shared.Crm.PartyDetailsPanel", { extend: "Ext.panel.Panel", alias: 'widget.<API key>', cls: '<API key>', layout: 'border', items: [], contactWidgetXtypes: [ 'phonenumbergrid', 'emailaddressgrid', 'postaladdressgrid' ], /** * @cfg {Array} additionalTabs * Array of additional tab panels to add. */ additionalTabs: [], /** * @cfg {Int} partyId * Id of party being edited. */ partyId: null, /** * @cfg {Array | Object} partyRelationships * Party Relationships to include in the details of this party, is an config object with the following options * * @param {String} title * title of tab * * @param {String} relationshipType * relationship type internal_identifier * * @param {String} <API key> {from | to} * if we are getting the to or from side of relationships * * @param {String} toRoleType * RoleType internal_identifier for to side * * @param {String} fromRoleType * RoleType internal_identifier for from side * * @param {String} allowedPartyType * Party type that can be created {Both | Individual | Organization}. * * @param {Array | Object} partyRelationships * * @example * { title: 'Employees', relationshipType: 'employee_customer', toRoleType: 'customer', fromRoleType: 'employee', allowedPartyType: 'Individual', partyRelationships: [ { title: 'Family', relationshipType: '<API key>', toRoleType: 'employee', fromRoleType: 'family_member', allowedPartyType: 'Individual' } ] } */ partyRelationships: [], /** * @cfg {Array} contactPurposes * Array of contactPurposes that can be added to a contact. * * @example * { * fieldLabel: 'Default', * internalIdentifier: 'default' * } */ contactPurposes: [ { fieldLabel: 'Default', internalIdentifier: 'default' } ], /** * @cfg {String} <API key> * Title of contact purposes fieldset. */ <API key>: 'Contact Purpose', initComponent: function () { var me = this, tabPanels = []; me.addEvents( /* * @event contactcreated * Fires when a contact is created * @param {Compass.ErpApp.Shared.Crm.PartyDetailsPanel} this * @param {String} ContactType {PhoneNumber, PostalAddress, EmailAddress} * @param {Record} record */ 'contactcreated', /* * @event contactupdated * Fires when a contact is updated * @param {Compass.ErpApp.Shared.Crm.PartyDetailsPanel} this * @param {String} ContactType {PhoneNumber, PostalAddress, EmailAddress} * @param {Record} record */ 'contactupdated', /* * @event contactdestroyed * Fires when a contact is destroyed * @param {Compass.ErpApp.Shared.Crm.PartyDetailsPanel} this * @param {String} ContactType {PhoneNumber, PostalAddress, EmailAddress} * @param {Record} record */ 'contactdestroyed' ); contactsPanel = Ext.create('widget.panel', { title: 'Contacts', layout: 'border', itemId: 'contactsContainer', items: [ { xtype: 'panel', style:{ borderRight: 'solid 2px black' }, header: false, collapsible: true, region: 'west', width: 155, items: Ext.create('widget.dataview', { autoScroll: true, store: Ext.create('Ext.data.SimpleStore', { fields: ['title', 'xtype', 'iconSrc'], data: [ ['Phone Numbers', 'phonenumbergrid', '/assets/icons/phone/phone_16x16.png'], ['Email Addresses', 'emailaddressgrid', '/assets/icons/mail/mail_16x16.png'], ['Postal Addressses', 'postaladdressgrid', '/assets/icons/home/home_16x16.png'] ] }), selModel: { mode: 'SINGLE', listeners: { selectionchange: function (dataView, selection) { if (selection) { selection = selection.first(); var <API key> = me.down('#contactsContainer').down('#<API key>'), selectedContact = <API key>.down(selection.data.xtype); <API key>.layout.setActiveItem(selectedContact); } } } }, listeners: { viewready: function (dataView) { dataView.getSelectionModel().select(dataView.store.first()); } }, trackOver: true, cls: 'crm-contacts-list', itemSelector: '.<API key>', overItemCls: '<API key>', tpl: '<tpl for="."><img class="<API key>" src="{iconSrc}" /><div class="<API key>">{title}</div></tpl>' }) }, { xtype: 'panel', flex: 1, itemId: '<API key>', cls: '<API key>', region: 'center', layout: 'card', items: [ { xtype: 'phonenumbergrid', <API key>: 'Use Phone Number for:', contactPurposes: me.contactPurposes, partyId: me.partyId, listeners: { contactcreated: {fn: me.contactCreated, scope: me}, contactupdated: {fn: me.contactUpdated, scope: me}, contactdestroyed: {fn: me.contactDestroyed, scope: me} } }, { xtype: 'emailaddressgrid', <API key>: 'Use Email for:', contactPurposes: me.contactPurposes, partyId: me.partyId, listeners: { contactcreated: {fn: me.contactCreated, scope: me}, contactupdated: {fn: me.contactUpdated, scope: me}, contactdestroyed: {fn: me.contactDestroyed, scope: me} } }, { xtype: 'postaladdressgrid', <API key>: 'Use Address for:', contactPurposes: me.contactPurposes, partyId: me.partyId, listeners: { contactcreated: {fn: me.contactCreated, scope: me}, contactupdated: {fn: me.contactUpdated, scope: me}, contactdestroyed: {fn: me.contactDestroyed, scope: me} } } ] } ] }); tabPanels.push(contactsPanel); tabPanels.push({xtype: 'shared_notesgrid', recordType: 'Party', recordId: me.partyId}); me.partyDetailsPanel = Ext.create('widget.panel', { itemId: 'partyDetails', html: 'Party Details', border: false, frame: false, region: 'north', bodyStyle: '<API key>: 5px; <API key>: 5px;', height: 200, header: false, split: true, collapsible: true, autoScroll: true }); Ext.each(me.partyRelationships, function (partyRelationship) { tabPanels.push({ xtype: 'crmpartygrid', title: partyRelationship.title, contactPurposes: partyRelationship.contactPurposes || [{fieldLabel: 'Default',internalIdentifier: 'default'}], formFields: partyRelationship.formFields || 'none', securityRoles: partyRelationship.securityRoles || [], allowedPartyType: partyRelationship.allowedPartyType || 'Both', addBtnDescription: partyRelationship.addBtnDescription || ('Add ' + Ext.String.capitalize(partyRelationship.fromRoleType)), searchDescription: 'Search ' + partyRelationship.title, toRole: partyRelationship.toRoleType, toPartyId: me.partyId, <API key>: partyRelationship.relationshipType, partyRole: partyRelationship.fromRoleType, canAddParty: partyRelationship.canAddParty || true, canEditParty: partyRelationship.canEditParty || true, canDeleteParty: partyRelationship.canDeleteParty || true, partyRelationships: partyRelationship.partyRelationships || [], listeners: { partycreated: function (comp, partyId) { this.store.load(); }, partyupdated: function (comp, partyId) { this.store.load(); } } }); }); Ext.each(me.additionalTabs, function (tab) { // Pass party id to each additional tab... Ext.apply(tab, {partyId: me.partyId}); tabPanels.push(tab); }); me.<API key> = Ext.create('widget.tabpanel', { //flex: 1, //height: 400, region: 'center', items: tabPanels }); me.items = [me.partyDetailsPanel, me.<API key>]; this.callParent(arguments); }, contactCreated: function (comp, contactType, record) { var me = this; me.fireEvent('contactcreated', me, contactType, record); me.loadDetails(); }, contactUpdated: function (comp, contactType, record) { var me = this; me.fireEvent('contactupdated', me, contactType, record); me.loadDetails(); }, contactDestroyed: function (comp, contactType, record) { var me = this; me.fireEvent('contactdestroyed', me, contactType, record); me.loadDetails(); }, loadDetails: function () { var me = this, partyDetails = me.down('#partyDetails'); var myMask = new Ext.LoadMask(partyDetails, {msg: "Please wait..."}); myMask.show(); // Load html of party Ext.Ajax.request({ url: '/erp_app/organizer/crm/parties/' + me.partyId + '/details', disableCaching: false, method: 'GET', success: function (response) { myMask.hide(); partyDetails.update(response.responseText); } }); }, loadParty: function () { var me = this, tabPanel = me.down('tabpanel'); me.loadDetails(); // Load contact stores for (i = 0; i < me.contactWidgetXtypes.length; i += 1) { var widget = tabPanel.down(me.contactWidgetXtypes[i]); if (!Ext.isEmpty(widget)) { widget.store.load(); } } } });
d = {"k1":1, "k2":"valore", 3:"val3", "quattro":4} for x in d.values(): print(x) print(" ") for x in d.keys(): print(x) print(" ") for x in d.items(): print(x) print(x[0], x[1])
CREATE VIEW [DwhDev].[_Knot] AS SELECT S.version, S.activation, Nodeset.knot.value('concat(@mnemonic, "_", @descriptor)', 'nvarchar(max)') as [name], Nodeset.knot.value('metadata[1]/@capsule', 'nvarchar(max)') as [capsule], Nodeset.knot.value('@mnemonic', 'nvarchar(max)') as [mnemonic], Nodeset.knot.value('@descriptor', 'nvarchar(max)') as [descriptor], Nodeset.knot.value('@identity', 'nvarchar(max)') as [identity], Nodeset.knot.value('metadata[1]/@generator', 'nvarchar(max)') as [generator], Nodeset.knot.value('@dataRange', 'nvarchar(max)') as [dataRange], isnull(Nodeset.knot.value('metadata[1]/@checksum', 'nvarchar(max)'), 'false') as [checksum], isnull(Nodeset.knot.value('metadata[1]/@equivalent', 'nvarchar(max)'), 'false') as [equivalent] FROM [DwhDev].[_Schema] S CROSS APPLY S.[schema].nodes('/schema/knot') as Nodeset(knot) WHERE S.[version] = (SELECT MAX([version]) FROM [DwhDev].[_Schema]);
#include "biosig_writer.h" #include "<API key>.h" namespace sigviewer { <API key>(gdf, BioSigWriter); BioSigWriter::BioSigWriter () : target_type_ (GDF) { <API key>.insert(GDF1); <API key>.insert(GDF); } BioSigWriter::BioSigWriter (FileFormat target_type, QString new_file_path) : target_type_ (target_type), new_file_path_ (new_file_path) { // nothing to do here } QPair<FileSignalWriter*, QString> BioSigWriter::createInstance (QString const& file_path) { BioSigWriter* writer (new BioSigWriter); writer->new_file_path_ = file_path; return QPair<FileSignalWriter*, QString> (writer, ""); } bool BioSigWriter::<API key> () const { return <API key>.count(target_type_) > 0; } QString BioSigWriter::<API key> (QSharedPointer<EventManager const> event_manager, std::set<EventType> const& types) { if (<API key>.count(target_type_) == 0) return QObject::tr("Cannot write events to this file type!"); QList<EventID> events; foreach (EventType type, types) events.append(event_manager->getEvents(type)); unsigned number_events = events.size(); qDebug () << "number_events = " <<number_events; qDebug () << "event_manager->getNumberOfEvents() = " << event_manager->getNumberOfEvents(); HDRTYPE* header = constructHDR (0, number_events); qDebug () << "BioSigWriter::<API key> to " << new_file_path_; header = sopen (new_file_path_.toStdString().c_str(), "r", header); header->EVENT.SampleRate = event_manager->getSampleRate(); header->EVENT.N = number_events; header->EVENT.TYP = (decltype(header->EVENT.TYP)) realloc(header->EVENT.TYP,number_events * sizeof(decltype(*header->EVENT.TYP))); header->EVENT.POS = (decltype(header->EVENT.POS)) realloc(header->EVENT.POS,number_events * sizeof(decltype(*header->EVENT.POS))); header->EVENT.CHN = (decltype(header->EVENT.CHN)) realloc(header->EVENT.CHN,number_events * sizeof(decltype(*header->EVENT.CHN))); header->EVENT.DUR = (decltype(header->EVENT.DUR)) realloc(header->EVENT.DUR,number_events * sizeof(decltype(*header->EVENT.DUR))); for (unsigned index = 0; index < number_events; index++) { QSharedPointer<SignalEvent const> event = event_manager->getEvent(events[index]); if (event->getChannel() == UNDEFINED_CHANNEL) header->EVENT.CHN[index] = 0; else header->EVENT.CHN[index] = event->getChannel() + 1; header->EVENT.TYP[index] = event->getType (); header->EVENT.POS[index] = event->getPosition(); header->EVENT.DUR[index] = event->getDuration(); } int error = <API key> (header); if (error) QMessageBox::critical(0, "Events not saved!!!", QString::number(error)); destructHDR (header); return ""; } QString BioSigWriter::save (QSharedPointer<FileContext const> file_context, std::set<EventType> const& types) { QString source_file_path = file_context->getFilePathAndName(); HDRTYPE* read_header = sopen (source_file_path.toStdString().c_str(), "r", NULL); uint32 read_data_size = read_header->NS * read_header->NRec * read_header->SPR; biosig_data_type* read_data = new biosig_data_type[read_data_size]; sread (read_data, 0, read_data_size, read_header); read_header->TYPE = target_type_; if (target_type_ == GDF) read_header->VERSION = 2; HDRTYPE* write_header = sopen (new_file_path_.toStdString().c_str(), "w", read_header); qDebug() << "write NELEM = " << swrite (read_data, read_header->NRec, write_header); delete[] read_data; sclose(write_header); sclose(read_header); destructHDR (write_header); if (<API key>.count(target_type_)) <API key> (file_context->getEventManager (), types); return ""; } }
#include "AP_GPS.h" #include <AP_Common/AP_Common.h> #include <AP_HAL/AP_HAL.h> #include <AP_Math/AP_Math.h> #include <AP_Notify/AP_Notify.h> #include <GCS_MAVLink/GCS.h> #include <AP_BoardConfig/AP_BoardConfig.h> #include <AP_RTC/AP_RTC.h> #include <climits> #include "AP_GPS_NOVA.h" #include "AP_GPS_ERB.h" #include "AP_GPS_GSOF.h" #include "AP_GPS_MTK.h" #include "AP_GPS_MTK19.h" #include "AP_GPS_NMEA.h" #include "AP_GPS_SBF.h" #include "AP_GPS_SBP.h" #include "AP_GPS_SBP2.h" #include "AP_GPS_SIRF.h" #include "AP_GPS_UBLOX.h" #include "AP_GPS_MAV.h" #include "AP_GPS_MSP.h" #include "AP_GPS_ExternalAHRS.h" #include "GPS_Backend.h" #if <API key> #include <AP_CANManager/AP_CANManager.h> #include <AP_UAVCAN/AP_UAVCAN.h> #include "AP_GPS_UAVCAN.h" #endif #include <AP_AHRS/AP_AHRS.h> #include <AP_Logger/AP_Logger.h> #define <API key> 127 #ifndef GPS_MAX_RATE_MS #define GPS_MAX_RATE_MS 200 // maximum value of rate_ms (i.e. slowest update rate) is 5hz or 200ms #endif #define GPS_BAUD_TIME_MS 1200 #define GPS_TIMEOUT_MS 4000u // defines used to specify the mask position for use of different accuracy metrics in the blending algorithm #define <API key> 1 #define <API key> 2 #define <API key> 4 #define <API key> 10 #ifndef <API key> #define <API key> 1 #endif extern const AP_HAL::HAL &hal; // baudrates to try to detect GPSes with const uint32_t AP_GPS::_baudrates[] = {9600U, 115200U, 4800U, 19200U, 38400U, 57600U, 230400U, 460800U}; // initialisation blobs to send to the GPS to try to get it into the // right mode const char AP_GPS::<API key>[] = <API key> MTK_SET_BINARY SIRF_SET_BINARY; AP_GPS *AP_GPS::_singleton; // table of user settable parameters const AP_Param::GroupInfo AP_GPS::var_info[] = { // @Param: _TYPE // @DisplayName: 1st GPS type // @Description: GPS type of 1st GPS // @Values: 0:None,1:AUTO,2:uBlox,3:MTK,4:MTK19,5:NMEA,6:SiRF,7:HIL,8:SwiftNav,9:UAVCAN,10:SBF,11:GSOF,13:ERB,14:MAV,15:NOVA,16:HemisphereNMEA,17:<API key>,18:<API key>,19:MSP,20:AllyStar,21:ExternalAHRS // @RebootRequired: True // @User: Advanced AP_GROUPINFO("_TYPE", 0, AP_GPS, _type[0], <API key>), #if GPS_MAX_RECEIVERS > 1 // @Param: _TYPE2 // @DisplayName: 2nd GPS type // @Description: GPS type of 2nd GPS // @Values: 0:None,1:AUTO,2:uBlox,3:MTK,4:MTK19,5:NMEA,6:SiRF,7:HIL,8:SwiftNav,9:UAVCAN,10:SBF,11:GSOF,13:ERB,14:MAV,15:NOVA,16:HemisphereNMEA,17:<API key>,18:<API key>,19:MSP,20:AllyStar,21:ExternalAHRS // @RebootRequired: True // @User: Advanced AP_GROUPINFO("_TYPE2", 1, AP_GPS, _type[1], 0), #endif // @Param: _NAVFILTER // @DisplayName: Navigation filter setting // @Description: Navigation filter engine setting // @Values: 0:Portable,2:Stationary,3:Pedestrian,4:Automotive,5:Sea,6:Airborne1G,7:Airborne2G,8:Airborne4G // @User: Advanced AP_GROUPINFO("_NAVFILTER", 2, AP_GPS, _navfilter, <API key>), #if GPS_MAX_RECEIVERS > 1 // @Param: _AUTO_SWITCH // @DisplayName: Automatic Switchover Setting // @Description: Automatic switchover to GPS reporting best lock, 1:UseBest selects the GPS with highest status, if both are equal the GPS with highest satellite count is used 4:Use primary if 3D fix or better, will revert to 'UseBest' behaviour if 3D fix is lost on primary // @Values: 0:Use primary, 1:UseBest, 2:Blend, 4:Use primary if 3D fix or better // @User: Advanced AP_GROUPINFO("_AUTO_SWITCH", 3, AP_GPS, _auto_switch, (int8_t)GPSAutoSwitch::USE_BEST), #endif // @Param: _MIN_DGPS // @DisplayName: Minimum Lock Type Accepted for DGPS // @Description: Sets the minimum type of differential GPS corrections required before allowing to switch into DGPS mode. // @Values: 0:Any,50:FloatRTK,100:IntegerRTK // @User: Advanced // @RebootRequired: True AP_GROUPINFO("_MIN_DGPS", 4, AP_GPS, _min_dgps, 100), // @Param: _SBAS_MODE // @DisplayName: SBAS Mode // @Description: This sets the SBAS (satellite based augmentation system) mode if available on this GPS. If set to 2 then the SBAS mode is not changed in the GPS. Otherwise the GPS will be reconfigured to enable/disable SBAS. Disabling SBAS may be worthwhile in some parts of the world where an SBAS signal is available but the baseline is too long to be useful. // @Values: 0:Disabled,1:Enabled,2:NoChange // @User: Advanced AP_GROUPINFO("_SBAS_MODE", 5, AP_GPS, _sbas_mode, 2), // @Param: _MIN_ELEV // @DisplayName: Minimum elevation // @Description: This sets the minimum elevation of satellites above the horizon for them to be used for navigation. Setting this to -100 leaves the minimum elevation set to the GPS modules default. // @Range: -100 90 // @Units: deg // @User: Advanced AP_GROUPINFO("_MIN_ELEV", 6, AP_GPS, _min_elevation, -100), // @Param: _INJECT_TO // @DisplayName: Destination for GPS_INJECT_DATA MAVLink packets // @Description: The GGS can send raw serial packets to inject data to multiple GPSes. // @Values: 0:send to first GPS,1:send to 2nd GPS,127:send to all // @User: Advanced AP_GROUPINFO("_INJECT_TO", 7, AP_GPS, _inject_to, <API key>), // @Param: _SBP_LOGMASK // @DisplayName: Swift Binary Protocol Logging Mask // @Description: Masked with the SBP msg_type field to determine whether SBR1/SBR2 data is logged // @Values: 0:None (0x0000),-1:All (0xFFFF),-256:External only (0xFF00) // @User: Advanced AP_GROUPINFO("_SBP_LOGMASK", 8, AP_GPS, _sbp_logmask, -256), // @Param: _RAW_DATA // @DisplayName: Raw data logging // @Description: Handles logging raw data; on uBlox chips that support raw data this will log RXM messages into logger; on Septentrio this will log on the equipment's SD card and when set to 2, the autopilot will try to stop logging after disarming and restart after arming // @Values: 0:Ignore,1:Always log,2:Stop logging when disarmed (SBF only),5:Only log every five samples (uBlox only) // @RebootRequired: True // @User: Advanced AP_GROUPINFO("_RAW_DATA", 9, AP_GPS, _raw_data, 0), // @Param: _GNSS_MODE // @DisplayName: GNSS system configuration // @Description: Bitmask for what GNSS system to use on the first GPS (all unchecked or zero to leave GPS as configured) // @Bitmask: 0:GPS,1:SBAS,2:Galileo,3:Beidou,4:IMES,5:QZSS,6:GLONASS // @User: Advanced AP_GROUPINFO("_GNSS_MODE", 10, AP_GPS, _gnss_mode[0], 0), // @Param: _SAVE_CFG // @DisplayName: Save GPS configuration // @Description: Determines whether the configuration for this GPS should be written to non-volatile memory on the GPS. Currently working for UBlox 6 series and above. // @Values: 0:Do not save config,1:Save config,2:Save only when needed // @User: Advanced AP_GROUPINFO("_SAVE_CFG", 11, AP_GPS, _save_config, 2), #if GPS_MAX_RECEIVERS > 1 // @Param: _GNSS_MODE2 // @DisplayName: GNSS system configuration // @Description: Bitmask for what GNSS system to use on the second GPS (all unchecked or zero to leave GPS as configured) // @Bitmask: 0:GPS,1:SBAS,2:Galileo,3:Beidou,4:IMES,5:QZSS,6:GLONASS // @User: Advanced AP_GROUPINFO("_GNSS_MODE2", 12, AP_GPS, _gnss_mode[1], 0), #endif // @Param: _AUTO_CONFIG // @DisplayName: Automatic GPS configuration // @Description: Controls if the autopilot should automatically configure the GPS based on the parameters and default settings // @Values: 0:Disables automatic configuration,1:Enable automatic configuration // @User: Advanced AP_GROUPINFO("_AUTO_CONFIG", 13, AP_GPS, _auto_config, 1), // @Param: _RATE_MS // @DisplayName: GPS update rate in milliseconds // @Description: Controls how often the GPS should provide a position update. Lowering below 5Hz(default) is not allowed. Raising the rate above 5Hz usually provides little benefit and for some GPS (eg Ublox M9N) can severely impact performance. // @Units: ms // @Values: 100:10Hz,125:8Hz,200:5Hz // @Range: 50 200 // @User: Advanced AP_GROUPINFO("_RATE_MS", 14, AP_GPS, _rate_ms[0], 200), #if GPS_MAX_RECEIVERS > 1 // @Param: _RATE_MS2 // @DisplayName: GPS 2 update rate in milliseconds // @Description: Controls how often the GPS should provide a position update. Lowering below 5Hz(default) is not allowed. Raising the rate above 5Hz usually provides little benefit and for some GPS (eg Ublox M9N) can severely impact performance. // @Units: ms // @Values: 100:10Hz,125:8Hz,200:5Hz // @Range: 50 200 // @User: Advanced AP_GROUPINFO("_RATE_MS2", 15, AP_GPS, _rate_ms[1], 200), #endif // @Param: _POS1_X // @DisplayName: Antenna X position offset // @Description: X position of the first GPS antenna in body frame. Positive X is forward of the origin. Use antenna phase centroid location if provided by the manufacturer. // @Units: m // @Range: -5 5 // @Increment: 0.01 // @User: Advanced // @Param: _POS1_Y // @DisplayName: Antenna Y position offset // @Description: Y position of the first GPS antenna in body frame. Positive Y is to the right of the origin. Use antenna phase centroid location if provided by the manufacturer. // @Units: m // @Range: -5 5 // @Increment: 0.01 // @User: Advanced // @Param: _POS1_Z // @DisplayName: Antenna Z position offset // @Description: Z position of the first GPS antenna in body frame. Positive Z is down from the origin. Use antenna phase centroid location if provided by the manufacturer. // @Units: m // @Range: -5 5 // @Increment: 0.01 // @User: Advanced AP_GROUPINFO("_POS1", 16, AP_GPS, _antenna_offset[0], 0.0f), #if GPS_MAX_RECEIVERS > 1 // @Param: _POS2_X // @DisplayName: Antenna X position offset // @Description: X position of the second GPS antenna in body frame. Positive X is forward of the origin. Use antenna phase centroid location if provided by the manufacturer. // @Units: m // @Range: -5 5 // @Increment: 0.01 // @User: Advanced // @Param: _POS2_Y // @DisplayName: Antenna Y position offset // @Description: Y position of the second GPS antenna in body frame. Positive Y is to the right of the origin. Use antenna phase centroid location if provided by the manufacturer. // @Units: m // @Range: -5 5 // @Increment: 0.01 // @User: Advanced // @Param: _POS2_Z // @DisplayName: Antenna Z position offset // @Description: Z position of the second GPS antenna in body frame. Positive Z is down from the origin. Use antenna phase centroid location if provided by the manufacturer. // @Units: m // @Range: -5 5 // @Increment: 0.01 // @User: Advanced AP_GROUPINFO("_POS2", 17, AP_GPS, _antenna_offset[1], 0.0f), #endif // @Param: _DELAY_MS // @DisplayName: GPS delay in milliseconds // @Description: Controls the amount of GPS measurement delay that the autopilot compensates for. Set to zero to use the default delay for the detected GPS type. // @Units: ms // @Range: 0 250 // @User: Advanced // @RebootRequired: True AP_GROUPINFO("_DELAY_MS", 18, AP_GPS, _delay_ms[0], 0), #if GPS_MAX_RECEIVERS > 1 // @Param: _DELAY_MS2 // @DisplayName: GPS 2 delay in milliseconds // @Description: Controls the amount of GPS measurement delay that the autopilot compensates for. Set to zero to use the default delay for the detected GPS type. // @Units: ms // @Range: 0 250 // @User: Advanced // @RebootRequired: True AP_GROUPINFO("_DELAY_MS2", 19, AP_GPS, _delay_ms[1], 0), #endif #if defined(<API key>) // @Param: _BLEND_MASK // @DisplayName: Multi GPS Blending Mask // @Description: Determines which of the accuracy measures Horizontal position, Vertical Position and Speed are used to calculate the weighting on each GPS receiver when soft switching has been selected by setting GPS_AUTO_SWITCH to 2(Blend) // @Bitmask: 0:Horiz Pos,1:Vert Pos,2:Speed // @User: Advanced AP_GROUPINFO("_BLEND_MASK", 20, AP_GPS, _blend_mask, 5), // @Param: _BLEND_TC // @DisplayName: Blending time constant // @Description: Controls the slowest time constant applied to the calculation of GPS position and height offsets used to adjust different GPS receivers for steady state position differences. // @Units: s // @Range: 5.0 30.0 // @User: Advanced AP_GROUPINFO("_BLEND_TC", 21, AP_GPS, _blend_tc, 10.0f), #endif #if GPS_MOVING_BASELINE // @Param: _DRV_OPTIONS // @DisplayName: driver options // @Description: Additional backend specific options // @Bitmask: 0:Use UART2 for moving baseline on ublox,1:Use base station for GPS yaw on SBF // @User: Advanced AP_GROUPINFO("_DRV_OPTIONS", 22, AP_GPS, _driver_options, 0), #endif // @Param: _COM_PORT // @DisplayName: GPS physical COM port // @Description: The physical COM port on the connected device, currently only applies to SBF GPS // @Range: 0 10 // @Increment: 1 // @User: Advanced // @RebootRequired: True AP_GROUPINFO("_COM_PORT", 23, AP_GPS, _com_port[0], <API key>), #if GPS_MAX_RECEIVERS > 1 // @Param: _COM_PORT2 // @DisplayName: GPS physical COM port // @Description: The physical COM port on the connected device, currently only applies to SBF GPS // @Range: 0 10 // @Increment: 1 // @User: Advanced // @RebootRequired: True AP_GROUPINFO("_COM_PORT2", 24, AP_GPS, _com_port[1], <API key>), #endif #if GPS_MOVING_BASELINE // @Group: _MB1_ // @Path: MovingBase.cpp AP_SUBGROUPINFO(mb_params[0], "_MB1_", 25, AP_GPS, MovingBase), #if GPS_MAX_RECEIVERS > 1 // @Group: _MB2_ // @Path: MovingBase.cpp AP_SUBGROUPINFO(mb_params[1], "_MB2_", 26, AP_GPS, MovingBase), #endif // GPS_MAX_RECEIVERS > 1 #endif // GPS_MOVING_BASELINE #if GPS_MAX_RECEIVERS > 1 // @Param: _PRIMARY // @DisplayName: Primary GPS // @Description: This GPS will be used when GPS_AUTO_SWITCH is 0 and used preferentially with GPS_AUTO_SWITCH = 4. // @Increment: 1 // @Values: 0:FirstGPS, 1:SecondGPS // @User: Advanced AP_GROUPINFO("_PRIMARY", 27, AP_GPS, _primary, 0), #endif #if GPS_MAX_RECEIVERS > 1 && <API key> // @Param: _CAN_NODEID1 // @DisplayName: GPS Node ID 1 // @Description: GPS Node id for discovered first. // @ReadOnly: True // @User: Advanced AP_GROUPINFO("_CAN_NODEID1", 28, AP_GPS, _node_id[0], 0), // @Param: _CAN_NODEID2 // @DisplayName: GPS Node ID 2 // @Description: GPS Node id for discovered second. // @ReadOnly: True // @User: Advanced AP_GROUPINFO("_CAN_NODEID2", 29, AP_GPS, _node_id[1], 0), // @Param: 1_CAN_OVRIDE // @DisplayName: First UAVCAN GPS NODE ID // @Description: GPS Node id for first GPS. If 0 the gps will be automatically selected on first come basis. // @User: Advanced AP_GROUPINFO("1_CAN_OVRIDE", 30, AP_GPS, _override_node_id[0], 0), // @Param: 2_CAN_OVRIDE // @DisplayName: Second UAVCAN GPS NODE ID // @Description: GPS Node id for second GPS. If 0 the gps will be automatically selected on first come basis. // @User: Advanced AP_GROUPINFO("2_CAN_OVRIDE", 31, AP_GPS, _override_node_id[1], 0), #endif AP_GROUPEND }; // constructor AP_GPS::AP_GPS() { static_assert((sizeof(<API key>) * (CHAR_BIT + 2)) < (4800 * GPS_BAUD_TIME_MS * 1e-3), "GPS initilisation blob is too large to be completely sent before the baud rate changes"); AP_Param::<API key>(this, var_info); if (_singleton != nullptr) { AP_HAL::panic("AP_GPS must be singleton"); } _singleton = this; } // return true if a specific type of GPS uses a UART bool AP_GPS::needs_uart(GPS_Type type) const { switch (type) { case GPS_TYPE_NONE: case GPS_TYPE_HIL: case GPS_TYPE_UAVCAN: case GPS_TYPE_MAV: case GPS_TYPE_MSP: case <API key>: return false; default: break; } return true; } Startup initialisation. void AP_GPS::init(const AP_SerialManager& serial_manager) { // Set new primary param based on old auto_switch use second option if ((_auto_switch.get() == 3) && !_primary.configured()) { _primary.set_and_save(1); _auto_switch.set_and_save(0); } // search for serial ports with gps protocol uint8_t uart_idx = 0; for (uint8_t i=0; i<GPS_MAX_RECEIVERS; i++) { if (needs_uart((GPS_Type)_type[i].get())) { _port[i] = serial_manager.find_serial(AP_SerialManager::SerialProtocol_GPS, uart_idx); uart_idx++; } } <API key> = 0; // Initialise class variables used to do GPS blending _omega_lpf = 1.0f / constrain_float(_blend_tc, 5.0f, 30.0f); // prep the state instance fields for (uint8_t i = 0; i < GPS_MAX_INSTANCES; i++) { state[i].instance = i; } // sanity check update rate for (uint8_t i=0; i<GPS_MAX_RECEIVERS; i++) { if (_rate_ms[i] <= 0 || _rate_ms[i] > GPS_MAX_RATE_MS) { _rate_ms[i] = GPS_MAX_RATE_MS; } } } // return number of active GPS sensors. Note that if the first GPS // is not present but the 2nd is then we return 2. Note that a blended // GPS solution is treated as an additional sensor. uint8_t AP_GPS::num_sensors(void) const { if (!_output_is_blended) { return num_instances; } else { return num_instances+1; } } bool AP_GPS::speed_accuracy(uint8_t instance, float &sacc) const { if (state[instance].have_speed_accuracy) { sacc = state[instance].speed_accuracy; return true; } return false; } bool AP_GPS::horizontal_accuracy(uint8_t instance, float &hacc) const { if (state[instance].<API key>) { hacc = state[instance].horizontal_accuracy; return true; } return false; } bool AP_GPS::vertical_accuracy(uint8_t instance, float &vacc) const { if (state[instance].<API key>) { vacc = state[instance].vertical_accuracy; return true; } return false; } /** convert GPS week and milliseconds to unix epoch in milliseconds */ uint64_t AP_GPS::time_epoch_convert(uint16_t gps_week, uint32_t gps_ms) { uint64_t fix_time_ms = UNIX_OFFSET_MSEC + gps_week * AP_MSEC_PER_WEEK + gps_ms; return fix_time_ms; } /** calculate current time since the unix epoch in microseconds */ uint64_t AP_GPS::time_epoch_usec(uint8_t instance) const { const GPS_State &istate = state[instance]; if (istate.last_gps_time_ms == 0 || istate.time_week == 0) { return 0; } uint64_t fix_time_ms = time_epoch_convert(istate.time_week, istate.time_week_ms); // add in the milliseconds since the last fix return (fix_time_ms + (AP_HAL::millis() - istate.last_gps_time_ms)) * 1000ULL; } /* send some more initialisation string bytes if there is room in the UART transmit buffer */ void AP_GPS::send_blob_start(uint8_t instance, const char *_blob, uint16_t size) { initblob_state[instance].blob = _blob; initblob_state[instance].remaining = size; } /* send some more initialisation string bytes if there is room in the UART transmit buffer */ void AP_GPS::send_blob_update(uint8_t instance) { // exit immediately if no uart for this instance if (_port[instance] == nullptr) { return; } // see if we can write some more of the initialisation blob if (initblob_state[instance].remaining > 0) { int16_t space = _port[instance]->txspace(); if (space > (int16_t)initblob_state[instance].remaining) { space = initblob_state[instance].remaining; } while (space > 0) { _port[instance]->write(*initblob_state[instance].blob); initblob_state[instance].blob++; space initblob_state[instance].remaining } } } /* run detection step for one GPS instance. If this finds a GPS then it will fill in drivers[instance] and change state[instance].status from NO_GPS to NO_FIX. */ void AP_GPS::detect_instance(uint8_t instance) { AP_GPS_Backend *new_gps = nullptr; struct detect_state *dstate = &detect_state[instance]; const uint32_t now = AP_HAL::millis(); state[instance].status = NO_GPS; state[instance].hdop = GPS_UNKNOWN_DOP; state[instance].vdop = GPS_UNKNOWN_DOP; switch (_type[instance]) { // user has to explicitly set the MAV type, do not use AUTO // do not try to detect the MAV type, assume it's there case GPS_TYPE_MAV: #ifndef HAL_BUILD_AP_PERIPH dstate->auto_detected_baud = false; // specified, not detected new_gps = new AP_GPS_MAV(*this, state[instance], nullptr); goto found_gps; #endif break; // user has to explicitly set the UAVCAN type, do not use AUTO case GPS_TYPE_UAVCAN: #if <API key> dstate->auto_detected_baud = false; // specified, not detected new_gps = AP_GPS_UAVCAN::probe(*this, state[instance]); goto found_gps; #endif return; // We don't do anything here if UAVCAN is not supported #if HAL_MSP_GPS_ENABLED case GPS_TYPE_MSP: dstate->auto_detected_baud = false; // specified, not detected new_gps = new AP_GPS_MSP(*this, state[instance], nullptr); goto found_gps; #endif #if <API key> case <API key>: dstate->auto_detected_baud = false; // specified, not detected new_gps = new AP_GPS_ExternalAHRS(*this, state[instance], nullptr); goto found_gps; #endif default: break; } if (_port[instance] == nullptr) { // UART not available return; } // all remaining drivers automatically cycle through baud rates to detect // the correct baud rate, and should have the selected baud broadcast dstate->auto_detected_baud = true; // don't build the less common GPS drivers on F1 AP_Periph #if !defined(HAL_BUILD_AP_PERIPH) || !defined(STM32F1) switch (_type[instance]) { // by default the sbf/trimble gps outputs no data on its port, until configured. case GPS_TYPE_SBF: new_gps = new AP_GPS_SBF(*this, state[instance], _port[instance]); break; case GPS_TYPE_GSOF: new_gps = new AP_GPS_GSOF(*this, state[instance], _port[instance]); break; case GPS_TYPE_NOVA: new_gps = new AP_GPS_NOVA(*this, state[instance], _port[instance]); break; default: break; } #endif // HAL_BUILD_AP_PERIPH if (now - dstate->last_baud_change_ms > GPS_BAUD_TIME_MS) { // try the next baud rate // incrementing like this will skip the first element in array of bauds // this is okay, and relied upon dstate->current_baud++; if (dstate->current_baud == ARRAY_SIZE(_baudrates)) { dstate->current_baud = 0; } uint32_t baudrate = _baudrates[dstate->current_baud]; _port[instance]->begin(baudrate); _port[instance]->set_flow_control(AP_HAL::UARTDriver::<API key>); dstate->last_baud_change_ms = now; if (_auto_config == <API key> && new_gps == nullptr) { if (_type[instance] == GPS_TYPE_HEMI) { send_blob_start(instance, <API key>, strlen(<API key>)); } else if ((_type[instance] == <API key> || _type[instance] == <API key>) && ((_driver_options.get() & AP_GPS_Backend::DriverOptions::UBX_MBUseUart2) == 0)) { // we use 460800 when doing moving baseline as we need // more bandwidth. We don't do this if using UART2, as // in that case the RTCMv3 data doesn't go over the // link to the flight controller static const char blob[] = <API key>; send_blob_start(instance, blob, sizeof(blob)); } else { send_blob_start(instance, <API key>, sizeof(<API key>)); } } } if (_auto_config == <API key> && new_gps == nullptr) { send_blob_update(instance); } while (initblob_state[instance].remaining == 0 && _port[instance]->available() > 0 && new_gps == nullptr) { uint8_t data = _port[instance]->read(); /* running a uBlox at less than 38400 will lead to packet corruption, as we can't receive the packets in the 200ms window for 5Hz fixes. The NMEA startup message should force the uBlox into 230400 no matter what rate it is configured for. */ if ((_type[instance] == GPS_TYPE_AUTO || _type[instance] == GPS_TYPE_UBLOX) && ((!_auto_config && _baudrates[dstate->current_baud] >= 38400) || _baudrates[dstate->current_baud] == 230400) && AP_GPS_UBLOX::_detect(dstate->ublox_detect_state, data)) { new_gps = new AP_GPS_UBLOX(*this, state[instance], _port[instance], GPS_ROLE_NORMAL); } const uint32_t <API key> = (_driver_options.get() & AP_GPS_Backend::DriverOptions::UBX_MBUseUart2)?230400:460800; if ((_type[instance] == <API key> || _type[instance] == <API key>) && _baudrates[dstate->current_baud] == <API key> && AP_GPS_UBLOX::_detect(dstate->ublox_detect_state, data)) { GPS_Role role; if (_type[instance] == <API key>) { role = GPS_ROLE_MB_BASE; } else { role = GPS_ROLE_MB_ROVER; } new_gps = new AP_GPS_UBLOX(*this, state[instance], _port[instance], role); } #ifndef HAL_BUILD_AP_PERIPH #if !<API key> // we drop the MTK drivers when building a small build as they are so rarely used // and are surprisingly large else if ((_type[instance] == GPS_TYPE_AUTO || _type[instance] == GPS_TYPE_MTK19) && AP_GPS_MTK19::_detect(dstate->mtk19_detect_state, data)) { new_gps = new AP_GPS_MTK19(*this, state[instance], _port[instance]); } else if ((_type[instance] == GPS_TYPE_AUTO || _type[instance] == GPS_TYPE_MTK) && AP_GPS_MTK::_detect(dstate->mtk_detect_state, data)) { new_gps = new AP_GPS_MTK(*this, state[instance], _port[instance]); } #endif else if ((_type[instance] == GPS_TYPE_AUTO || _type[instance] == GPS_TYPE_SBP) && AP_GPS_SBP2::_detect(dstate->sbp2_detect_state, data)) { new_gps = new AP_GPS_SBP2(*this, state[instance], _port[instance]); } else if ((_type[instance] == GPS_TYPE_AUTO || _type[instance] == GPS_TYPE_SBP) && AP_GPS_SBP::_detect(dstate->sbp_detect_state, data)) { new_gps = new AP_GPS_SBP(*this, state[instance], _port[instance]); } #if !<API key> else if ((_type[instance] == GPS_TYPE_AUTO || _type[instance] == GPS_TYPE_SIRF) && AP_GPS_SIRF::_detect(dstate->sirf_detect_state, data)) { new_gps = new AP_GPS_SIRF(*this, state[instance], _port[instance]); } #endif else if ((_type[instance] == GPS_TYPE_AUTO || _type[instance] == GPS_TYPE_ERB) && AP_GPS_ERB::_detect(dstate->erb_detect_state, data)) { new_gps = new AP_GPS_ERB(*this, state[instance], _port[instance]); } else if ((_type[instance] == GPS_TYPE_NMEA || _type[instance] == GPS_TYPE_HEMI || _type[instance] == GPS_TYPE_ALLYSTAR) && AP_GPS_NMEA::_detect(dstate->nmea_detect_state, data)) { new_gps = new AP_GPS_NMEA(*this, state[instance], _port[instance]); } #endif // HAL_BUILD_AP_PERIPH if (new_gps) { goto found_gps; } } found_gps: if (new_gps != nullptr) { state[instance].status = NO_FIX; drivers[instance] = new_gps; timing[instance].<API key> = now; timing[instance].delta_time_ms = GPS_TIMEOUT_MS; new_gps->broadcast_gps_type(); } } AP_GPS::GPS_Status AP_GPS::<API key>(uint8_t instance) const { if (instance < GPS_MAX_RECEIVERS && drivers[instance] != nullptr) { return drivers[instance]-><API key>(); } return AP_GPS::GPS_OK_FIX_3D; } bool AP_GPS::should_log() const { #if HAL_LOGGING_ENABLED AP_Logger *logger = AP_Logger::get_singleton(); if (logger == nullptr) { return false; } if (_log_gps_bit == (uint32_t)-1) { return false; } if (!logger->should_log(_log_gps_bit)) { return false; } return true; #else return false; #endif } /* update one GPS instance. This should be called at 10Hz or greater */ void AP_GPS::update_instance(uint8_t instance) { if (_type[instance] == GPS_TYPE_HIL) { // in HIL, leave info alone return; } if (_type[instance] == GPS_TYPE_NONE) { // not enabled state[instance].status = NO_GPS; state[instance].hdop = GPS_UNKNOWN_DOP; state[instance].vdop = GPS_UNKNOWN_DOP; return; } if (locked_ports & (1U<<instance)) { // the port is locked by another driver return; } if (drivers[instance] == nullptr) { // we don't yet know the GPS type of this one, or it has timed // out and needs to be re-initialised detect_instance(instance); return; } if (_auto_config == <API key>) { send_blob_update(instance); } // we have an active driver for this instance bool result = drivers[instance]->read(); uint32_t tnow = AP_HAL::millis(); // if we did not get a message, and the idle timer of 2 seconds // has expired, re-initialise the GPS. This will cause GPS // detection to run again bool <API key> = false; if (!result) { if (tnow - timing[instance].<API key> > GPS_TIMEOUT_MS) { memset((void *)&state[instance], 0, sizeof(state[instance])); state[instance].instance = instance; state[instance].hdop = GPS_UNKNOWN_DOP; state[instance].vdop = GPS_UNKNOWN_DOP; timing[instance].<API key> = tnow; timing[instance].delta_time_ms = GPS_TIMEOUT_MS; // do not try to detect again if type is MAV or UAVCAN if (_type[instance] == GPS_TYPE_MAV || _type[instance] == GPS_TYPE_UAVCAN) { state[instance].status = NO_FIX; } else { // free the driver before we run the next detection, so we // don't end up with two allocated at any time delete drivers[instance]; drivers[instance] = nullptr; state[instance].status = NO_GPS; } // log this data as a "flag" that the GPS is no longer // valid (see PR#8144) <API key> = true; } } else { if (state[instance].uart_timestamp_ms != 0) { // set the timestamp for this messages based on // set_uart_timestamp() in backend, if available tnow = state[instance].uart_timestamp_ms; state[instance].uart_timestamp_ms = 0; } // delta will only be correct after parsing two messages timing[instance].delta_time_ms = tnow - timing[instance].<API key>; timing[instance].<API key> = tnow; // if GPS disabled for flight testing then don't update fix timing value if (state[instance].status >= GPS_OK_FIX_2D && !_force_disable_gps) { timing[instance].last_fix_time_ms = tnow; } <API key> = true; } #if GPS_MAX_RECEIVERS > 1 if (drivers[instance] && _type[instance] == <API key>) { // see if a moving baseline base has some RTCMv3 data // which we need to pass along to the rover const uint8_t *rtcm_data; uint16_t rtcm_len; if (drivers[instance]->get_RTCMV3(rtcm_data, rtcm_len)) { for (uint8_t i=0; i< GPS_MAX_RECEIVERS; i++) { if (i != instance && _type[i] == <API key>) { // pass the data to the rover inject_data(i, rtcm_data, rtcm_len); drivers[instance]->clear_RTCMV3(); break; } } } } #endif if (<API key>) { // keep count of delayed frames and average frame delay for health reporting const uint16_t gps_max_delta_ms = 245; // 200 ms (5Hz) + 45 ms buffer GPS_timing &t = timing[instance]; if (t.delta_time_ms > gps_max_delta_ms) { t.delayed_count++; } else { t.delayed_count = 0; } if (t.delta_time_ms < 2000) { if (t.average_delta_ms <= 0) { t.average_delta_ms = t.delta_time_ms; } else { t.average_delta_ms = 0.98f * t.average_delta_ms + 0.02f * t.delta_time_ms; } } } #if HAL_LOGGING_ENABLED if (<API key> && should_log()) { Write_GPS(instance); } #endif #ifndef HAL_BUILD_AP_PERIPH if (state[instance].status >= GPS_OK_FIX_3D) { const uint64_t now = time_epoch_usec(instance); if (now != 0) { AP::rtc().set_utc_usec(now, AP_RTC::SOURCE_GPS); } } #else (void)<API key>; #endif } /* update all GPS instances */ void AP_GPS::update(void) { WITH_SEMAPHORE(rsem); for (uint8_t i=0; i<GPS_MAX_RECEIVERS; i++) { update_instance(i); } // calculate number of instances for (uint8_t i=0; i<GPS_MAX_RECEIVERS; i++) { if (drivers[i] != nullptr) { num_instances = i+1; } } update_primary(); #ifndef HAL_BUILD_AP_PERIPH // update notify with gps status. We always base this on the primary_instance AP_Notify::flags.gps_status = state[primary_instance].status; AP_Notify::flags.gps_num_sats = state[primary_instance].num_sats; #endif } /* update primary GPS instance */ void AP_GPS::update_primary(void) { #if defined(<API key>) // if blending is requested, attempt to calculate weighting for each GPS if ((GPSAutoSwitch)_auto_switch.get() == GPSAutoSwitch::BLEND) { _output_is_blended = calc_blend_weights(); // adjust blend health counter if (!_output_is_blended) { <API key> = MIN(<API key>+<API key>, 100); } else if (<API key> > 0) { <API key> } // stop blending if unhealthy if (<API key> >= 50) { _output_is_blended = false; } } else { _output_is_blended = false; <API key> = 0; } if (_output_is_blended) { // Use the weighting to calculate blended GPS states calc_blended_state(); // set primary to the virtual instance primary_instance = <API key>; return; } // check the primary param is set to possible GPS int8_t primary_param = _primary.get(); if ((primary_param < 0) || (primary_param>=GPS_MAX_RECEIVERS)) { primary_param = 0; } // if primary is not enabled try first instance if (get_type(primary_param) == GPS_TYPE_NONE) { primary_param = 0; } if ((GPSAutoSwitch)_auto_switch.get() == GPSAutoSwitch::NONE) { // No switching of GPSs, always use the primary instance primary_instance = primary_param; return; } uint32_t now = AP_HAL::millis(); // special handling of RTK moving baseline pair. Always use the // base as the rover position is derived from the base, which // means the rover always has worse position and velocity than the // base. This overrides the normal logic which would select the // rover as it typically is in fix type 6 (RTK) whereas base is // usually fix type 3 for (uint8_t i=0; i<GPS_MAX_RECEIVERS; i++) { if (_type[i] == <API key> && _type[i^1] == <API key> && ((state[i].status >= GPS_OK_FIX_3D) || (state[i].status >= state[i^1].status))) { if (primary_instance != i) { <API key> = now; primary_instance = i; } // don't do any more switching logic. We don't want the // RTK status of the rover to cause a switch return; } } // handling switching away from blended GPS if (primary_instance == <API key>) { primary_instance = 0; for (uint8_t i=1; i<GPS_MAX_RECEIVERS; i++) { // choose GPS with highest state or higher number of satellites if ((state[i].status > state[primary_instance].status) || ((state[i].status == state[primary_instance].status) && (state[i].num_sats > state[primary_instance].num_sats))) { primary_instance = i; <API key> = now; } } return; } // Use primary if 3D fix or better if (((GPSAutoSwitch)_auto_switch.get() == GPSAutoSwitch::<API key>) && (state[primary_param].status >= GPS_OK_FIX_3D)) { // Primary GPS has a least a 3D fix, switch to it if necessary if (primary_instance != primary_param) { primary_instance = primary_param; <API key> = now; } return; } // handle switch between real GPSs for (uint8_t i=0; i<GPS_MAX_RECEIVERS; i++) { if (i == primary_instance) { continue; } if (state[i].status > state[primary_instance].status) { // we have a higher status lock, or primary is set to the blended GPS, change GPS primary_instance = i; <API key> = now; continue; } bool <API key> = (state[i].num_sats >= state[primary_instance].num_sats + 1); if (state[i].status == state[primary_instance].status && <API key>) { bool <API key> = (state[i].num_sats >= state[primary_instance].num_sats + 2); if ((<API key> && (now - <API key>) >= 20000) || (<API key> && (now - <API key>) >= 5000)) { // this GPS has more satellites than the // current primary, switch primary. Once we switch we will // then tend to stick to the new GPS as primary. We don't // want to switch too often as it will look like a // position shift to the controllers. primary_instance = i; <API key> = now; } } } #endif // <API key> } void AP_GPS::handle_gps_inject(const mavlink_message_t &msg) { <API key> packet; <API key>(&msg, &packet); if (packet.len > sizeof(packet.data)) { // invalid packet return; } <API key>(0, packet.data, packet.len); } /* pass along a mavlink message (for MAV type) */ void AP_GPS::handle_msg(const mavlink_message_t &msg) { switch (msg.msgid) { case <API key>: // pass data to de-fragmenter <API key>(msg); break; case <API key>: handle_gps_inject(msg); break; default: { uint8_t i; for (i=0; i<num_instances; i++) { if ((drivers[i] != nullptr) && (_type[i] != GPS_TYPE_NONE)) { drivers[i]->handle_msg(msg); } } break; } } } #if HAL_MSP_GPS_ENABLED void AP_GPS::handle_msp(const MSP::<API key> &pkt) { for (uint8_t i=0; i<num_instances; i++) { if (drivers[i] != nullptr && _type[i] == GPS_TYPE_MSP) { drivers[i]->handle_msp(pkt); } } } #endif // HAL_MSP_GPS_ENABLED #if <API key> void AP_GPS::handle_external(const AP_ExternalAHRS::gps_data_message_t &pkt) { for (uint8_t i=0; i<num_instances; i++) { if (drivers[i] != nullptr && _type[i] == <API key>) { drivers[i]->handle_external(pkt); } } } #endif // <API key> /** Lock a GPS port, preventing the GPS driver from using it. This can be used to allow a user to control a GPS port via the SERIAL_CONTROL protocol */ void AP_GPS::lock_port(uint8_t instance, bool lock) { if (instance >= GPS_MAX_RECEIVERS) { return; } if (lock) { locked_ports |= (1U<<instance); } else { locked_ports &= ~(1U<<instance); } } // Inject a packet of raw binary to a GPS void AP_GPS::inject_data(const uint8_t *data, uint16_t len) { //Support broadcasting to all GPSes. if (_inject_to == <API key>) { for (uint8_t i=0; i<GPS_MAX_RECEIVERS; i++) { if (_type[i] == <API key>) { // we don't externally inject to moving baseline rover continue; } inject_data(i, data, len); } } else { inject_data(_inject_to, data, len); } } void AP_GPS::inject_data(uint8_t instance, const uint8_t *data, uint16_t len) { if (instance < GPS_MAX_RECEIVERS && drivers[instance] != nullptr) { drivers[instance]->inject_data(data, len); } } /* get GPS yaw following mavlink GPS_RAW_INT and GPS2_RAW convention. We return 0 if the GPS is not configured to provide yaw. We return 65535 for a GPS configured to provide yaw that can't currently provide it. We return from 1 to 36000 for yaw otherwise */ uint16_t AP_GPS::gps_yaw_cdeg(uint8_t instance) const { if (!<API key>(instance)) { return 0; } float yaw_deg, accuracy_deg; uint32_t time_ms; if (!gps_yaw_deg(instance, yaw_deg, accuracy_deg, time_ms)) { return 65535; } int yaw_cd = wrap_360_cd(yaw_deg * 100); if (yaw_cd == 0) { return 36000; } return yaw_cd; } void AP_GPS::<API key>(mavlink_channel_t chan) { const Location &loc = location(0); float hacc = 0.0f; float vacc = 0.0f; float sacc = 0.0f; horizontal_accuracy(0, hacc); vertical_accuracy(0, vacc); speed_accuracy(0, sacc); <API key>( chan, last_fix_time_ms(0)*(uint64_t)1000, status(0), loc.lat, // in 1E7 degrees loc.lng, // in 1E7 degrees loc.alt * 10UL, // in mm get_hdop(0), get_vdop(0), ground_speed(0)*100, // cm/s ground_course(0)*100, // 1/100 degrees, num_sats(0), 0, // TODO: Elipsoid height in mm hacc * 1000, // one-sigma standard deviation in mm vacc * 1000, // one-sigma standard deviation in mm sacc * 1000, // one-sigma standard deviation in mm/s 0, // TODO one-sigma heading accuracy standard deviation gps_yaw_cdeg(0)); } #if GPS_MAX_RECEIVERS > 1 void AP_GPS::<API key>(mavlink_channel_t chan) { // always send the message if 2nd GPS is configured if (_type[1] == GPS_TYPE_NONE) { return; } const Location &loc = location(1); float hacc = 0.0f; float vacc = 0.0f; float sacc = 0.0f; horizontal_accuracy(1, hacc); vertical_accuracy(1, vacc); speed_accuracy(1, sacc); <API key>( chan, last_fix_time_ms(1)*(uint64_t)1000, status(1), loc.lat, loc.lng, loc.alt * 10UL, get_hdop(1), get_vdop(1), ground_speed(1)*100, // cm/s ground_course(1)*100, // 1/100 degrees, num_sats(1), state[1].rtk_num_sats, state[1].rtk_age_ms, gps_yaw_cdeg(1), 0, // TODO: Elipsoid height in mm hacc * 1000, // one-sigma standard deviation in mm vacc * 1000, // one-sigma standard deviation in mm sacc * 1000, // one-sigma standard deviation in mm/s 0); // TODO one-sigma heading accuracy standard deviation } #endif // GPS_MAX_RECEIVERS void AP_GPS::<API key>(mavlink_channel_t chan, uint8_t inst) { if (inst >= GPS_MAX_RECEIVERS) { return; } if (drivers[inst] != nullptr && drivers[inst]-><API key>()) { drivers[inst]-><API key>(chan); } } bool AP_GPS::<API key>(uint8_t &instance) const { for (int i = 0; i < GPS_MAX_RECEIVERS; i++) { if (_type[i] != GPS_TYPE_NONE && (drivers[i] == nullptr || !drivers[i]->is_configured())) { instance = i; return true; } } return false; } void AP_GPS::<API key>(void) const { uint8_t unconfigured; if (<API key>(unconfigured)) { if (drivers[unconfigured] == nullptr) { GCS_SEND_TEXT(MAV_SEVERITY_INFO, "GPS %d: was not found", unconfigured + 1); } else { drivers[unconfigured]-><API key>(); } } } // pre-arm check that all GPSs are close to each other. farthest distance between GPSs (in meters) is returned bool AP_GPS::all_consistent(float &distance) const { // return true immediately if only one valid receiver if (num_instances <= 1 || drivers[0] == nullptr || _type[0] == GPS_TYPE_NONE) { distance = 0; return true; } // calculate distance distance = state[0].location.get_distance_NED(state[1].location).length(); // success if distance is within 50m return (distance < 50); } // pre-arm check of GPS blending. True means healthy or that blending is not being used bool AP_GPS::blend_health_check() const { return (<API key> < 50); } /* re-assemble fragmented RTCM data */ void AP_GPS::<API key>(uint8_t flags, const uint8_t *data, uint8_t len) { if ((flags & 1) == 0) { // it is not fragmented, pass direct inject_data(data, len); return; } // see if we need to allocate re-assembly buffer if (rtcm_buffer == nullptr) { rtcm_buffer = (struct rtcm_buffer *)calloc(1, sizeof(*rtcm_buffer)); if (rtcm_buffer == nullptr) { // nothing to do but discard the data return; } } const uint8_t fragment = (flags >> 1U) & 0x03; const uint8_t sequence = (flags >> 3U) & 0x1F; // see if this fragment is consistent with existing fragments if (rtcm_buffer->fragments_received && (rtcm_buffer->sequence != sequence || (rtcm_buffer->fragments_received & (1U<<fragment)))) { // we have one or more partial fragments already received // which conflict with the new fragment, discard previous fragments rtcm_buffer->fragment_count = 0; rtcm_buffer->fragments_received = 0; } // add this fragment rtcm_buffer->sequence = sequence; rtcm_buffer->fragments_received |= (1U << fragment); // copy the data memcpy(&rtcm_buffer->buffer[<API key>*(uint16_t)fragment], data, len); // when we get a fragment of less than max size then we know the // number of fragments. Note that this means if you want to send a // block of RTCM data of an exact multiple of the buffer size you // need to send a final packet of zero length if (len < <API key>) { rtcm_buffer->fragment_count = fragment+1; rtcm_buffer->total_length = (<API key>*fragment) + len; } else if (rtcm_buffer->fragments_received == 0x0F) { // special case of 4 full fragments rtcm_buffer->fragment_count = 4; rtcm_buffer->total_length = <API key>*4; } // see if we have all fragments if (rtcm_buffer->fragment_count != 0 && rtcm_buffer->fragments_received == (1U << rtcm_buffer->fragment_count) - 1) { // we have them all, inject inject_data(rtcm_buffer->buffer, rtcm_buffer->total_length); rtcm_buffer->fragment_count = 0; rtcm_buffer->fragments_received = 0; } } /* re-assemble GPS_RTCM_DATA message */ void AP_GPS::<API key>(const mavlink_message_t &msg) { <API key> packet; <API key>(&msg, &packet); if (packet.len > sizeof(packet.data)) { // invalid packet return; } <API key>(packet.flags, packet.data, packet.len); } void AP_GPS::<API key>() { for (uint8_t instance=0; instance<num_instances; instance++) { if (drivers[instance] == nullptr || state[instance].status == NO_GPS) { continue; } drivers[instance]-><API key>(); } } /* return the expected lag (in seconds) in the position and velocity readings from the gps return true if the GPS hardware configuration is known or the delay parameter has been set */ bool AP_GPS::get_lag(uint8_t instance, float &lag_sec) const { // always enusre a lag is provided lag_sec = 0.22f; if (instance >= GPS_MAX_INSTANCES) { return false; } #if defined(<API key>) // return lag of blended GPS if (instance == <API key>) { lag_sec = _blended_lag_sec; // auto switching uses all GPS receivers, so all must be configured uint8_t inst; // we don't actually care what the number is, but must pass it return <API key>(inst); } #endif if (_delay_ms[instance] > 0) { // if the user has specified a non zero time delay, always return that value lag_sec = 0.001f * (float)_delay_ms[instance]; // the user is always right !! return true; } else if (drivers[instance] == nullptr || state[instance].status == NO_GPS) { // no GPS was detected in this instance so return the worst possible lag term if (_type[instance] == GPS_TYPE_NONE) { lag_sec = 0.0f; return true; } return _type[instance] == GPS_TYPE_AUTO; } else { // the user has not specified a delay so we determine it from the GPS type return drivers[instance]->get_lag(lag_sec); } } // return a 3D vector defining the offset of the GPS antenna in meters relative to the body frame origin const Vector3f &AP_GPS::get_antenna_offset(uint8_t instance) const { if (instance >= GPS_MAX_INSTANCES) { // we have to return a reference so use instance 0 return _antenna_offset[0]; } #if defined(<API key>) if (instance == <API key>) { // return an offset for the blended GPS solution return <API key>; } #endif return _antenna_offset[instance]; } /* returns the desired gps update rate in milliseconds this does not provide any guarantee that the GPS is updating at the requested rate it is simply a helper for use in the backends for determining what rate they should be configuring the GPS to run at */ uint16_t AP_GPS::get_rate_ms(uint8_t instance) const { // sanity check if (instance >= num_instances || _rate_ms[instance] <= 0) { return GPS_MAX_RATE_MS; } return MIN(_rate_ms[instance], GPS_MAX_RATE_MS); } #if defined(<API key>) /* calculate the weightings used to blend GPSs location and velocity data */ bool AP_GPS::calc_blend_weights(void) { // zero the blend weights memset(&_blend_weights, 0, sizeof(_blend_weights)); static_assert(GPS_MAX_RECEIVERS == 2, "GPS blending only currently works with 2 receivers"); // Note that the early quit below relies upon exactly 2 instances // The time delta calculations below also rely upon every instance being currently detected and being parsed // exit immediately if not enough receivers to do blending if (state[0].status <= NO_FIX || state[1].status <= NO_FIX) { return false; } // Use the oldest non-zero time, but if time difference is excessive, use newest to prevent a disconnected receiver from blocking updates uint32_t max_ms = 0; // newest non-zero system time of arrival of a GPS message uint32_t min_ms = -1; // oldest non-zero system time of arrival of a GPS message uint32_t max_rate_ms = 0; // largest update interval of a GPS receiver for (uint8_t i=0; i<GPS_MAX_RECEIVERS; i++) { // Find largest and smallest times if (state[i].last_gps_time_ms > max_ms) { max_ms = state[i].last_gps_time_ms; } if ((state[i].last_gps_time_ms < min_ms) && (state[i].last_gps_time_ms > 0)) { min_ms = state[i].last_gps_time_ms; } max_rate_ms = MAX(get_rate_ms(i), max_rate_ms); if (isinf(state[i].speed_accuracy) || isinf(state[i].horizontal_accuracy) || isinf(state[i].vertical_accuracy)) { return false; } } if ((max_ms - min_ms) < (2 * max_rate_ms)) { // data is not too delayed so use the oldest time_stamp to give a chance for data from that receiver to be updated state[<API key>].last_gps_time_ms = min_ms; } else { // receiver data has timed out so fail out of blending return false; } // calculate the sum squared speed accuracy across all GPS sensors float <API key> = 0.0f; if (_blend_mask & <API key>) { for (uint8_t i=0; i<GPS_MAX_RECEIVERS; i++) { if (state[i].status >= GPS_OK_FIX_3D) { if (state[i].have_speed_accuracy && state[i].speed_accuracy > 0.0f) { <API key> += state[i].speed_accuracy * state[i].speed_accuracy; } else { // not all receivers support this metric so set it to zero and don't use it <API key> = 0.0f; break; } } } } // calculate the sum squared horizontal position accuracy across all GPS sensors float <API key> = 0.0f; if (_blend_mask & <API key>) { for (uint8_t i=0; i<GPS_MAX_RECEIVERS; i++) { if (state[i].status >= GPS_OK_FIX_2D) { if (state[i].<API key> && state[i].horizontal_accuracy > 0.0f) { <API key> += state[i].horizontal_accuracy * state[i].horizontal_accuracy; } else { // not all receivers support this metric so set it to zero and don't use it <API key> = 0.0f; break; } } } } // calculate the sum squared vertical position accuracy across all GPS sensors float <API key> = 0.0f; if (_blend_mask & <API key>) { for (uint8_t i=0; i<GPS_MAX_RECEIVERS; i++) { if (state[i].status >= GPS_OK_FIX_3D) { if (state[i].<API key> && state[i].vertical_accuracy > 0.0f) { <API key> += state[i].vertical_accuracy * state[i].vertical_accuracy; } else { // not all receivers support this metric so set it to zero and don't use it <API key> = 0.0f; break; } } } } // Check if we can do blending using reported accuracy bool can_do_blending = (<API key> > 0.0f || <API key> > 0.0f || <API key> > 0.0f); // if we can't do blending using reported accuracy, return false and hard switch logic will be used instead if (!can_do_blending) { return false; } float sum_of_all_weights = 0.0f; // calculate a weighting using the reported horizontal position float hpos_blend_weights[GPS_MAX_RECEIVERS] = {}; if (<API key> > 0.0f && (_blend_mask & <API key>)) { // calculate the weights using the inverse of the variances float sum_of_hpos_weights = 0.0f; for (uint8_t i=0; i<GPS_MAX_RECEIVERS; i++) { if (state[i].status >= GPS_OK_FIX_2D && state[i].horizontal_accuracy >= 0.001f) { hpos_blend_weights[i] = <API key> / (state[i].horizontal_accuracy * state[i].horizontal_accuracy); sum_of_hpos_weights += hpos_blend_weights[i]; } } // normalise the weights if (sum_of_hpos_weights > 0.0f) { for (uint8_t i=0; i<GPS_MAX_RECEIVERS; i++) { hpos_blend_weights[i] = hpos_blend_weights[i] / sum_of_hpos_weights; } sum_of_all_weights += 1.0f; } } // calculate a weighting using the reported vertical position accuracy float vpos_blend_weights[GPS_MAX_RECEIVERS] = {}; if (<API key> > 0.0f && (_blend_mask & <API key>)) { // calculate the weights using the inverse of the variances float sum_of_vpos_weights = 0.0f; for (uint8_t i=0; i<GPS_MAX_RECEIVERS; i++) { if (state[i].status >= GPS_OK_FIX_3D && state[i].vertical_accuracy >= 0.001f) { vpos_blend_weights[i] = <API key> / (state[i].vertical_accuracy * state[i].vertical_accuracy); sum_of_vpos_weights += vpos_blend_weights[i]; } } // normalise the weights if (sum_of_vpos_weights > 0.0f) { for (uint8_t i=0; i<GPS_MAX_RECEIVERS; i++) { vpos_blend_weights[i] = vpos_blend_weights[i] / sum_of_vpos_weights; } sum_of_all_weights += 1.0f; }; } // calculate a weighting using the reported speed accuracy float spd_blend_weights[GPS_MAX_RECEIVERS] = {}; if (<API key> > 0.0f && (_blend_mask & <API key>)) { // calculate the weights using the inverse of the variances float sum_of_spd_weights = 0.0f; for (uint8_t i=0; i<GPS_MAX_RECEIVERS; i++) { if (state[i].status >= GPS_OK_FIX_3D && state[i].speed_accuracy >= 0.001f) { spd_blend_weights[i] = <API key> / (state[i].speed_accuracy * state[i].speed_accuracy); sum_of_spd_weights += spd_blend_weights[i]; } } // normalise the weights if (sum_of_spd_weights > 0.0f) { for (uint8_t i=0; i<GPS_MAX_RECEIVERS; i++) { spd_blend_weights[i] = spd_blend_weights[i] / sum_of_spd_weights; } sum_of_all_weights += 1.0f; } } if (!is_positive(sum_of_all_weights)) { return false; } // calculate an overall weight for (uint8_t i=0; i<GPS_MAX_RECEIVERS; i++) { _blend_weights[i] = (hpos_blend_weights[i] + vpos_blend_weights[i] + spd_blend_weights[i]) / sum_of_all_weights; } return true; } /* calculate a blended GPS state */ void AP_GPS::calc_blended_state(void) { // initialise the blended states so we can accumulate the results using the weightings for each GPS receiver state[<API key>].instance = <API key>; state[<API key>].status = NO_FIX; state[<API key>].time_week_ms = 0; state[<API key>].time_week = 0; state[<API key>].ground_speed = 0.0f; state[<API key>].ground_course = 0.0f; state[<API key>].hdop = GPS_UNKNOWN_DOP; state[<API key>].vdop = GPS_UNKNOWN_DOP; state[<API key>].num_sats = 0; state[<API key>].velocity.zero(); state[<API key>].speed_accuracy = 1e6f; state[<API key>].horizontal_accuracy = 1e6f; state[<API key>].vertical_accuracy = 1e6f; state[<API key>].<API key> = false; state[<API key>].have_speed_accuracy = false; state[<API key>].<API key> = false; state[<API key>].<API key> = false; state[<API key>].location = {}; <API key>.zero(); _blended_lag_sec = 0; #if HAL_LOGGING_ENABLED const uint32_t <API key> = timing[<API key>].<API key>; #endif timing[<API key>].last_fix_time_ms = 0; timing[<API key>].<API key> = 0; // combine the states into a blended solution for (uint8_t i=0; i<GPS_MAX_RECEIVERS; i++) { // use the highest status if (state[i].status > state[<API key>].status) { state[<API key>].status = state[i].status; } // calculate a blended average velocity state[<API key>].velocity += state[i].velocity * _blend_weights[i]; // report the best valid accuracies and DOP metrics if (state[i].<API key> && state[i].horizontal_accuracy > 0.0f && state[i].horizontal_accuracy < state[<API key>].horizontal_accuracy) { state[<API key>].<API key> = true; state[<API key>].horizontal_accuracy = state[i].horizontal_accuracy; } if (state[i].<API key> && state[i].vertical_accuracy > 0.0f && state[i].vertical_accuracy < state[<API key>].vertical_accuracy) { state[<API key>].<API key> = true; state[<API key>].vertical_accuracy = state[i].vertical_accuracy; } if (state[i].<API key>) { state[<API key>].<API key> = true; } if (state[i].have_speed_accuracy && state[i].speed_accuracy > 0.0f && state[i].speed_accuracy < state[<API key>].speed_accuracy) { state[<API key>].have_speed_accuracy = true; state[<API key>].speed_accuracy = state[i].speed_accuracy; } if (state[i].hdop > 0 && state[i].hdop < state[<API key>].hdop) { state[<API key>].hdop = state[i].hdop; } if (state[i].vdop > 0 && state[i].vdop < state[<API key>].vdop) { state[<API key>].vdop = state[i].vdop; } if (state[i].num_sats > 0 && state[i].num_sats > state[<API key>].num_sats) { state[<API key>].num_sats = state[i].num_sats; } // report a blended average GPS antenna position Vector3f temp_antenna_offset = _antenna_offset[i]; temp_antenna_offset *= _blend_weights[i]; <API key> += temp_antenna_offset; // blend the timing data if (timing[i].last_fix_time_ms > timing[<API key>].last_fix_time_ms) { timing[<API key>].last_fix_time_ms = timing[i].last_fix_time_ms; } if (timing[i].<API key> > timing[<API key>].<API key>) { timing[<API key>].<API key> = timing[i].<API key>; } } /* * Calculate an instantaneous weighted/blended average location from the available GPS instances and store in the _output_state. * This will be statistically the most likely location, but will be not stable enough for direct use by the autopilot. */ // Use the GPS with the highest weighting as the reference position float best_weight = 0.0f; uint8_t best_index = 0; for (uint8_t i=0; i<GPS_MAX_RECEIVERS; i++) { if (_blend_weights[i] > best_weight) { best_weight = _blend_weights[i]; best_index = i; state[<API key>].location = state[i].location; } } // Calculate the weighted sum of horizontal and vertical position offsets relative to the reference position Vector2f blended_NE_offset_m; float <API key> = 0.0f; blended_NE_offset_m.zero(); for (uint8_t i=0; i<GPS_MAX_RECEIVERS; i++) { if (_blend_weights[i] > 0.0f && i != best_index) { blended_NE_offset_m += state[<API key>].location.get_distance_NE(state[i].location) * _blend_weights[i]; <API key> += (float)(state[i].location.alt - state[<API key>].location.alt) * _blend_weights[i]; } } // Add the sum of weighted offsets to the reference location to obtain the blended location state[<API key>].location.offset(blended_NE_offset_m.x, blended_NE_offset_m.y); state[<API key>].location.alt += (int)<API key>; // Calculate ground speed and course from blended velocity vector state[<API key>].ground_speed = norm(state[<API key>].velocity.x, state[<API key>].velocity.y); state[<API key>].ground_course = wrap_360(degrees(atan2f(state[<API key>].velocity.y, state[<API key>].velocity.x))); // If the GPS week is the same then use a blended time_week_ms // If week is different, then use time stamp from GPS with largest weighting // detect inconsistent week data uint8_t last_week_instance = 0; bool weeks_consistent = true; for (uint8_t i=0; i<GPS_MAX_RECEIVERS; i++) { if (last_week_instance == 0 && _blend_weights[i] > 0) { // this is our first valid sensor week data last_week_instance = state[i].time_week; } else if (last_week_instance != 0 && _blend_weights[i] > 0 && last_week_instance != state[i].time_week) { // there is valid sensor week data that is inconsistent weeks_consistent = false; } } // calculate output if (!weeks_consistent) { // use data from highest weighted sensor state[<API key>].time_week = state[best_index].time_week; state[<API key>].time_week_ms = state[best_index].time_week_ms; } else { // use week number from highest weighting GPS (they should all have the same week number) state[<API key>].time_week = state[best_index].time_week; // calculate a blended value for the number of ms lapsed in the week double temp_time_0 = 0.0; for (uint8_t i=0; i<GPS_MAX_RECEIVERS; i++) { if (_blend_weights[i] > 0.0f) { temp_time_0 += (double)state[i].time_week_ms * (double)_blend_weights[i]; } } state[<API key>].time_week_ms = (uint32_t)temp_time_0; } // calculate a blended value for the timing data and lag double temp_time_1 = 0.0; double temp_time_2 = 0.0; for (uint8_t i=0; i<GPS_MAX_RECEIVERS; i++) { if (_blend_weights[i] > 0.0f) { temp_time_1 += (double)timing[i].last_fix_time_ms * (double) _blend_weights[i]; temp_time_2 += (double)timing[i].<API key> * (double)_blend_weights[i]; float gps_lag_sec = 0; get_lag(i, gps_lag_sec); _blended_lag_sec += gps_lag_sec * _blend_weights[i]; } } timing[<API key>].last_fix_time_ms = (uint32_t)temp_time_1; timing[<API key>].<API key> = (uint32_t)temp_time_2; #if HAL_LOGGING_ENABLED if (timing[<API key>].<API key> > <API key> && should_log()) { Write_GPS(<API key>); } #endif } #endif // <API key> bool AP_GPS::is_healthy(uint8_t instance) const { if (instance >= GPS_MAX_INSTANCES) { return false; } if (get_type(_primary.get()) == GPS_TYPE_NONE) { return false; } /* allow two lost frames before declaring the GPS unhealthy, but require the average frame rate to be close to 5Hz. We allow for a bit higher average for a rover due to the packet loss that happens with the RTCMv3 data */ const uint8_t delay_threshold = 2; const float delay_avg_max = _type[instance] == <API key>?245:215; const GPS_timing &t = timing[instance]; bool delay_ok = (t.delayed_count < delay_threshold) && t.average_delta_ms < delay_avg_max && state[instance].lagged_sample_count < 5; #if defined(<API key>) if (instance == <API key>) { return delay_ok && blend_health_check(); } #endif return delay_ok && drivers[instance] != nullptr && drivers[instance]->is_healthy(); } bool AP_GPS::prepare_for_arming(void) { bool all_passed = true; for (uint8_t i = 0; i < GPS_MAX_RECEIVERS; i++) { if (drivers[i] != nullptr) { all_passed &= drivers[i]->prepare_for_arming(); } } return all_passed; } bool AP_GPS::backends_healthy(char failure_msg[], uint16_t failure_msg_len) { #if <API key> for (uint8_t i = 0; i < GPS_MAX_RECEIVERS; i++) { if (_type[i] == GPS_TYPE_UAVCAN) { if (!AP_GPS_UAVCAN::backends_healthy(failure_msg, failure_msg_len)) { return false; } } } #endif return true; } bool AP_GPS::logging_failed(void) const { if (!logging_enabled()) { return false; } for (uint8_t i = 0; i < GPS_MAX_RECEIVERS; i++) { if ((drivers[i] != nullptr) && !(drivers[i]->logging_healthy())) { return true; } } return false; } // get iTOW, if supported, zero otherwie uint32_t AP_GPS::get_itow(uint8_t instance) const { if (instance >= GPS_MAX_RECEIVERS || drivers[instance] == nullptr) { return 0; } return drivers[instance]->get_last_itow(); } bool AP_GPS::get_error_codes(uint8_t instance, uint32_t &error_codes) const { if (instance >= GPS_MAX_RECEIVERS || drivers[instance] == nullptr) { return false; } return drivers[instance]->get_error_codes(error_codes); } // Logging support: // Write an GPS packet void AP_GPS::Write_GPS(uint8_t i) { const uint64_t time_us = AP_HAL::micros64(); const struct Location &loc = location(i); float yaw_deg=0, yaw_accuracy_deg=0; uint32_t yaw_time_ms; gps_yaw_deg(i, yaw_deg, yaw_accuracy_deg, yaw_time_ms); const struct log_GPS pkt { <API key>(LOG_GPS_MSG), time_us : time_us, instance : i, status : (uint8_t)status(i), gps_week_ms : time_week_ms(i), gps_week : time_week(i), num_sats : num_sats(i), hdop : get_hdop(i), latitude : loc.lat, longitude : loc.lng, altitude : loc.alt, ground_speed : ground_speed(i), ground_course : ground_course(i), vel_z : velocity(i).z, yaw : yaw_deg, used : (uint8_t)(AP::gps().primary_sensor() == i) }; AP::logger().WriteBlock(&pkt, sizeof(pkt)); /* write auxiliary accuracy information as well */ float hacc = 0, vacc = 0, sacc = 0; horizontal_accuracy(i, hacc); vertical_accuracy(i, vacc); speed_accuracy(i, sacc); struct log_GPA pkt2{ <API key>(LOG_GPA_MSG), time_us : time_us, instance : i, vdop : get_vdop(i), hacc : (uint16_t)MIN((hacc*100), UINT16_MAX), vacc : (uint16_t)MIN((vacc*100), UINT16_MAX), sacc : (uint16_t)MIN((sacc*100), UINT16_MAX), yaw_accuracy : yaw_accuracy_deg, have_vv : (uint8_t)<API key>(i), sample_ms : <API key>(i), delta_ms : <API key>(i) }; AP::logger().WriteBlock(&pkt2, sizeof(pkt2)); } /* get GPS based yaw */ bool AP_GPS::gps_yaw_deg(uint8_t instance, float &yaw_deg, float &accuracy_deg, uint32_t &time_ms) const { #if GPS_MAX_RECEIVERS > 1 if (instance < GPS_MAX_RECEIVERS && _type[instance] == <API key> && _type[instance^1] == <API key>) { // return the yaw from the rover instance ^= 1; } #endif if (!have_gps_yaw(instance)) { return false; } yaw_deg = state[instance].gps_yaw; // get lagged timestamp time_ms = state[instance].gps_yaw_time_ms; float lag_s; if (get_lag(instance, lag_s)) { uint32_t lag_ms = lag_s * 1000; time_ms -= lag_ms; } if (state[instance].<API key>) { accuracy_deg = state[instance].gps_yaw_accuracy; } else { // fall back to 10 degrees as a generic default accuracy_deg = 10; } return true; } namespace AP { AP_GPS &gps() { return *AP_GPS::get_singleton(); } };
<!DOCTYPE html> <! Template Name: Metronic - Responsive Admin Dashboard Template build with Twitter Bootstrap 3.3.7 Version: 4.7.1 Author: KeenThemes Website: http: Contact: support@keenthemes.com Follow: www.twitter.com/keenthemes Dribbble: www.dribbble.com/keenthemes Like: www.facebook.com/keenthemes Purchase: http://themeforest.net/item/<API key>/4021469?ref=keenthemes Renew Support: http://themeforest.net/item/<API key>/4021469?ref=keenthemes License: You must have a valid license purchased only from themeforest(the above link) in order to legally use the theme for your project. <!--[if IE 8]> <html lang="en" class="ie8 no-js"> <![endif]--> <!--[if IE 9]> <html lang="en" class="ie9 no-js"> <![endif]--> <!--[if !IE]><!--> <html lang="en"> <!--<![endif]--> <!-- BEGIN HEAD --> <head> <meta charset="utf-8" /> <title>Metronic Admin Theme #3 | Rowreorder Extension</title> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta content="width=device-width, initial-scale=1" name="viewport" /> <meta content="Preview page of Metronic Admin Theme #3 for rowreorder extension demos" name="description" /> <meta content="" name="author" /> <!-- BEGIN GLOBAL MANDATORY STYLES --> <link href="http://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700&subset=all" rel="stylesheet" type="text/css" /> <link href="../assets/global/plugins/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css" /> <link href="../assets/global/plugins/simple-line-icons/simple-line-icons.min.css" rel="stylesheet" type="text/css" /> <link href="../assets/global/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css" /> <link href="../assets/global/plugins/bootstrap-switch/css/bootstrap-switch.min.css" rel="stylesheet" type="text/css" /> <!-- END GLOBAL MANDATORY STYLES --> <!-- BEGIN PAGE LEVEL PLUGINS --> <link href="../assets/global/plugins/datatables/datatables.min.css" rel="stylesheet" type="text/css" /> <link href="../assets/global/plugins/datatables/plugins/bootstrap/datatables.bootstrap.css" rel="stylesheet" type="text/css" /> <!-- END PAGE LEVEL PLUGINS --> <!-- BEGIN THEME GLOBAL STYLES --> <link href="../assets/global/css/components.min.css" rel="stylesheet" id="style_components" type="text/css" /> <link href="../assets/global/css/plugins.min.css" rel="stylesheet" type="text/css" /> <!-- END THEME GLOBAL STYLES --> <!-- BEGIN THEME LAYOUT STYLES --> <link href="../assets/layouts/layout3/css/layout.min.css" rel="stylesheet" type="text/css" /> <link href="../assets/layouts/layout3/css/themes/default.min.css" rel="stylesheet" type="text/css" id="style_color" /> <link href="../assets/layouts/layout3/css/custom.min.css" rel="stylesheet" type="text/css" /> <!-- END THEME LAYOUT STYLES --> <link rel="shortcut icon" href="favicon.ico" /> </head> <!-- END HEAD --> <body class="<API key>"> <div class="page-wrapper"> <div class="page-wrapper-row"> <div class="page-wrapper-top"> <!-- BEGIN HEADER --> <div class="page-header"> <!-- BEGIN HEADER TOP --> <div class="page-header-top"> <div class="container"> <!-- BEGIN LOGO --> <div class="page-logo"> <a href="index.html"> <img src="../assets/layouts/layout3/img/logo-default.jpg" alt="logo" class="logo-default"> </a> </div> <!-- END LOGO --> <!-- BEGIN RESPONSIVE MENU TOGGLER --> <a href="javascript:;" class="menu-toggler"></a> <!-- END RESPONSIVE MENU TOGGLER --> <!-- BEGIN TOP NAVIGATION MENU --> <div class="top-menu"> <ul class="nav navbar-nav pull-right"> <!-- BEGIN NOTIFICATION DROPDOWN --> <!-- DOC: Apply "dropdown-hoverable" class after "dropdown" and remove data-toggle="dropdown" data-hover="dropdown" data-close-others="true" attributes to enable hover dropdown mode --> <!-- DOC: Remove "dropdown-hoverable" and add data-toggle="dropdown" data-hover="dropdown" data-close-others="true" attributes to the below A element with dropdown-toggle class --> <li class="dropdown dropdown-extended <API key> dropdown-dark" id="<API key>"> <a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true"> <i class="icon-bell"></i> <span class="badge badge-default">7</span> </a> <ul class="dropdown-menu"> <li class="external"> <h3>You have <strong>12 pending</strong> tasks</h3> <a href="app_todo.html">view all</a> </li> <li> <ul class="dropdown-menu-list scroller" style="height: 250px;" data-handle-color="#637283"> <li> <a href="javascript:;"> <span class="time">just now</span> <span class="details"> <span class="label label-sm label-icon label-success"> <i class="fa fa-plus"></i> </span> New user registered. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">3 mins</span> <span class="details"> <span class="label label-sm label-icon label-danger"> <i class="fa fa-bolt"></i> </span> Server #12 overloaded. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">10 mins</span> <span class="details"> <span class="label label-sm label-icon label-warning"> <i class="fa fa-bell-o"></i> </span> Server #2 not responding. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">14 hrs</span> <span class="details"> <span class="label label-sm label-icon label-info"> <i class="fa fa-bullhorn"></i> </span> Application error. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">2 days</span> <span class="details"> <span class="label label-sm label-icon label-danger"> <i class="fa fa-bolt"></i> </span> Database overloaded 68%. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">3 days</span> <span class="details"> <span class="label label-sm label-icon label-danger"> <i class="fa fa-bolt"></i> </span> A user IP blocked. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">4 days</span> <span class="details"> <span class="label label-sm label-icon label-warning"> <i class="fa fa-bell-o"></i> </span> Storage Server #4 not responding dfdfdfd. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">5 days</span> <span class="details"> <span class="label label-sm label-icon label-info"> <i class="fa fa-bullhorn"></i> </span> System Error. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">9 days</span> <span class="details"> <span class="label label-sm label-icon label-danger"> <i class="fa fa-bolt"></i> </span> Storage server failed. </span> </a> </li> </ul> </li> </ul> </li> <!-- END NOTIFICATION DROPDOWN --> <!-- BEGIN TODO DROPDOWN --> <li class="dropdown dropdown-extended dropdown-tasks dropdown-dark" id="header_task_bar"> <a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true"> <i class="icon-calendar"></i> <span class="badge badge-default">3</span> </a> <ul class="dropdown-menu extended tasks"> <li class="external"> <h3>You have <strong>12 pending</strong> tasks</h3> <a href="app_todo_2.html">view all</a> </li> <li> <ul class="dropdown-menu-list scroller" style="height: 275px;" data-handle-color="#637283"> <li> <a href="javascript:;"> <span class="task"> <span class="desc">New release v1.2 </span> <span class="percent">30%</span> </span> <span class="progress"> <span style="width: 40%;" class="progress-bar <API key>" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100"> <span class="sr-only">40% Complete</span> </span> </span> </a> </li> <li> <a href="javascript:;"> <span class="task"> <span class="desc">Application deployment</span> <span class="percent">65%</span> </span> <span class="progress"> <span style="width: 65%;" class="progress-bar progress-bar-danger" aria-valuenow="65" aria-valuemin="0" aria-valuemax="100"> <span class="sr-only">65% Complete</span> </span> </span> </a> </li> <li> <a href="javascript:;"> <span class="task"> <span class="desc">Mobile app release</span> <span class="percent">98%</span> </span> <span class="progress"> <span style="width: 98%;" class="progress-bar <API key>" aria-valuenow="98" aria-valuemin="0" aria-valuemax="100"> <span class="sr-only">98% Complete</span> </span> </span> </a> </li> <li> <a href="javascript:;"> <span class="task"> <span class="desc">Database migration</span> <span class="percent">10%</span> </span> <span class="progress"> <span style="width: 10%;" class="progress-bar <API key>" aria-valuenow="10" aria-valuemin="0" aria-valuemax="100"> <span class="sr-only">10% Complete</span> </span> </span> </a> </li> <li> <a href="javascript:;"> <span class="task"> <span class="desc">Web server upgrade</span> <span class="percent">58%</span> </span> <span class="progress"> <span style="width: 58%;" class="progress-bar progress-bar-info" aria-valuenow="58" aria-valuemin="0" aria-valuemax="100"> <span class="sr-only">58% Complete</span> </span> </span> </a> </li> <li> <a href="javascript:;"> <span class="task"> <span class="desc">Mobile development</span> <span class="percent">85%</span> </span> <span class="progress"> <span style="width: 85%;" class="progress-bar <API key>" aria-valuenow="85" aria-valuemin="0" aria-valuemax="100"> <span class="sr-only">85% Complete</span> </span> </span> </a> </li> <li> <a href="javascript:;"> <span class="task"> <span class="desc">New UI release</span> <span class="percent">38%</span> </span> <span class="progress progress-striped"> <span style="width: 38%;" class="progress-bar <API key>" aria-valuenow="18" aria-valuemin="0" aria-valuemax="100"> <span class="sr-only">38% Complete</span> </span> </span> </a> </li> </ul> </li> </ul> </li> <!-- END TODO DROPDOWN --> <li class="droddown dropdown-separator"> <span class="separator"></span> </li> <!-- BEGIN INBOX DROPDOWN --> <li class="dropdown dropdown-extended dropdown-inbox dropdown-dark" id="header_inbox_bar"> <a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true"> <span class="circle">3</span> <span class="corner"></span> </a> <ul class="dropdown-menu"> <li class="external"> <h3>You have <strong>7 New</strong> Messages</h3> <a href="app_inbox.html">view all</a> </li> <li> <ul class="dropdown-menu-list scroller" style="height: 275px;" data-handle-color="#637283"> <li> <a href=" <span class="photo"> <img src="../assets/layouts/layout3/img/avatar2.jpg" class="img-circle" alt=""> </span> <span class="subject"> <span class="from"> Lisa Wong </span> <span class="time">Just Now </span> </span> <span class="message"> Vivamus sed auctor nibh congue nibh. auctor nibh auctor nibh... </span> </a> </li> <li> <a href=" <span class="photo"> <img src="../assets/layouts/layout3/img/avatar3.jpg" class="img-circle" alt=""> </span> <span class="subject"> <span class="from"> Richard Doe </span> <span class="time">16 mins </span> </span> <span class="message"> Vivamus sed congue nibh auctor nibh congue nibh. auctor nibh auctor nibh... </span> </a> </li> <li> <a href=" <span class="photo"> <img src="../assets/layouts/layout3/img/avatar1.jpg" class="img-circle" alt=""> </span> <span class="subject"> <span class="from"> Bob Nilson </span> <span class="time">2 hrs </span> </span> <span class="message"> Vivamus sed nibh auctor nibh congue nibh. auctor nibh auctor nibh... </span> </a> </li> <li> <a href=" <span class="photo"> <img src="../assets/layouts/layout3/img/avatar2.jpg" class="img-circle" alt=""> </span> <span class="subject"> <span class="from"> Lisa Wong </span> <span class="time">40 mins </span> </span> <span class="message"> Vivamus sed auctor 40% nibh congue nibh... </span> </a> </li> <li> <a href=" <span class="photo"> <img src="../assets/layouts/layout3/img/avatar3.jpg" class="img-circle" alt=""> </span> <span class="subject"> <span class="from"> Richard Doe </span> <span class="time">46 mins </span> </span> <span class="message"> Vivamus sed congue nibh auctor nibh congue nibh. auctor nibh auctor nibh... </span> </a> </li> </ul> </li> </ul> </li> <!-- END INBOX DROPDOWN --> <!-- BEGIN USER LOGIN DROPDOWN --> <li class="dropdown dropdown-user dropdown-dark"> <a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true"> <img alt="" class="img-circle" src="../assets/layouts/layout3/img/avatar9.jpg"> <span class="username <API key>">Nick</span> </a> <ul class="dropdown-menu <API key>"> <li> <a href="page_user_profile_1.html"> <i class="icon-user"></i> My Profile </a> </li> <li> <a href="app_calendar.html"> <i class="icon-calendar"></i> My Calendar </a> </li> <li> <a href="app_inbox.html"> <i class="icon-envelope-open"></i> My Inbox <span class="badge badge-danger"> 3 </span> </a> </li> <li> <a href="app_todo_2.html"> <i class="icon-rocket"></i> My Tasks <span class="badge badge-success"> 7 </span> </a> </li> <li class="divider"> </li> <li> <a href="page_user_lock_1.html"> <i class="icon-lock"></i> Lock Screen </a> </li> <li> <a href="page_user_login_1.html"> <i class="icon-key"></i> Log Out </a> </li> </ul> </li> <!-- END USER LOGIN DROPDOWN --> <!-- BEGIN QUICK SIDEBAR TOGGLER --> <li class="dropdown dropdown-extended <API key>"> <span class="sr-only">Toggle Quick Sidebar</span> <i class="icon-logout"></i> </li> <!-- END QUICK SIDEBAR TOGGLER --> </ul> </div> <!-- END TOP NAVIGATION MENU --> </div> </div> <!-- END HEADER TOP --> <!-- BEGIN HEADER MENU --> <div class="page-header-menu"> <div class="container"> <!-- BEGIN HEADER SEARCH BOX --> <form class="search-form" action="page_general_search.html" method="GET"> <div class="input-group"> <input type="text" class="form-control" placeholder="Search" name="query"> <span class="input-group-btn"> <a href="javascript:;" class="btn submit"> <i class="icon-magnifier"></i> </a> </span> </div> </form> <!-- END HEADER SEARCH BOX --> <!-- BEGIN MEGA MENU --> <!-- DOC: Apply "hor-menu-light" class after the "hor-menu" class below to have a horizontal menu with white background --> <!-- DOC: Remove data-hover="dropdown" and data-close-others="true" attributes below to disable the dropdown opening on mouse hover --> <div class="hor-menu "> <ul class="nav navbar-nav"> <li aria-haspopup="true" class="menu-dropdown <API key> "> <a href="javascript:;"> Dashboard <span class="arrow"></span> </a> <ul class="dropdown-menu pull-left"> <li aria-haspopup="true" class=" "> <a href="index.html" class="nav-link "> <i class="icon-bar-chart"></i> Default Dashboard <span class="badge badge-success">1</span> </a> </li> <li aria-haspopup="true" class=" "> <a href="dashboard_2.html" class="nav-link "> <i class="icon-bulb"></i> Dashboard 2 </a> </li> <li aria-haspopup="true" class=" "> <a href="dashboard_3.html" class="nav-link "> <i class="icon-graph"></i> Dashboard 3 <span class="badge badge-danger">3</span> </a> </li> </ul> </li> <li aria-haspopup="true" class="menu-dropdown mega-menu-dropdown "> <a href="javascript:;"> UI Features <span class="arrow"></span> </a> <ul class="dropdown-menu" style="min-width: 710px"> <li> <div class="mega-menu-content"> <div class="row"> <div class="col-md-4"> <ul class="mega-menu-submenu"> <li> <a href="ui_colors.html"> Color Library </a> </li> <li> <a href="ui_metronic_grid.html"> Metronic Grid System </a> </li> <li> <a href="ui_general.html"> General Components </a> </li> <li> <a href="ui_buttons.html"> Buttons </a> </li> <li> <a href="ui_buttons_spinner.html"> Spinner Buttons </a> </li> <li> <a href="ui_confirmations.html"> Popover Confirmations </a> </li> <li> <a href="ui_sweetalert.html"> Bootstrap Sweet Alerts </a> </li> <li> <a href="ui_icons.html"> Font Icons </a> </li> <li> <a href="ui_socicons.html"> Social Icons </a> </li> <li> <a href="ui_typography.html"> Typography </a> </li> <li> <a href="<API key>.html"> Tabs, Accordions & Navs </a> </li> <li> <a href="ui_tree.html"> Tree View </a> </li> <li> <a href="maps_google.html"> Google Maps </a> </li> </ul> </div> <div class="col-md-4"> <ul class="mega-menu-submenu"> <li> <a href="maps_vector.html"> Vector Maps </a> </li> <li> <a href="ui_timeline.html"> Timeline 1 </a> </li> <li> <a href="ui_timeline_2.html"> Timeline 2 </a> </li> <li> <a href="<API key>.html"> Horizontal Timeline </a> </li> <li> <a href="<API key>.html"> Page Progress Bar - Flash </a> </li> <li> <a href="<API key>.html"> Page Progress Bar - Big Counter </a> </li> <li> <a href="ui_blockui.html"> Block UI </a> </li> <li> <a href="ui_bootstrap_growl.html"> Bootstrap Growl Notifications </a> </li> <li> <a href="ui_notific8.html"> Notific8 Notifications </a> </li> <li> <a href="ui_toastr.html"> Toastr Notifications </a> </li> <li> <a href="ui_bootbox.html"> Bootbox Dialogs </a> </li> </ul> </div> <div class="col-md-4"> <ul class="mega-menu-submenu"> <li> <a href="ui_alerts_api.html"> Metronic Alerts API </a> </li> <li> <a href="ui_session_timeout.html"> Session Timeout </a> </li> <li> <a href="ui_idle_timeout.html"> User Idle Timeout </a> </li> <li> <a href="ui_modals.html"> Modals </a> </li> <li> <a href="ui_extended_modals.html"> Extended Modals </a> </li> <li> <a href="ui_tiles.html"> Tiles </a> </li> <li> <a href="ui_datepaginator.html"> Date Paginator </a> </li> <li> <a href="ui_nestable.html"> Nestable List </a> </li> </ul> </div> </div> </div> </li> </ul> </li> <li aria-haspopup="true" class="menu-dropdown <API key> "> <a href="javascript:;"> Layouts <span class="arrow"></span> </a> <ul class="dropdown-menu pull-left"> <li aria-haspopup="true" class=" "> <a href="<API key>.html" class="nav-link "> Light Mega Menu </a> </li> <li aria-haspopup="true" class=" "> <a href="<API key>.html" class="nav-link "> Light Top Bar Dropdowns </a> </li> <li aria-haspopup="true" class=" "> <a href="layout_fluid_page.html" class="nav-link "> Fluid Page </a> </li> <li aria-haspopup="true" class=" "> <a href="<API key>.html" class="nav-link "> Fixed Top Bar </a> </li> <li aria-haspopup="true" class=" "> <a href="<API key>.html" class="nav-link "> Fixed Mega Menu </a> </li> <li aria-haspopup="true" class=" "> <a href="<API key>.html" class="nav-link "> Disabled Menu Links </a> </li> <li aria-haspopup="true" class=" "> <a href="layout_blank_page.html" class="nav-link "> Blank Page </a> </li> </ul> </li> <li aria-haspopup="true" class="menu-dropdown mega-menu-dropdown mega-menu-full"> <a href="javascript:;"> Components <span class="arrow"></span> </a> <ul class="dropdown-menu" style="min-width: "> <li> <div class="mega-menu-content"> <div class="row"> <div class="col-md-3"> <ul class="mega-menu-submenu"> <li> <h3>Components 1</h3> </li> <li> <a href="<API key>.html"> Date & Time Pickers </a> </li> <li> <a href="<API key>.html"> Color Pickers </a> </li> <li> <a href="components_select2.html"> Select2 Dropdowns </a> </li> <li> <a href="<API key>.html"> Bootstrap Multiselect Dropdowns </a> </li> <li> <a href="<API key>.html"> Bootstrap Select </a> </li> <li> <a href="<API key>.html"> Bootstrap Multiple Select </a> </li> </ul> </div> <div class="col-md-3"> <ul class="mega-menu-submenu"> <li> <h3>Components 2</h3> </li> <li> <a href="<API key>.html"> Select Splitter </a> </li> <li> <a href="<API key>.html"> Clipboard </a> </li> <li> <a href="<API key>.html"> Typeahead Autocomplete </a> </li> <li> <a href="<API key>.html"> Bootstrap Tagsinput </a> </li> <li> <a href="<API key>.html"> Bootstrap Switch </a> </li> <li> <a href="<API key>.html"> Bootstrap Maxlength </a> </li> </ul> </div> <div class="col-md-3"> <ul class="mega-menu-submenu"> <li> <h3>Components 3</h3> </li> <li> <a href="<API key>.html"> Bootstrap File Input </a> </li> <li> <a href="<API key>.html"> Bootstrap Touchspin </a> </li> <li> <a href="<API key>.html"> Form Widgets & Tools </a> </li> <li> <a href="<API key>.html"> Context Menu </a> </li> <li> <a href="components_editors.html"> Markdown & WYSIWYG Editors </a> </li> </ul> </div> <div class="col-md-3"> <ul class="mega-menu-submenu"> <li> <h3>Components 4</h3> </li> <li> <a href="<API key>.html"> Code Editors </a> </li> <li> <a href="<API key>.html"> Ion Range Sliders </a> </li> <li> <a href="<API key>.html"> NoUI Range Sliders </a> </li> <li> <a href="<API key>.html"> Knob Circle Dials </a> </li> </ul> </div> </div> </div> </li> </ul> </li> <li aria-haspopup="true" class="menu-dropdown <API key> active"> <a href="javascript:;"> More <span class="arrow"></span> </a> <ul class="dropdown-menu pull-left"> <li aria-haspopup="true" class="dropdown-submenu "> <a href="javascript:;" class="nav-link nav-toggle "> <i class="icon-settings"></i> Form Stuff <span class="arrow"></span> </a> <ul class="dropdown-menu"> <li aria-haspopup="true" class=" "> <a href="form_controls.html" class="nav-link "> Bootstrap Form <br>Controls </a> </li> <li aria-haspopup="true" class=" "> <a href="form_controls_md.html" class="nav-link "> Material Design <br>Form Controls </a> </li> <li aria-haspopup="true" class=" "> <a href="form_validation.html" class="nav-link "> Form Validation </a> </li> <li aria-haspopup="true" class=" "> <a href="<API key>.html" class="nav-link "> Material Design <br>Form Validation States </a> </li> <li aria-haspopup="true" class=" "> <a href="form_validation_md.html" class="nav-link "> Material Design <br>Form Validation </a> </li> <li aria-haspopup="true" class=" "> <a href="form_layouts.html" class="nav-link "> Form Layouts </a> </li> <li aria-haspopup="true" class=" "> <a href="form_repeater.html" class="nav-link "> Form Repeater </a> </li> <li aria-haspopup="true" class=" "> <a href="form_input_mask.html" class="nav-link "> Form Input Mask </a> </li> <li aria-haspopup="true" class=" "> <a href="form_editable.html" class="nav-link "> Form X-editable </a> </li> <li aria-haspopup="true" class=" "> <a href="form_wizard.html" class="nav-link "> Form Wizard </a> </li> <li aria-haspopup="true" class=" "> <a href="form_icheck.html" class="nav-link "> iCheck Controls </a> </li> <li aria-haspopup="true" class=" "> <a href="form_image_crop.html" class="nav-link "> Image Cropping </a> </li> <li aria-haspopup="true" class=" "> <a href="form_fileupload.html" class="nav-link "> Multiple File Upload </a> </li> <li aria-haspopup="true" class=" "> <a href="form_dropzone.html" class="nav-link "> Dropzone File Upload </a> </li> </ul> </li> <li aria-haspopup="true" class="dropdown-submenu active"> <a href="javascript:;" class="nav-link nav-toggle active"> <i class="icon-briefcase"></i> Tables <span class="arrow open"></span> </a> <ul class="dropdown-menu"> <li aria-haspopup="true" class=" "> <a href="table_static_basic.html" class="nav-link "> Basic Tables </a> </li> <li aria-haspopup="true" class=" "> <a href="<API key>.html" class="nav-link "> Responsive Tables </a> </li> <li aria-haspopup="true" class=" "> <a href="table_bootstrap.html" class="nav-link "> Bootstrap Tables </a> </li> <li aria-haspopup="true" class="dropdown-submenu active"> <a href="javascript:;" class="nav-link nav-toggle"> Datatables <span class="arrow open"></span> </a> <ul class="dropdown-menu"> <li class=""> <a href="<API key>.html" class="nav-link "> Managed Datatables </a> </li> <li class=""> <a href="<API key>.html" class="nav-link "> Buttons Extension </a> </li> <li class=""> <a href="<API key>.html" class="nav-link "> Colreorder Extension </a> </li> <li class="active"> <a href="<API key>.html" class="nav-link "> Rowreorder Extension </a> </li> <li class=""> <a href="<API key>.html" class="nav-link "> Scroller Extension </a> </li> <li class=""> <a href="<API key>.html" class="nav-link "> FixedHeader Extension </a> </li> <li class=""> <a href="<API key>.html" class="nav-link "> Responsive Extension </a> </li> <li class=""> <a href="<API key>.html" class="nav-link "> Editable Datatables </a> </li> <li class=""> <a href="<API key>.html" class="nav-link "> Ajax Datatables </a> </li> </ul> </li> </ul> </li> <li aria-haspopup="true" class="dropdown-submenu "> <a href="?p=" class="nav-link nav-toggle "> <i class="icon-wallet"></i> Portlets <span class="arrow"></span> </a> <ul class="dropdown-menu"> <li aria-haspopup="true" class=" "> <a href="portlet_boxed.html" class="nav-link "> Boxed Portlets </a> </li> <li aria-haspopup="true" class=" "> <a href="portlet_light.html" class="nav-link "> Light Portlets </a> </li> <li aria-haspopup="true" class=" "> <a href="portlet_solid.html" class="nav-link "> Solid Portlets </a> </li> <li aria-haspopup="true" class=" "> <a href="portlet_ajax.html" class="nav-link "> Ajax Portlets </a> </li> <li aria-haspopup="true" class=" "> <a href="portlet_draggable.html" class="nav-link "> Draggable Portlets </a> </li> </ul> </li> <li aria-haspopup="true" class="dropdown-submenu "> <a href="?p=" class="nav-link nav-toggle "> <i class="icon-settings"></i> Elements <span class="arrow"></span> </a> <ul class="dropdown-menu"> <li aria-haspopup="true" class=" "> <a href="elements_steps.html" class="nav-link "> Steps </a> </li> <li aria-haspopup="true" class=" "> <a href="elements_lists.html" class="nav-link "> Lists </a> </li> <li aria-haspopup="true" class=" "> <a href="elements_ribbons.html" class="nav-link "> Ribbons </a> </li> <li aria-haspopup="true" class=" "> <a href="elements_overlay.html" class="nav-link "> Overlays </a> </li> <li aria-haspopup="true" class=" "> <a href="elements_cards.html" class="nav-link "> User Cards </a> </li> </ul> </li> <li aria-haspopup="true" class="dropdown-submenu "> <a href="javascript:;" class="nav-link nav-toggle "> <i class="icon-bar-chart"></i> Charts <span class="arrow"></span> </a> <ul class="dropdown-menu"> <li aria-haspopup="true" class=" "> <a href="charts_amcharts.html" class="nav-link "> amChart </a> </li> <li aria-haspopup="true" class=" "> <a href="charts_flotcharts.html" class="nav-link "> Flot Charts </a> </li> <li aria-haspopup="true" class=" "> <a href="charts_flowchart.html" class="nav-link "> Flow Charts </a> </li> <li aria-haspopup="true" class=" "> <a href="charts_google.html" class="nav-link "> Google Charts </a> </li> <li aria-haspopup="true" class=" "> <a href="charts_echarts.html" class="nav-link "> eCharts </a> </li> <li aria-haspopup="true" class=" "> <a href="charts_morris.html" class="nav-link "> Morris Charts </a> </li> <li aria-haspopup="true" class="dropdown-submenu "> <a href="javascript:;" class="nav-link nav-toggle"> HighCharts <span class="arrow"></span> </a> <ul class="dropdown-menu"> <li class=""> <a href="charts_highcharts.html" class="nav-link " target="_blank"> HighCharts </a> </li> <li class=""> <a href="charts_highstock.html" class="nav-link " target="_blank"> HighStock </a> </li> <li class=""> <a href="charts_highmaps.html" class="nav-link " target="_blank"> HighMaps </a> </li> </ul> </li> </ul> </li> </ul> </li> <li aria-haspopup="true" class="menu-dropdown <API key> "> <a href="javascript:;"> <i class="icon-briefcase"></i> Pages <span class="arrow"></span> </a> <ul class="dropdown-menu pull-left"> <li aria-haspopup="true" class="dropdown-submenu "> <a href="javascript:;" class="nav-link nav-toggle "> <i class="icon-basket"></i> eCommerce <span class="arrow"></span> </a> <ul class="dropdown-menu"> <li aria-haspopup="true" class=" "> <a href="ecommerce_index.html" class="nav-link "> <i class="icon-home"></i> Dashboard </a> </li> <li aria-haspopup="true" class=" "> <a href="ecommerce_orders.html" class="nav-link "> <i class="icon-basket"></i> Orders </a> </li> <li aria-haspopup="true" class=" "> <a href="<API key>.html" class="nav-link "> <i class="icon-tag"></i> Order View </a> </li> <li aria-haspopup="true" class=" "> <a href="ecommerce_products.html" class="nav-link "> <i class="icon-graph"></i> Products </a> </li> <li aria-haspopup="true" class=" "> <a href="<API key>.html" class="nav-link "> <i class="icon-graph"></i> Product Edit </a> </li> </ul> </li> <li aria-haspopup="true" class="dropdown-submenu "> <a href="javascript:;" class="nav-link nav-toggle "> <i class="icon-docs"></i> Apps <span class="arrow"></span> </a> <ul class="dropdown-menu"> <li aria-haspopup="true" class=" "> <a href="app_todo.html" class="nav-link "> <i class="icon-clock"></i> Todo 1 </a> </li> <li aria-haspopup="true" class=" "> <a href="app_todo_2.html" class="nav-link "> <i class="icon-check"></i> Todo 2 </a> </li> <li aria-haspopup="true" class=" "> <a href="app_inbox.html" class="nav-link "> <i class="icon-envelope"></i> Inbox </a> </li> <li aria-haspopup="true" class=" "> <a href="app_calendar.html" class="nav-link "> <i class="icon-calendar"></i> Calendar </a> </li> <li aria-haspopup="true" class=" "> <a href="app_ticket.html" class="nav-link "> <i class="icon-notebook"></i> Support </a> </li> </ul> </li> <li aria-haspopup="true" class="dropdown-submenu "> <a href="javascript:;" class="nav-link nav-toggle "> <i class="icon-user"></i> User <span class="arrow"></span> </a> <ul class="dropdown-menu"> <li aria-haspopup="true" class=" "> <a href="page_user_profile_1.html" class="nav-link "> <i class="icon-user"></i> Profile 1 </a> </li> <li aria-haspopup="true" class=" "> <a href="<API key>.html" class="nav-link "> <i class="icon-user-female"></i> Profile 1 Account </a> </li> <li aria-haspopup="true" class=" "> <a href="<API key>.html" class="nav-link "> <i class="icon-user-following"></i> Profile 1 Help </a> </li> <li aria-haspopup="true" class=" "> <a href="page_user_profile_2.html" class="nav-link "> <i class="icon-users"></i> Profile 2 </a> </li> <li aria-haspopup="true" class="dropdown-submenu "> <a href="javascript:;" class="nav-link nav-toggle"> <i class="icon-notebook"></i> Login <span class="arrow"></span> </a> <ul class="dropdown-menu"> <li class=""> <a href="page_user_login_1.html" class="nav-link " target="_blank"> Login Page 1 </a> </li> <li class=""> <a href="page_user_login_2.html" class="nav-link " target="_blank"> Login Page 2 </a> </li> <li class=""> <a href="page_user_login_3.html" class="nav-link " target="_blank"> Login Page 3 </a> </li> <li class=""> <a href="page_user_login_4.html" class="nav-link " target="_blank"> Login Page 4 </a> </li> <li class=""> <a href="page_user_login_5.html" class="nav-link " target="_blank"> Login Page 5 </a> </li> <li class=""> <a href="page_user_login_6.html" class="nav-link " target="_blank"> Login Page 6 </a> </li> </ul> </li> <li aria-haspopup="true" class=" "> <a href="page_user_lock_1.html" class="nav-link " target="_blank"> <i class="icon-lock"></i> Lock Screen 1 </a> </li> <li aria-haspopup="true" class=" "> <a href="page_user_lock_2.html" class="nav-link " target="_blank"> <i class="icon-lock-open"></i> Lock Screen 2 </a> </li> </ul> </li> <li aria-haspopup="true" class="dropdown-submenu "> <a href="javascript:;" class="nav-link nav-toggle "> <i class="<API key>"></i> General <span class="arrow"></span> </a> <ul class="dropdown-menu"> <li aria-haspopup="true" class=" "> <a href="page_general_about.html" class="nav-link "> <i class="icon-info"></i> About </a> </li> <li aria-haspopup="true" class=" "> <a href="<API key>.html" class="nav-link "> <i class="icon-call-end"></i> Contact </a> </li> <li aria-haspopup="true" class="dropdown-submenu "> <a href="javascript:;" class="nav-link nav-toggle"> <i class="icon-notebook"></i> Portfolio <span class="arrow"></span> </a> <ul class="dropdown-menu"> <li class=""> <a href="<API key>.html" class="nav-link "> Portfolio 1 </a> </li> <li class=""> <a href="<API key>.html" class="nav-link "> Portfolio 2 </a> </li> <li class=""> <a href="<API key>.html" class="nav-link "> Portfolio 3 </a> </li> <li class=""> <a href="<API key>.html" class="nav-link "> Portfolio 4 </a> </li> </ul> </li> <li aria-haspopup="true" class="dropdown-submenu "> <a href="javascript:;" class="nav-link nav-toggle"> <i class="icon-magnifier"></i> Search <span class="arrow"></span> </a> <ul class="dropdown-menu"> <li class=""> <a href="page_general_search.html" class="nav-link "> Search 1 </a> </li> <li class=""> <a href="<API key>.html" class="nav-link "> Search 2 </a> </li> <li class=""> <a href="<API key>.html" class="nav-link "> Search 3 </a> </li> <li class=""> <a href="<API key>.html" class="nav-link "> Search 4 </a> </li> <li class=""> <a href="<API key>.html" class="nav-link "> Search 5 </a> </li> </ul> </li> <li aria-haspopup="true" class=" "> <a href="<API key>.html" class="nav-link "> <i class="icon-tag"></i> Pricing </a> </li> <li aria-haspopup="true" class=" "> <a href="page_general_faq.html" class="nav-link "> <i class="icon-wrench"></i> FAQ </a> </li> <li aria-haspopup="true" class=" "> <a href="page_general_blog.html" class="nav-link "> <i class="icon-pencil"></i> Blog </a> </li> <li aria-haspopup="true" class=" "> <a href="<API key>.html" class="nav-link "> <i class="icon-note"></i> Blog Post </a> </li> <li aria-haspopup="true" class=" "> <a href="<API key>.html" class="nav-link "> <i class="icon-envelope"></i> Invoice </a> </li> <li aria-haspopup="true" class=" "> <a href="<API key>.html" class="nav-link "> <i class="icon-envelope"></i> Invoice 2 </a> </li> </ul> </li> <li aria-haspopup="true" class="dropdown-submenu "> <a href="javascript:;" class="nav-link nav-toggle "> <i class="icon-settings"></i> System <span class="arrow"></span> </a> <ul class="dropdown-menu"> <li aria-haspopup="true" class=" "> <a href="<API key>.html" class="nav-link " target="_blank"> Coming Soon </a> </li> <li aria-haspopup="true" class=" "> <a href="page_system_404_1.html" class="nav-link "> 404 Page 1 </a> </li> <li aria-haspopup="true" class=" "> <a href="page_system_404_2.html" class="nav-link " target="_blank"> 404 Page 2 </a> </li> <li aria-haspopup="true" class=" "> <a href="page_system_404_3.html" class="nav-link " target="_blank"> 404 Page 3 </a> </li> <li aria-haspopup="true" class=" "> <a href="page_system_500_1.html" class="nav-link "> 500 Page 1 </a> </li> <li aria-haspopup="true" class=" "> <a href="page_system_500_2.html" class="nav-link " target="_blank"> 500 Page 2 </a> </li> </ul> </li> </ul> </li> </ul> </div> <!-- END MEGA MENU --> </div> </div> <!-- END HEADER MENU --> </div> <!-- END HEADER --> </div> </div> <div class="page-wrapper-row full-height"> <div class="page-wrapper-middle"> <!-- BEGIN CONTAINER --> <div class="page-container"> <!-- BEGIN CONTENT --> <div class="<API key>"> <!-- BEGIN CONTENT BODY --> <!-- BEGIN PAGE HEAD--> <div class="page-head"> <div class="container"> <!-- BEGIN PAGE TITLE --> <div class="page-title"> <h1>Rowreorder Extension <small>rowreorder extension demos</small> </h1> </div> <!-- END PAGE TITLE --> <!-- BEGIN PAGE TOOLBAR --> <div class="page-toolbar"> <!-- BEGIN THEME PANEL --> <div class="btn-group btn-theme-panel"> <a href="javascript:;" class="btn dropdown-toggle" data-toggle="dropdown"> <i class="icon-settings"></i> </a> <div class="dropdown-menu theme-panel pull-right dropdown-custom hold-on-click"> <div class="row"> <div class="col-md-6 col-sm-6 col-xs-12"> <h3>THEME COLORS</h3> <div class="row"> <div class="col-md-6 col-sm-6 col-xs-12"> <ul class="theme-colors"> <li class="theme-color theme-color-default" data-theme="default"> <span class="theme-color-view"></span> <span class="theme-color-name">Default</span> </li> <li class="theme-color <API key>" data-theme="blue-hoki"> <span class="theme-color-view"></span> <span class="theme-color-name">Blue Hoki</span> </li> <li class="theme-color <API key>" data-theme="blue-steel"> <span class="theme-color-view"></span> <span class="theme-color-name">Blue Steel</span> </li> <li class="theme-color <API key>" data-theme="yellow-orange"> <span class="theme-color-view"></span> <span class="theme-color-name">Orange</span> </li> <li class="theme-color <API key>" data-theme="yellow-crusta"> <span class="theme-color-view"></span> <span class="theme-color-name">Yellow Crusta</span> </li> </ul> </div> <div class="col-md-6 col-sm-6 col-xs-12"> <ul class="theme-colors"> <li class="theme-color <API key>" data-theme="green-haze"> <span class="theme-color-view"></span> <span class="theme-color-name">Green Haze</span> </li> <li class="theme-color <API key>" data-theme="red-sunglo"> <span class="theme-color-view"></span> <span class="theme-color-name">Red Sunglo</span> </li> <li class="theme-color <API key>" data-theme="red-intense"> <span class="theme-color-view"></span> <span class="theme-color-name">Red Intense</span> </li> <li class="theme-color <API key>" data-theme="purple-plum"> <span class="theme-color-view"></span> <span class="theme-color-name">Purple Plum</span> </li> <li class="theme-color <API key>" data-theme="purple-studio"> <span class="theme-color-view"></span> <span class="theme-color-name">Purple Studio</span> </li> </ul> </div> </div> </div> <div class="col-md-6 col-sm-6 col-xs-12 seperator"> <h3>LAYOUT</h3> <ul class="theme-settings"> <li> Theme Style <select class="theme-setting theme-setting-style form-control input-sm input-small input-inline tooltips" data-original-title="Change theme style" data-container="body" data-placement="left"> <option value="boxed" selected="selected">Square corners</option> <option value="rounded">Rounded corners</option> </select> </li> <li> Layout <select class="theme-setting <API key> form-control input-sm input-small input-inline tooltips" data-original-title="Change layout type" data-container="body" data-placement="left"> <option value="boxed" selected="selected">Boxed</option> <option value="fluid">Fluid</option> </select> </li> <li> Top Menu Style <select class="theme-setting <API key> form-control input-sm input-small input-inline tooltips" data-original-title="Change top menu dropdowns style" data-container="body" data-placement="left"> <option value="dark" selected="selected">Dark</option> <option value="light">Light</option> </select> </li> <li> Top Menu Mode <select class="theme-setting <API key> form-control input-sm input-small input-inline tooltips" data-original-title="Enable fixed(sticky) top menu" data-container="body" data-placement="left"> <option value="fixed">Fixed</option> <option value="not-fixed" selected="selected">Not Fixed</option> </select> </li> <li> Mega Menu Style <select class="theme-setting <API key> form-control input-sm input-small input-inline tooltips" data-original-title="Change mega menu dropdowns style" data-container="body" data-placement="left"> <option value="dark" selected="selected">Dark</option> <option value="light">Light</option> </select> </li> <li> Mega Menu Mode <select class="theme-setting <API key> form-control input-sm input-small input-inline tooltips" data-original-title="Enable fixed(sticky) mega menu" data-container="body" data-placement="left"> <option value="fixed" selected="selected">Fixed</option> <option value="not-fixed">Not Fixed</option> </select> </li> </ul> </div> </div> </div> </div> <!-- END THEME PANEL --> </div> <!-- END PAGE TOOLBAR --> </div> </div> <!-- END PAGE HEAD--> <!-- BEGIN PAGE CONTENT BODY --> <div class="page-content"> <div class="container"> <!-- BEGIN PAGE BREADCRUMBS --> <ul class="page-breadcrumb breadcrumb"> <li> <a href="index.html">Home</a> <i class="fa fa-circle"></i> </li> <li> <a href="#">More</a> <i class="fa fa-circle"></i> </li> <li> <a href="#">Tables</a> <i class="fa fa-circle"></i> </li> <li> <span>Datatables</span> </li> </ul> <!-- END PAGE BREADCRUMBS --> <!-- BEGIN PAGE CONTENT INNER --> <div class="page-content-inner"> <div class="m-heading-1 border-green m-bordered"> <h3>DataTables Rowreorder Extension</h3> <p> RowReorder adds the ability for rows in a DataTable to be reordered through user interaction with the table (click and drag / touch and drag). </p> <p> For more info please check out <a class="btn red btn-outline" href="http://datatables.net/extensions/rowreorder" target="_blank">the official documentation</a> </p> </div> <div class="row"> <div class="col-md-12"> <!-- BEGIN EXAMPLE TABLE PORTLET--> <div class="portlet light "> <div class="portlet-title"> <div class="caption font-dark"> <i class="icon-settings font-dark"></i> <span class="caption-subject bold uppercase">Row Reordering</span> </div> <div class="tools"> </div> </div> <div class="portlet-body"> <table class="table table-striped table-bordered table-hover" id="sample_1"> <thead> <tr> <th> Rendering engine </th> <th> Browser </th> <th> Platform(s) </th> <th> Engine version </th> <th> CSS grade </th> </tr> </thead> <tbody> <tr> <td> Trident </td> <td> Internet Explorer 4.0 </td> <td> Win 95+ </td> <td> 4 </td> <td> X </td> </tr> <tr> <td> Trident </td> <td> Internet Explorer 5.0 </td> <td> Win 95+ </td> <td> 5 </td> <td> C </td> </tr> <tr> <td> Trident </td> <td> Internet Explorer 5.5 </td> <td> Win 95+ </td> <td> 5.5 </td> <td> A </td> </tr> <tr> <td> Trident </td> <td> Internet Explorer 6 </td> <td> Win 98+ </td> <td> 6 </td> <td> A </td> </tr> <tr> <td> Trident </td> <td> Internet Explorer 7 </td> <td> Win XP SP2+ </td> <td> 7 </td> <td> A </td> </tr> <tr> <td> Trident </td> <td> AOL browser (AOL desktop) </td> <td> Win XP </td> <td> 6 </td> <td> A </td> </tr> <tr> <td> Gecko </td> <td> Firefox 1.0 </td> <td> Win 98+ / OSX.2+ </td> <td> 1.7 </td> <td> A </td> </tr> <tr> <td> Gecko </td> <td> Firefox 1.5 </td> <td> Win 98+ / OSX.2+ </td> <td> 1.8 </td> <td> A </td> </tr> <tr> <td> Gecko </td> <td> Firefox 2.0 </td> <td> Win 98+ / OSX.2+ </td> <td> 1.8 </td> <td> A </td> </tr> <tr> <td> Gecko </td> <td> Firefox 3.0 </td> <td> Win 2k+ / OSX.3+ </td> <td> 1.9 </td> <td> A </td> </tr> <tr> <td> Gecko </td> <td> Camino 1.0 </td> <td> OSX.2+ </td> <td> 1.8 </td> <td> A </td> </tr> <tr> <td> Gecko </td> <td> Camino 1.5 </td> <td> OSX.3+ </td> <td> 1.8 </td> <td> A </td> </tr> <tr> <td> Gecko </td> <td> Netscape 7.2 </td> <td> Win 95+ / Mac OS 8.6-9.2 </td> <td> 1.7 </td> <td> A </td> </tr> <tr> <td> Gecko </td> <td> Netscape Browser 8 </td> <td> Win 98SE+ </td> <td> 1.7 </td> <td> A </td> </tr> <tr> <td> Gecko </td> <td> Netscape Navigator 9 </td> <td> Win 98+ / OSX.2+ </td> <td> 1.8 </td> <td> A </td> </tr> <tr> <td> Gecko </td> <td> Mozilla 1.0 </td> <td> Win 95+ / OSX.1+ </td> <td> 1 </td> <td> A </td> </tr> <tr> <td> Gecko </td> <td> Mozilla 1.1 </td> <td> Win 95+ / OSX.1+ </td> <td> 1.1 </td> <td> A </td> </tr> <tr> <td> Gecko </td> <td> Mozilla 1.2 </td> <td> Win 95+ / OSX.1+ </td> <td> 1.2 </td> <td> A </td> </tr> <tr> <td> Gecko </td> <td> Mozilla 1.3 </td> <td> Win 95+ / OSX.1+ </td> <td> 1.3 </td> <td> A </td> </tr> <tr> <td> Gecko </td> <td> Mozilla 1.4 </td> <td> Win 95+ / OSX.1+ </td> <td> 1.4 </td> <td> A </td> </tr> <tr> <td> Gecko </td> <td> Mozilla 1.5 </td> <td> Win 95+ / OSX.1+ </td> <td> 1.5 </td> <td> A </td> </tr> <tr> <td> Gecko </td> <td> Mozilla 1.6 </td> <td> Win 95+ / OSX.1+ </td> <td> 1.6 </td> <td> A </td> </tr> <tr> <td> Gecko </td> <td> Mozilla 1.7 </td> <td> Win 98+ / OSX.1+ </td> <td> 1.7 </td> <td> A </td> </tr> <tr> <td> Gecko </td> <td> Mozilla 1.8 </td> <td> Win 98+ / OSX.1+ </td> <td> 1.8 </td> <td> A </td> </tr> <tr> <td> Gecko </td> <td> Seamonkey 1.1 </td> <td> Win 98+ / OSX.2+ </td> <td> 1.8 </td> <td> A </td> </tr> <tr> <td> Gecko </td> <td> Epiphany 2.20 </td> <td> Gnome </td> <td> 1.8 </td> <td> A </td> </tr> <tr> <td> Webkit </td> <td> Safari 1.2 </td> <td> OSX.3 </td> <td> 125.5 </td> <td> A </td> </tr> <tr> <td> Webkit </td> <td> Safari 1.3 </td> <td> OSX.3 </td> <td> 312.8 </td> <td> A </td> </tr> <tr> <td> Webkit </td> <td> Safari 2.0 </td> <td> OSX.4+ </td> <td> 419.3 </td> <td> A </td> </tr> <tr> <td> Webkit </td> <td> Safari 3.0 </td> <td> OSX.4+ </td> <td> 522.1 </td> <td> A </td> </tr> <tr> <td> Webkit </td> <td> OmniWeb 5.5 </td> <td> OSX.4+ </td> <td> 420 </td> <td> A </td> </tr> <tr> <td> Webkit </td> <td> iPod Touch / iPhone </td> <td> iPod </td> <td> 420.1 </td> <td> A </td> </tr> <tr> <td> Webkit </td> <td> S60 </td> <td> S60 </td> <td> 413 </td> <td> A </td> </tr> <tr> <td> Presto </td> <td> Opera 7.0 </td> <td> Win 95+ / OSX.1+ </td> <td> - </td> <td> A </td> </tr> <tr> <td> Presto </td> <td> Opera 7.5 </td> <td> Win 95+ / OSX.2+ </td> <td> - </td> <td> A </td> </tr> <tr> <td> Presto </td> <td> Opera 8.0 </td> <td> Win 95+ / OSX.2+ </td> <td> - </td> <td> A </td> </tr> <tr> <td> Presto </td> <td> Opera 8.5 </td> <td> Win 95+ / OSX.2+ </td> <td> - </td> <td> A </td> </tr> <tr> <td> Presto </td> <td> Opera 9.0 </td> <td> Win 95+ / OSX.3+ </td> <td> - </td> <td> A </td> </tr> <tr> <td> Presto </td> <td> Opera 9.2 </td> <td> Win 88+ / OSX.3+ </td> <td> - </td> <td> A </td> </tr> <tr> <td> Presto </td> <td> Opera 9.5 </td> <td> Win 88+ / OSX.3+ </td> <td> - </td> <td> A </td> </tr> <tr> <td> Presto </td> <td> Opera for Wii </td> <td> Wii </td> <td> - </td> <td> A </td> </tr> <tr> <td> Presto </td> <td> Nokia N800 </td> <td> N800 </td> <td> - </td> <td> A </td> </tr> <tr> <td> Presto </td> <td> Nintendo DS browser </td> <td> Nintendo DS </td> <td> 8.5 </td> <td> C/A <sup>1</sup> </td> </tr> </tbody> </table> </div> </div> <!-- END EXAMPLE TABLE PORTLET--> <!-- BEGIN EXAMPLE TABLE PORTLET--> <div class="portlet box red"> <div class="portlet-title"> <div class="caption"> <i class="fa fa-globe"></i>Row & Column Reordering </div> <div class="tools"> </div> </div> <div class="portlet-body"> <table class="table table-striped table-bordered table-hover" id="sample_2"> <thead> <tr> <th> Rendering engine </th> <th> Browser </th> <th> Platform(s) </th> <th> Engine version </th> <th> CSS grade </th> </tr> </thead> <tbody> <tr> <td> Trident </td> <td> Internet Explorer 4.0 </td> <td> Win 95+ </td> <td> 4 </td> <td> X </td> </tr> <tr> <td> Trident </td> <td> Internet Explorer 5.0 </td> <td> Win 95+ </td> <td> 5 </td> <td> C </td> </tr> <tr> <td> Trident </td> <td> Internet Explorer 5.5 </td> <td> Win 95+ </td> <td> 5.5 </td> <td> A </td> </tr> <tr> <td> Trident </td> <td> Internet Explorer 6 </td> <td> Win 98+ </td> <td> 6 </td> <td> A </td> </tr> <tr> <td> Trident </td> <td> Internet Explorer 7 </td> <td> Win XP SP2+ </td> <td> 7 </td> <td> A </td> </tr> <tr> <td> Trident </td> <td> AOL browser (AOL desktop) </td> <td> Win XP </td> <td> 6 </td> <td> A </td> </tr> <tr> <td> Gecko </td> <td> Firefox 1.0 </td> <td> Win 98+ / OSX.2+ </td> <td> 1.7 </td> <td> A </td> </tr> <tr> <td> Gecko </td> <td> Firefox 1.5 </td> <td> Win 98+ / OSX.2+ </td> <td> 1.8 </td> <td> A </td> </tr> <tr> <td> Gecko </td> <td> Firefox 2.0 </td> <td> Win 98+ / OSX.2+ </td> <td> 1.8 </td> <td> A </td> </tr> <tr> <td> Gecko </td> <td> Firefox 3.0 </td> <td> Win 2k+ / OSX.3+ </td> <td> 1.9 </td> <td> A </td> </tr> <tr> <td> Gecko </td> <td> Camino 1.0 </td> <td> OSX.2+ </td> <td> 1.8 </td> <td> A </td> </tr> <tr> <td> Gecko </td> <td> Camino 1.5 </td> <td> OSX.3+ </td> <td> 1.8 </td> <td> A </td> </tr> <tr> <td> Gecko </td> <td> Netscape 7.2 </td> <td> Win 95+ / Mac OS 8.6-9.2 </td> <td> 1.7 </td> <td> A </td> </tr> <tr> <td> Gecko </td> <td> Netscape Browser 8 </td> <td> Win 98SE+ </td> <td> 1.7 </td> <td> A </td> </tr> <tr> <td> Gecko </td> <td> Netscape Navigator 9 </td> <td> Win 98+ / OSX.2+ </td> <td> 1.8 </td> <td> A </td> </tr> <tr> <td> Gecko </td> <td> Mozilla 1.0 </td> <td> Win 95+ / OSX.1+ </td> <td> 1 </td> <td> A </td> </tr> <tr> <td> Gecko </td> <td> Mozilla 1.1 </td> <td> Win 95+ / OSX.1+ </td> <td> 1.1 </td> <td> A </td> </tr> <tr> <td> Gecko </td> <td> Mozilla 1.2 </td> <td> Win 95+ / OSX.1+ </td> <td> 1.2 </td> <td> A </td> </tr> <tr> <td> Gecko </td> <td> Mozilla 1.3 </td> <td> Win 95+ / OSX.1+ </td> <td> 1.3 </td> <td> A </td> </tr> <tr> <td> Gecko </td> <td> Mozilla 1.4 </td> <td> Win 95+ / OSX.1+ </td> <td> 1.4 </td> <td> A </td> </tr> <tr> <td> Gecko </td> <td> Mozilla 1.5 </td> <td> Win 95+ / OSX.1+ </td> <td> 1.5 </td> <td> A </td> </tr> <tr> <td> Gecko </td> <td> Mozilla 1.6 </td> <td> Win 95+ / OSX.1+ </td> <td> 1.6 </td> <td> A </td> </tr> <tr> <td> Gecko </td> <td> Mozilla 1.7 </td> <td> Win 98+ / OSX.1+ </td> <td> 1.7 </td> <td> A </td> </tr> <tr> <td> Gecko </td> <td> Mozilla 1.8 </td> <td> Win 98+ / OSX.1+ </td> <td> 1.8 </td> <td> A </td> </tr> <tr> <td> Gecko </td> <td> Seamonkey 1.1 </td> <td> Win 98+ / OSX.2+ </td> <td> 1.8 </td> <td> A </td> </tr> <tr> <td> Gecko </td> <td> Epiphany 2.20 </td> <td> Gnome </td> <td> 1.8 </td> <td> A </td> </tr> <tr> <td> Webkit </td> <td> Safari 1.2 </td> <td> OSX.3 </td> <td> 125.5 </td> <td> A </td> </tr> <tr> <td> Webkit </td> <td> Safari 1.3 </td> <td> OSX.3 </td> <td> 312.8 </td> <td> A </td> </tr> <tr> <td> Webkit </td> <td> Safari 2.0 </td> <td> OSX.4+ </td> <td> 419.3 </td> <td> A </td> </tr> <tr> <td> Webkit </td> <td> Safari 3.0 </td> <td> OSX.4+ </td> <td> 522.1 </td> <td> A </td> </tr> <tr> <td> Webkit </td> <td> OmniWeb 5.5 </td> <td> OSX.4+ </td> <td> 420 </td> <td> A </td> </tr> <tr> <td> Webkit </td> <td> iPod Touch / iPhone </td> <td> iPod </td> <td> 420.1 </td> <td> A </td> </tr> <tr> <td> Webkit </td> <td> S60 </td> <td> S60 </td> <td> 413 </td> <td> A </td> </tr> <tr> <td> Presto </td> <td> Opera 7.0 </td> <td> Win 95+ / OSX.1+ </td> <td> - </td> <td> A </td> </tr> <tr> <td> Presto </td> <td> Opera 7.5 </td> <td> Win 95+ / OSX.2+ </td> <td> - </td> <td> A </td> </tr> <tr> <td> Presto </td> <td> Opera 8.0 </td> <td> Win 95+ / OSX.2+ </td> <td> - </td> <td> A </td> </tr> <tr> <td> Presto </td> <td> Opera 8.5 </td> <td> Win 95+ / OSX.2+ </td> <td> - </td> <td> A </td> </tr> <tr> <td> Presto </td> <td> Opera 9.0 </td> <td> Win 95+ / OSX.3+ </td> <td> - </td> <td> A </td> </tr> <tr> <td> Presto </td> <td> Opera 9.2 </td> <td> Win 88+ / OSX.3+ </td> <td> - </td> <td> A </td> </tr> <tr> <td> Presto </td> <td> Opera 9.5 </td> <td> Win 88+ / OSX.3+ </td> <td> - </td> <td> A </td> </tr> <tr> <td> Presto </td> <td> Opera for Wii </td> <td> Wii </td> <td> - </td> <td> A </td> </tr> <tr> <td> Presto </td> <td> Nokia N800 </td> <td> N800 </td> <td> - </td> <td> A </td> </tr> <tr> <td> Presto </td> <td> Nintendo DS browser </td> <td> Nintendo DS </td> <td> 8.5 </td> <td> C/A <sup>1</sup> </td> </tr> </tbody> </table> </div> </div> <!-- END EXAMPLE TABLE PORTLET--> </div> </div> </div> <!-- END PAGE CONTENT INNER --> </div> </div> <!-- END PAGE CONTENT BODY --> <!-- END CONTENT BODY --> </div> <!-- END CONTENT --> <!-- BEGIN QUICK SIDEBAR --> <a href="javascript:;" class="<API key>"> <i class="icon-login"></i> </a> <div class="<API key>" <API key>="false"> <div class="page-quick-sidebar"> <ul class="nav nav-tabs"> <li class="active"> <a href="javascript:;" data-target="#quick_sidebar_tab_1" data-toggle="tab"> Users <span class="badge badge-danger">2</span> </a> </li> <li> <a href="javascript:;" data-target="#quick_sidebar_tab_2" data-toggle="tab"> Alerts <span class="badge badge-success">7</span> </a> </li> <li class="dropdown"> <a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown"> More <i class="fa fa-angle-down"></i> </a> <ul class="dropdown-menu pull-right"> <li> <a href="javascript:;" data-target="#quick_sidebar_tab_3" data-toggle="tab"> <i class="icon-bell"></i> Alerts </a> </li> <li> <a href="javascript:;" data-target="#quick_sidebar_tab_3" data-toggle="tab"> <i class="icon-info"></i> Notifications </a> </li> <li> <a href="javascript:;" data-target="#quick_sidebar_tab_3" data-toggle="tab"> <i class="icon-speech"></i> Activities </a> </li> <li class="divider"></li> <li> <a href="javascript:;" data-target="#quick_sidebar_tab_3" data-toggle="tab"> <i class="icon-settings"></i> Settings </a> </li> </ul> </li> </ul> <div class="tab-content"> <div class="tab-pane active <API key>" id="quick_sidebar_tab_1"> <div class="<API key>" data-rail-color="#ddd" data-wrapper-class="<API key>"> <h3 class="list-heading">Staff</h3> <ul class="media-list list-items"> <li class="media"> <div class="media-status"> <span class="badge badge-success">8</span> </div> <img class="media-object" src="../assets/layouts/layout/img/avatar3.jpg" alt="..."> <div class="media-body"> <h4 class="media-heading">Bob Nilson</h4> <div class="media-heading-sub"> Project Manager </div> </div> </li> <li class="media"> <img class="media-object" src="../assets/layouts/layout/img/avatar1.jpg" alt="..."> <div class="media-body"> <h4 class="media-heading">Nick Larson</h4> <div class="media-heading-sub"> Art Director </div> </div> </li> <li class="media"> <div class="media-status"> <span class="badge badge-danger">3</span> </div> <img class="media-object" src="../assets/layouts/layout/img/avatar4.jpg" alt="..."> <div class="media-body"> <h4 class="media-heading">Deon Hubert</h4> <div class="media-heading-sub"> CTO </div> </div> </li> <li class="media"> <img class="media-object" src="../assets/layouts/layout/img/avatar2.jpg" alt="..."> <div class="media-body"> <h4 class="media-heading">Ella Wong</h4> <div class="media-heading-sub"> CEO </div> </div> </li> </ul> <h3 class="list-heading">Customers</h3> <ul class="media-list list-items"> <li class="media"> <div class="media-status"> <span class="badge badge-warning">2</span> </div> <img class="media-object" src="../assets/layouts/layout/img/avatar6.jpg" alt="..."> <div class="media-body"> <h4 class="media-heading">Lara Kunis</h4> <div class="media-heading-sub"> CEO, Loop Inc </div> <div class="media-heading-small"> Last seen 03:10 AM </div> </div> </li> <li class="media"> <div class="media-status"> <span class="label label-sm label-success">new</span> </div> <img class="media-object" src="../assets/layouts/layout/img/avatar7.jpg" alt="..."> <div class="media-body"> <h4 class="media-heading">Ernie Kyllonen</h4> <div class="media-heading-sub"> Project Manager, <br> SmartBizz PTL </div> </div> </li> <li class="media"> <img class="media-object" src="../assets/layouts/layout/img/avatar8.jpg" alt="..."> <div class="media-body"> <h4 class="media-heading">Lisa Stone</h4> <div class="media-heading-sub"> CTO, Keort Inc </div> <div class="media-heading-small"> Last seen 13:10 PM </div> </div> </li> <li class="media"> <div class="media-status"> <span class="badge badge-success">7</span> </div> <img class="media-object" src="../assets/layouts/layout/img/avatar9.jpg" alt="..."> <div class="media-body"> <h4 class="media-heading">Deon Portalatin</h4> <div class="media-heading-sub"> CFO, H&D LTD </div> </div> </li> <li class="media"> <img class="media-object" src="../assets/layouts/layout/img/avatar10.jpg" alt="..."> <div class="media-body"> <h4 class="media-heading">Irina Savikova</h4> <div class="media-heading-sub"> CEO, Tizda Motors Inc </div> </div> </li> <li class="media"> <div class="media-status"> <span class="badge badge-danger">4</span> </div> <img class="media-object" src="../assets/layouts/layout/img/avatar11.jpg" alt="..."> <div class="media-body"> <h4 class="media-heading">Maria Gomez</h4> <div class="media-heading-sub"> Manager, Infomatic Inc </div> <div class="media-heading-small"> Last seen 03:10 AM </div> </div> </li> </ul> </div> <div class="<API key>"> <div class="<API key>"> <div class="<API key>"> <a href="javascript:;" class="<API key>"> <i class="icon-arrow-left"></i>Back</a> </div> <div class="<API key>"> <div class="post out"> <img class="avatar" alt="" src="../assets/layouts/layout/img/avatar3.jpg" /> <div class="message"> <span class="arrow"></span> <a href="javascript:;" class="name">Bob Nilson</a> <span class="datetime">20:15</span> <span class="body"> When could you send me the report ? </span> </div> </div> <div class="post in"> <img class="avatar" alt="" src="../assets/layouts/layout/img/avatar2.jpg" /> <div class="message"> <span class="arrow"></span> <a href="javascript:;" class="name">Ella Wong</a> <span class="datetime">20:15</span> <span class="body"> Its almost done. I will be sending it shortly </span> </div> </div> <div class="post out"> <img class="avatar" alt="" src="../assets/layouts/layout/img/avatar3.jpg" /> <div class="message"> <span class="arrow"></span> <a href="javascript:;" class="name">Bob Nilson</a> <span class="datetime">20:15</span> <span class="body"> Alright. Thanks! :) </span> </div> </div> <div class="post in"> <img class="avatar" alt="" src="../assets/layouts/layout/img/avatar2.jpg" /> <div class="message"> <span class="arrow"></span> <a href="javascript:;" class="name">Ella Wong</a> <span class="datetime">20:16</span> <span class="body"> You are most welcome. Sorry for the delay. </span> </div> </div> <div class="post out"> <img class="avatar" alt="" src="../assets/layouts/layout/img/avatar3.jpg" /> <div class="message"> <span class="arrow"></span> <a href="javascript:;" class="name">Bob Nilson</a> <span class="datetime">20:17</span> <span class="body"> No probs. Just take your time :) </span> </div> </div> <div class="post in"> <img class="avatar" alt="" src="../assets/layouts/layout/img/avatar2.jpg" /> <div class="message"> <span class="arrow"></span> <a href="javascript:;" class="name">Ella Wong</a> <span class="datetime">20:40</span> <span class="body"> Alright. I just emailed it to you. </span> </div> </div> <div class="post out"> <img class="avatar" alt="" src="../assets/layouts/layout/img/avatar3.jpg" /> <div class="message"> <span class="arrow"></span> <a href="javascript:;" class="name">Bob Nilson</a> <span class="datetime">20:17</span> <span class="body"> Great! Thanks. Will check it right away. </span> </div> </div> <div class="post in"> <img class="avatar" alt="" src="../assets/layouts/layout/img/avatar2.jpg" /> <div class="message"> <span class="arrow"></span> <a href="javascript:;" class="name">Ella Wong</a> <span class="datetime">20:40</span> <span class="body"> Please let me know if you have any comment. </span> </div> </div> <div class="post out"> <img class="avatar" alt="" src="../assets/layouts/layout/img/avatar3.jpg" /> <div class="message"> <span class="arrow"></span> <a href="javascript:;" class="name">Bob Nilson</a> <span class="datetime">20:17</span> <span class="body"> Sure. I will check and buzz you if anything needs to be corrected. </span> </div> </div> </div> <div class="<API key>"> <div class="input-group"> <input type="text" class="form-control" placeholder="Type a message here..."> <div class="input-group-btn"> <button type="button" class="btn green"> <i class="icon-paper-clip"></i> </button> </div> </div> </div> </div> </div> </div> <div class="tab-pane <API key>" id="quick_sidebar_tab_2"> <div class="<API key>"> <h3 class="list-heading">General</h3> <ul class="feeds list-items"> <li> <div class="col1"> <div class="cont"> <div class="cont-col1"> <div class="label label-sm label-info"> <i class="fa fa-check"></i> </div> </div> <div class="cont-col2"> <div class="desc"> You have 4 pending tasks. <span class="label label-sm label-warning "> Take action <i class="fa fa-share"></i> </span> </div> </div> </div> </div> <div class="col2"> <div class="date"> Just now </div> </div> </li> <li> <a href="javascript:;"> <div class="col1"> <div class="cont"> <div class="cont-col1"> <div class="label label-sm label-success"> <i class="fa fa-bar-chart-o"></i> </div> </div> <div class="cont-col2"> <div class="desc"> Finance Report for year 2013 has been released. </div> </div> </div> </div> <div class="col2"> <div class="date"> 20 mins </div> </div> </a> </li> <li> <div class="col1"> <div class="cont"> <div class="cont-col1"> <div class="label label-sm label-danger"> <i class="fa fa-user"></i> </div> </div> <div class="cont-col2"> <div class="desc"> You have 5 pending membership that requires a quick review. </div> </div> </div> </div> <div class="col2"> <div class="date"> 24 mins </div> </div> </li> <li> <div class="col1"> <div class="cont"> <div class="cont-col1"> <div class="label label-sm label-info"> <i class="fa fa-shopping-cart"></i> </div> </div> <div class="cont-col2"> <div class="desc"> New order received with <span class="label label-sm label-success"> Reference Number: DR23923 </span> </div> </div> </div> </div> <div class="col2"> <div class="date"> 30 mins </div> </div> </li> <li> <div class="col1"> <div class="cont"> <div class="cont-col1"> <div class="label label-sm label-success"> <i class="fa fa-user"></i> </div> </div> <div class="cont-col2"> <div class="desc"> You have 5 pending membership that requires a quick review. </div> </div> </div> </div> <div class="col2"> <div class="date"> 24 mins </div> </div> </li> <li> <div class="col1"> <div class="cont"> <div class="cont-col1"> <div class="label label-sm label-info"> <i class="fa fa-bell-o"></i> </div> </div> <div class="cont-col2"> <div class="desc"> Web server hardware needs to be upgraded. <span class="label label-sm label-warning"> Overdue </span> </div> </div> </div> </div> <div class="col2"> <div class="date"> 2 hours </div> </div> </li> <li> <a href="javascript:;"> <div class="col1"> <div class="cont"> <div class="cont-col1"> <div class="label label-sm label-default"> <i class="fa fa-briefcase"></i> </div> </div> <div class="cont-col2"> <div class="desc"> IPO Report for year 2013 has been released. </div> </div> </div> </div> <div class="col2"> <div class="date"> 20 mins </div> </div> </a> </li> </ul> <h3 class="list-heading">System</h3> <ul class="feeds list-items"> <li> <div class="col1"> <div class="cont"> <div class="cont-col1"> <div class="label label-sm label-info"> <i class="fa fa-check"></i> </div> </div> <div class="cont-col2"> <div class="desc"> You have 4 pending tasks. <span class="label label-sm label-warning "> Take action <i class="fa fa-share"></i> </span> </div> </div> </div> </div> <div class="col2"> <div class="date"> Just now </div> </div> </li> <li> <a href="javascript:;"> <div class="col1"> <div class="cont"> <div class="cont-col1"> <div class="label label-sm label-danger"> <i class="fa fa-bar-chart-o"></i> </div> </div> <div class="cont-col2"> <div class="desc"> Finance Report for year 2013 has been released. </div> </div> </div> </div> <div class="col2"> <div class="date"> 20 mins </div> </div> </a> </li> <li> <div class="col1"> <div class="cont"> <div class="cont-col1"> <div class="label label-sm label-default"> <i class="fa fa-user"></i> </div> </div> <div class="cont-col2"> <div class="desc"> You have 5 pending membership that requires a quick review. </div> </div> </div> </div> <div class="col2"> <div class="date"> 24 mins </div> </div> </li> <li> <div class="col1"> <div class="cont"> <div class="cont-col1"> <div class="label label-sm label-info"> <i class="fa fa-shopping-cart"></i> </div> </div> <div class="cont-col2"> <div class="desc"> New order received with <span class="label label-sm label-success"> Reference Number: DR23923 </span> </div> </div> </div> </div> <div class="col2"> <div class="date"> 30 mins </div> </div> </li> <li> <div class="col1"> <div class="cont"> <div class="cont-col1"> <div class="label label-sm label-success"> <i class="fa fa-user"></i> </div> </div> <div class="cont-col2"> <div class="desc"> You have 5 pending membership that requires a quick review. </div> </div> </div> </div> <div class="col2"> <div class="date"> 24 mins </div> </div> </li> <li> <div class="col1"> <div class="cont"> <div class="cont-col1"> <div class="label label-sm label-warning"> <i class="fa fa-bell-o"></i> </div> </div> <div class="cont-col2"> <div class="desc"> Web server hardware needs to be upgraded. <span class="label label-sm label-default "> Overdue </span> </div> </div> </div> </div> <div class="col2"> <div class="date"> 2 hours </div> </div> </li> <li> <a href="javascript:;"> <div class="col1"> <div class="cont"> <div class="cont-col1"> <div class="label label-sm label-info"> <i class="fa fa-briefcase"></i> </div> </div> <div class="cont-col2"> <div class="desc"> IPO Report for year 2013 has been released. </div> </div> </div> </div> <div class="col2"> <div class="date"> 20 mins </div> </div> </a> </li> </ul> </div> </div> <div class="tab-pane <API key>" id="quick_sidebar_tab_3"> <div class="<API key>"> <h3 class="list-heading">General Settings</h3> <ul class="list-items borderless"> <li> Enable Notifications <input type="checkbox" class="make-switch" checked data-size="small" data-on-color="success" data-on-text="ON" data-off-color="default" data-off-text="OFF"> </li> <li> Allow Tracking <input type="checkbox" class="make-switch" data-size="small" data-on-color="info" data-on-text="ON" data-off-color="default" data-off-text="OFF"> </li> <li> Log Errors <input type="checkbox" class="make-switch" checked data-size="small" data-on-color="danger" data-on-text="ON" data-off-color="default" data-off-text="OFF"> </li> <li> Auto Sumbit Issues <input type="checkbox" class="make-switch" data-size="small" data-on-color="warning" data-on-text="ON" data-off-color="default" data-off-text="OFF"> </li> <li> Enable SMS Alerts <input type="checkbox" class="make-switch" checked data-size="small" data-on-color="success" data-on-text="ON" data-off-color="default" data-off-text="OFF"> </li> </ul> <h3 class="list-heading">System Settings</h3> <ul class="list-items borderless"> <li> Security Level <select class="form-control input-inline input-sm input-small"> <option value="1">Normal</option> <option value="2" selected>Medium</option> <option value="e">High</option> </select> </li> <li> Failed Email Attempts <input class="form-control input-inline input-sm input-small" value="5" /> </li> <li> Secondary SMTP Port <input class="form-control input-inline input-sm input-small" value="3560" /> </li> <li> Notify On System Error <input type="checkbox" class="make-switch" checked data-size="small" data-on-color="danger" data-on-text="ON" data-off-color="default" data-off-text="OFF"> </li> <li> Notify On SMTP Error <input type="checkbox" class="make-switch" checked data-size="small" data-on-color="warning" data-on-text="ON" data-off-color="default" data-off-text="OFF"> </li> </ul> <div class="inner-content"> <button class="btn btn-success"> <i class="icon-settings"></i> Save Changes</button> </div> </div> </div> </div> </div> </div> <!-- END QUICK SIDEBAR --> </div> <!-- END CONTAINER --> </div> </div> <div class="page-wrapper-row"> <div class="page-wrapper-bottom"> <!-- BEGIN FOOTER --> <!-- BEGIN PRE-FOOTER --> <div class="page-prefooter"> <div class="container"> <div class="row"> <div class="col-md-3 col-sm-6 col-xs-12 footer-block"> <h2>About</h2> <p> Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam dolore. </p> </div> <div class="col-md-3 col-sm-6 col-xs12 footer-block"> <h2>Subscribe Email</h2> <div class="subscribe-form"> <form action="javascript:;"> <div class="input-group"> <input type="text" placeholder="mail@email.com" class="form-control"> <span class="input-group-btn"> <button class="btn" type="submit">Submit</button> </span> </div> </form> </div> </div> <div class="col-md-3 col-sm-6 col-xs-12 footer-block"> <h2>Follow Us On</h2> <ul class="social-icons"> <li> <a href="javascript:;" data-original-title="rss" class="rss"></a> </li> <li> <a href="javascript:;" data-original-title="facebook" class="facebook"></a> </li> <li> <a href="javascript:;" data-original-title="twitter" class="twitter"></a> </li> <li> <a href="javascript:;" data-original-title="googleplus" class="googleplus"></a> </li> <li> <a href="javascript:;" data-original-title="linkedin" class="linkedin"></a> </li> <li> <a href="javascript:;" data-original-title="youtube" class="youtube"></a> </li> <li> <a href="javascript:;" data-original-title="vimeo" class="vimeo"></a> </li> </ul> </div> <div class="col-md-3 col-sm-6 col-xs-12 footer-block"> <h2>Contacts</h2> <address class="margin-bottom-40"> Phone: 800 123 3456 <br> Email: <a href="mailto:info@metronic.com">info@metronic.com</a> </address> </div> </div> </div> </div> <!-- END PRE-FOOTER --> <!-- BEGIN INNER FOOTER --> <div class="page-footer"> <div class="container"> 2016 &copy; Metronic Theme By <a target="_blank" href="http://keenthemes.com">Keenthemes</a> &nbsp;|&nbsp; <a href="http://themeforest.net/item/<API key>/4021469?ref=keenthemes" title="Purchase Metronic just for 27$ and get lifetime updates for free" target="_blank">Purchase Metronic!</a> </div> </div> <div class="scroll-to-top"> <i class="icon-arrow-up"></i> </div> <!-- END INNER FOOTER --> <!-- END FOOTER --> </div> </div> </div> <!-- BEGIN QUICK NAV --> <nav class="quick-nav"> <a class="quick-nav-trigger" href=" <span aria-hidden="true"></span> </a> <ul> <li> <a href="https://themeforest.net/item/<API key>/4021469?ref=keenthemes" target="_blank" class="active"> <span>Purchase Metronic</span> <i class="icon-basket"></i> </a> </li> <li> <a href="https://themeforest.net/item/<API key>/reviews/4021469?ref=keenthemes" target="_blank"> <span>Customer Reviews</span> <i class="icon-users"></i> </a> </li> <li> <a href="http://keenthemes.com/showcast/" target="_blank"> <span>Showcase</span> <i class="icon-user"></i> </a> </li> <li> <a href="http://keenthemes.com/metronic-theme/changelog/" target="_blank"> <span>Changelog</span> <i class="icon-graph"></i> </a> </li> </ul> <span aria-hidden="true" class="quick-nav-bg"></span> </nav> <div class="quick-nav-overlay"></div> <!-- END QUICK NAV --> <!--[if lt IE 9]> <script src="../assets/global/plugins/respond.min.js"></script> <script src="../assets/global/plugins/excanvas.min.js"></script> <script src="../assets/global/plugins/ie8.fix.min.js"></script> <![endif] <!-- BEGIN CORE PLUGINS --> <script src="../assets/global/plugins/jquery.min.js" type="text/javascript"></script> <script src="../assets/global/plugins/bootstrap/js/bootstrap.min.js" type="text/javascript"></script> <script src="../assets/global/plugins/js.cookie.min.js" type="text/javascript"></script> <script src="../assets/global/plugins/jquery-slimscroll/jquery.slimscroll.min.js" type="text/javascript"></script> <script src="../assets/global/plugins/jquery.blockui.min.js" type="text/javascript"></script> <script src="../assets/global/plugins/bootstrap-switch/js/bootstrap-switch.min.js" type="text/javascript"></script> <!-- END CORE PLUGINS --> <!-- BEGIN PAGE LEVEL PLUGINS --> <script src="../assets/global/scripts/datatable.js" type="text/javascript"></script> <script src="../assets/global/plugins/datatables/datatables.min.js" type="text/javascript"></script> <script src="../assets/global/plugins/datatables/plugins/bootstrap/datatables.bootstrap.js" type="text/javascript"></script> <!-- END PAGE LEVEL PLUGINS --> <!-- BEGIN THEME GLOBAL SCRIPTS --> <script src="../assets/global/scripts/app.min.js" type="text/javascript"></script> <!-- END THEME GLOBAL SCRIPTS --> <!-- BEGIN PAGE LEVEL SCRIPTS --> <script src="../assets/pages/scripts/<API key>.min.js" type="text/javascript"></script> <!-- END PAGE LEVEL SCRIPTS --> <!-- BEGIN THEME LAYOUT SCRIPTS --> <script src="../assets/layouts/layout3/scripts/layout.min.js" type="text/javascript"></script> <script src="../assets/layouts/layout3/scripts/demo.min.js" type="text/javascript"></script> <script src="../assets/layouts/global/scripts/quick-sidebar.min.js" type="text/javascript"></script> <script src="../assets/layouts/global/scripts/quick-nav.min.js" type="text/javascript"></script> <!-- END THEME LAYOUT SCRIPTS --> </body> </html>
<?php function connect($host,$usuario,$pass,$bd){ $connection = mysqli_connect($host,$usuario,$pass,$bd); if(!$connection){ die("Error en la conexión ".<API key>()); } return $connection; }
define([ 'Magento_Ui/js/lib/view/utils/async', 'uiRegistry', 'underscore', 'Magento_Ui/js/form/components/insert-listing' ], function ($, registry, _, InsertListing) { 'use strict'; return InsertListing.extend({ defaults: { addAttributeUrl: '', attributeSetId: '', attributeIds: '', groupCode: '', groupName: '', groupSortOrder: 0, productId: 0, formProvider: '', modules: { form: '${ $.formProvider }', modal: '${ $.parentName }' }, productType: '' }, /** * Render attribute */ render: function () { this._super(); }, /** * Save attribute */ save: function () { this.<API key>(); this._super(); }, /** * Add selected attributes */ <API key>: function () { $.ajax({ url: this.addAttributeUrl, type: 'POST', dataType: 'json', data: { attributeIds: this.selections().getSelections(), templateId: this.attributeSetId, groupCode: this.groupCode, groupName: this.groupName, groupSortOrder: this.groupSortOrder, productId: this.productId, componentJson: 1 }, success: function () { this.form().params = { set: this.attributeSetId, id: this.productId, type: this.productType }; this.form().reload(); this.modal().state(false); this.reload(); }.bind(this) }); } }); });
package votebox; import auditorium.<API key>; import auditorium.Bugout; import auditorium.Event; import auditorium.NetworkException; import crypto.*; import crypto.adder.AdderInteger; import preptool.model.language.Language; import preptool.model.layout.manager.RenderingUtils; import printer.Printer; import sexpression.*; import sexpression.stream.<API key>; import supervisor.model.Ballot; import votebox.events.*; import votebox.middle.<API key>; import votebox.middle.Properties; import votebox.middle.driver.Driver; import votebox.middle.view.AWTViewFactory; import votebox.middle.view.IViewFactory; import javax.imageio.ImageIO; import javax.swing.*; import javax.swing.Timer; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.*; import java.util.List; /** * This is the top level votebox main class. This class organizes and connects * the components of VoteBox, namely:<br> * 1) The auditorium network<br> * 2) The vote storage backend<br> * 3) The votebox "middle" (that is, the link between the voter and the backend, * the gui) * * @author derrley, Corey Shaw */ public class VoteBox{ private final AuditoriumParams _constants; private final IViewFactory _factory; private <API key> auditorium; private Driver currentDriver; private IVoteBoxInactiveUI inactiveUI; private final int mySerial; private boolean connected; private boolean voting; private boolean promptingForPin; private boolean override; private boolean committedBallot; private boolean finishedVoting; private boolean isProvisional; private int label; private String bid; private Event<Integer> labelChangedEvent; private int protectedCount; private int publicCount; private int numConnections; private ASExpression nonce; private int pageBeforeOverride; private Timer killVBTimer; private Timer statusTimer; boolean superOnline; private int superSerial; private String precinct; private final String launchCode; private BallotCrypter<<API key>> ballotCrypter; /** Will keep the short code - nonce pairings to send over when the polls close */ private HashMap<ASExpression, VotePair> <API key>; private Printer printer; private Random rand; private File _currentBallotFile; /** A forced default value only used by the launcher */ private static File <API key> = new File(System.getProperty("user.dir") + "/tmp/ballots/ballot/ballot.zip"); /** * Default constructor: Equivalent to new VoteBox(-1) which sets a default serial of -1 */ public VoteBox(){ this(-1, "0000000000"); } /** * Constructs a new instance of a persistent VoteBox booth. This * implementation runs in the background, on an auditorium network, and * waits to receive an authorization before launching the VoteBox middle. * For a standalone implementation, see * {@link votebox.middle.datacollection.Launcher}. * * @param serial the serial number of the votebox */ public VoteBox(int serial, String launchCode) { rand = new Random(System.currentTimeMillis()); _constants = new AuditoriumParams("vb.conf"); this.launchCode = launchCode; /* If serial is not a good value, set mySerial to the default */ mySerial = (serial != -1) ? serial : _constants.<API key>(); /* If mySerial ends up with a bad number anyway, throw an error */ if(mySerial == -1) throw new RuntimeException("usage: VoteBox <machineID>"); numConnections = 0; labelChangedEvent = new Event<>(); /* Announce to auditorium the status */ statusTimer = new Timer(300000, new ActionListener() { public void actionPerformed(ActionEvent e) { if (connected) auditorium.announce(getStatus()); } }); /* Run fullscreen on OSX only */ if (_constants.<API key>().equals("AWT")) { _factory = new AWTViewFactory(_constants.getUseWindowedView(), _constants.getAllowUIScaling()); } else { throw new RuntimeException("Unknown view implementation defined in configuration"); } /* Make sure this boolean is set properly */ promptingForPin = false; /* Destroys any previous commits */ <API key> = new HashMap<>(); /* Loads default ballot file */ <API key> = new File(_constants.getBallotFile()); } /** * Broadcasts this VoteBox booth's status, and resets the status timer */ public void broadcastStatus() { auditorium.announce(getStatus()); statusTimer.restart(); } /** * Returns this booth's label, assigned by a supervisor over auditorium. If * unassigned, will return 0. * * @return the label */ public int getLabel() { return label; } /** * Returns this booth's status as a VoteBoxEvent, used for periodic broadcasts * * @return the status as a @VoteBoxEvent */ public VoteBoxEvent getStatus() { int battery = BatteryStatus.read(_constants.getOS()); /* Create the status */ String status = voting ? ( isProvisional ? "provisional-in-use" : "in-use" ) : "ready"; System.out.println("Protected count: " + protectedCount + " Public count: " + publicCount); /* Create the event corresponding to the status */ return new VoteBoxEvent(mySerial, label, status, battery, protectedCount, publicCount); } /** * Allows the VoteBox inactive UI (what is shown when a user isn't voting) * to register for a label changed event, and update itself accordingly * * @param obs the observer */ public void <API key>(Observer obs) { labelChangedEvent.addObserver(obs); } /** * Launch the VoteBox middle. Registers for events that we would want to * know about (such as cast ballot, so we can send the message over * auditorium) * * @param location the location on disk of the ballot */ public void run(String location) { inactiveUI.setVisible(false); currentDriver = new Driver(location, _factory, _constants.<API key>()); voting = true; currentDriver.run(); /* Listen for commit UI events. When received, send out an encrypted vote. */ currentDriver.getView().registerForCommit(new Observer() { /** * Handles the updating procedure after a ballot gets committed * @see Observer#update(java.util.Observable, Object) */ @SuppressWarnings("unchecked") public void update(Observable o, Object argTemp) { if (!connected) throw new RuntimeException("Attempted to cast ballot when not connected to any machines"); if (!voting || currentDriver == null) throw new RuntimeException("VoteBox attempted to cast ballot, but was not currently voting"); if (finishedVoting) throw new RuntimeException("This machine has already finished voting, but attempted to vote again"); committedBallot = true; /* Can we just get Ballot<Plaintext> type objects? */ Object[] arg = (Object[]) argTemp; /* arg0 should be the cast ballot structure, check. TODO Fix handling */ //if (RuntimeBallot.BALLOT_PATTERN.match((ASExpression) arg[0]) == NoMatch.SINGLETON) // throw new RuntimeException("Incorrectly expected a cast-ballot"); /* Convert Ballot from ASE to Ballot object TODO check if this is right, should be able to do something similar */ List<<API key>> ballotForm = ASEConverter.convertFromASE((ListExpression) arg[0]); Ballot<<API key>> ballot = new Ballot<>(bid, ballotForm, nonce.toString()); /* Encrypt Ballot */ Ballot<<API key><<API key>>> encBallot; try { encBallot = ballotCrypter.encrypt(ballot); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Could not encrypt the ballot because of " + e.getClass()); } /* Check if provisional and choose announcement format */ if (!isProvisional) { auditorium.announce(new CommitBallotEvent(mySerial, nonce, ASEConverter.convertToASE(encBallot).toVerbatim(), bid, precinct)); } /* Provisional */ else { auditorium.announce(new <API key>(mySerial, nonce, ASEConverter.convertToASE(encBallot).toVerbatim(), bid)); } /* Announce ballot printing and print */ List<List<String>> races = currentDriver.getBallotAdapter().getRaceGroups(); auditorium.announce(new BallotPrintingEvent(mySerial, bid, nonce)); printer = new Printer(_currentBallotFile, races); boolean success = printer.<API key>(ballot.getRaceSelections(), bid); printer.printedReceipt(bid); /* By this time, the voter is done voting */ /* Wait before returning to inactive */ long start = System.currentTimeMillis(); while (System.currentTimeMillis() - start < 5000) ; finishedVoting = true; System.out.println("\nBID: " + bid + "\n"); if (success) auditorium.announce(new <API key>(mySerial, bid, nonce)); } }); currentDriver.getView().<API key>( new Observer() { /** * Kill the VB runtime, and announce the confirm message * @see java.util.Observer#update(java.util.Observable, Object) */ public void update(Observable o, Object arg) { if (voting && override && !finishedVoting && currentDriver != null) { /* Announce the override */ auditorium.announce(new <API key>(mySerial, nonce)); /* Kills the voting session */ currentDriver.kill(); currentDriver = null; nonce = null; voting = false; override = false; /* Broadcast the new status */ broadcastStatus(); promptForPin("Enter Voting Authentication PIN"); } else { /* TODO runtime exception */ throw new RuntimeException("Received an <API key> event at the incorrect time"); } } }); currentDriver.getView().<API key>(new Observer() { /** * Announce the deny message, and return to the page on which the voter was previously * @see Observer#update(java.util.Observable, Object) */ public void update(Observable o, Object arg) { if (voting && override && !finishedVoting && currentDriver != null) { /* Announce the denial of the override and go back */ auditorium.announce(new <API key>(mySerial, nonce)); override = false; currentDriver.getView().drawPage(pageBeforeOverride, false); } else { /* TODO runtime exception */ throw new RuntimeException("Received an <API key> event at the incorrect time"); } } }); currentDriver.getView().<API key>(new Observer() { /** * Increment counters, and send the ballot in the confirm message. * Also kill VoteBox and show the inactive UI * * @see java.util.Observer#update(java.util.Observable, Object) */ public void update(Observable o, Object argTemp) { /* Check to see if voting is still in progress after the override commit selection */ if (voting && override && !finishedVoting && currentDriver != null) { Object[] arg = (Object[]) argTemp; /* arg1 should be the cast ballot structure, check TODO */ //if (RuntimeBallot.BALLOT_PATTERN.match((ASExpression) arg[0]) == NoMatch.SINGLETON) // throw new RuntimeException("Incorrectly expected a cast-ballot"); //TODO use this if logging fails and requires ASE -- this might make threads wait long enough for ASEParser /* Need to make the thread wait for the PDF to get created. */ //long start = System.currentTimeMillis(); //while (System.currentTimeMillis() - start < 1000); /* Convert Ballot from ASE to Ballot object TODO check if this is right, should be able to do something similar */ List<<API key>> ballotForm = ASEConverter.convertFromASE((ListExpression) arg[0]); Ballot<<API key>> ballot = new Ballot<>(bid, ballotForm, nonce.toString()); /* Encrypt Ballot */ Ballot<<API key><<API key>>> encBallot; try { encBallot = ballotCrypter.encrypt(ballot); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Could not encrypt the ballot because of "+ e.getClass()); } committedBallot = true; /* Announce that we're commiting this ballot as override to auditorium and commit it */ auditorium.announce(new <API key>(mySerial, nonce, ASEConverter.convertToASE(ballot).toVerbatim())); auditorium.announce(new CommitBallotEvent(mySerial, nonce, ASEConverter.convertToASE(encBallot).toVerbatim(), bid, precinct)); /* Broadcast new status */ broadcastStatus(); /* Announce a new printing event and print */ List<List<String>> races = currentDriver.getBallotAdapter().getRaceGroups(); auditorium.announce(new BallotPrintingEvent(mySerial, bid, nonce)); printer = new Printer(_currentBallotFile, races); /* Check for success */ boolean success = printer.<API key>(ballot.getRaceSelections(), bid); printer.printedReceipt(bid); /* By this time, the voter is done voting. Wait before returning to inactive. */ long start = System.currentTimeMillis(); while (System.currentTimeMillis() - start < 5000) ; finishedVoting = true; /* Announce successful print event or throw an error */ if (success) auditorium.announce(new <API key>(mySerial, bid, nonce)); } else { /* TODO runtime error should be graceful */ throw new RuntimeException("Received an <API key> event at the incorrect time"); } } }); currentDriver.getView().<API key>(new Observer() { /** * Announce the deny message, and return to the page the voter was * previously on * * @see java.util.Observer#update(java.util.Observable, Object) */ public void update(Observable o, Object arg) { if (voting && override && !finishedVoting && currentDriver != null) { auditorium.announce(new <API key>(mySerial, nonce)); override = false; currentDriver.getView().drawPage(pageBeforeOverride, false); } else { throw new RuntimeException("Received an override-cast-deny event at the incorrect time"); } } }); } /** * This method generates a short code for each vote on this machine, which will * eventually be sent over the wire to the controller, who will then publish the * short code - plaintext pairs and document the nonces generated here so that the * votes can be audited and verified * * @param ballot - the ballot containing all of the votes to be short coded * */ private void shortCodes(ListExpression ballot, List<List<String>> raceGroups) { try { for (ASExpression x : ballot) { ListExpression choice = (ListExpression) x; AdderInteger num = ASEConverter.convertFromASE((ListExpression) choice.get(1)); if(num == AdderInteger.ONE){ ASExpression raceId = null; /* Find the race to which the choice belongs */ for(List<String> race : raceGroups) if(race.contains(choice.get(0).toString())) raceId = ASExpression.make(race.get(0)); if(raceId == null) throw new RuntimeException("Found a vote with no race?"); /* Create a new shortcode and votepair from the raceId */ ListExpression code = new ListExpression(raceId, ASExpression.make(bid), nonce); ASExpression shortCode = ASExpression.makeVerbatim(code.getSHA256()); VotePair pair = new VotePair(shortCode, choice); /* Pair this ballot's nonce with each of its short codes and votes */ <API key>.put(nonce, pair); } } } catch (<API key> e) { throw new RuntimeException("Malformed nonce!", e); } } /** * Starts Auditorium, registers the listener, and connects to the network. */ public void start() { inactiveUI = new VoteBoxInactiveUI(this); inactiveUI.setVisible(true); try { auditorium = new <API key>(mySerial, _constants, launchCode, ActivatedEvent.getMatcher(), AssignLabelEvent.getMatcher(), <API key>.getMatcher(), BallotReceivedEvent.getMatcher(), OverrideCancelEvent.getMatcher(), OverrideCommitEvent.getMatcher(), PollsOpenQEvent.getMatcher(), PINEnteredEvent.getMatcher(), InvalidPinEvent.getMatcher(), PollsOpenEvent.getMatcher(), PollStatusEvent.getMatcher(), BallotPrintingEvent.getMatcher(), <API key>.getMatcher(), <API key>.getMatcher(), PollMachinesEvent.getMatcher(), <API key>.getMatcher()); } catch (NetworkException e1) { /* NetworkException represents a recoverable error so just note it and continue */ System.out.println("Recoverable error occurred: "+e1.getMessage()); e1.printStackTrace(System.err); } auditorium.addListener(new <API key>() { /* These are all NO-OPs because we don't respond to these */ public void ballotPrinting(BallotPrintingEvent ballotPrintingEvent) {} public void castCommittedBallot(<API key> e) { if(e.getSource() == mySerial) { publicCount++; protectedCount++; } } public void <API key>(<API key> e) {} public void overrideCancelDeny(<API key> e) {} public void lastPollsOpen(LastPollsOpenEvent e) {} public void <API key>(<API key> e) {} public void overrideCommitDeny(<API key> e) {} public void pollsClosed(PollsClosedEvent e) {} public void supervisor(SupervisorEvent e) {} public void votebox(VoteBoxEvent e) {} public void commitBallot(CommitBallotEvent e) {} public void pinEntered(PINEnteredEvent e) {} public void ballotPrintFail(<API key> e){} public void scannerStart(StartScannerEvent startScannerEvent) {} public void spoilBallot(SpoilBallotEvent spoilBallotEvent) {} public void <API key>(<API key> e) {} public void <API key>(<API key> <API key>) {} public void tapMachine(TapMachineEvent tapMachineEvent) {} public void startUpload(StartUploadEvent startUploadEvent) {} public void completedUpload(<API key> <API key>) {} public void ballotScanned(BallotScannedEvent e) {} public void ballotScanner(BallotScannerEvent e) {} public void ballotAccepted(<API key> e){} public void ballotRejected(<API key> e){} public void uploadBallots(BallotUploadEvent ballotUploadEvent) {} /** * Handler for the activated message. Look to see if this VoteBox's * status exists (and is correct), and if not, broadcast its status * * @see votebox.events.ActivatedEvent */ public void activated(ActivatedEvent e) { boolean found = false; for (StatusEvent ae : e.getStatuses()) { /* TODO NODE */ if (ae.getTargetSerial() == mySerial) { VoteBoxEvent ve = (VoteBoxEvent) ae.getStatus(); VoteBoxEvent status = getStatus(); /* Checking to make sure the status is correct */ boolean checkStatus = !ve.getStatus().equals(status.getStatus()) || ve.getBattery() != status.getBattery() || ve.getLabel() != status.getLabel() || ve.getProtectedCount() != status.getProtectedCount() || ve.getPublicCount() != status.getPublicCount(); /* Broadcast the status if any of these are not correct */ if (checkStatus) broadcastStatus(); found = true; } } /* If the StatusEvent was not found in the list of statuses, broadcast */ if (!found) broadcastStatus(); superSerial = e.getSerial(); superOnline = true; } /** * Handler for the assign-label message. If it is referring to this * booth, set the label. * * @see votebox.events.AssignLabelEvent */ public void assignLabel(AssignLabelEvent e) { /* See if this message is directed towards this machine and, if so, change the label */ if (e.getTargetSerial() == mySerial) label = e.getLabel(); /* Notify that the label was changed */ labelChangedEvent.notify(label); } /** * Handler for the authorized-to-cast message. If it is for this * booth, and it is not already voting, unzip the ballot and fire * the VoteBox runtime. Also announce the new status. * * @see votebox.events.<API key> */ public void authorizedToCast(<API key> e) { System.out.println("Detected <API key> for machine with serial " + e.getTargetSerial()); /* See if this is directed towards this machine */ if (e.getTargetSerial() == mySerial) { isProvisional = false; /* Make sure not already voting TFODO runtime exception */ System.out.println("Currently this machine is " + (voting ? "voting already!" : "not voting already!")); if (voting || (currentDriver != null && killVBTimer == null)) throw new RuntimeException( "VoteBox was authorized-to-cast, but was already voting"); /* If last VB runtime is on thank you screen and counting down to when it disappears, kill it prematurely without showing inactive UI */ if (killVBTimer != null && currentDriver != null) { /* Kill the runtime */ killVBTimer.stop(); killVBTimer = null; /* Kill voting session */ currentDriver.kill(); currentDriver = null; } nonce = e.getNonce(); /* Current working directory TODO path construction */ File path = new File(System.getProperty("user.dir")); path = new File(path, "tmp"); path = new File(path, "ballots"); path = new File(path, "ballot"/* + protectedCount*/); path.mkdirs(); bid = String.valueOf(rand.nextInt(Integer.MAX_VALUE)); precinct = e.getPrecinct(); System.out.println("Dealing with ballot " + bid + " in precinct " + precinct + "..."); System.out.println("Initialising crypto..."); <API key> cryptoType = new <API key>(); try { cryptoType.loadPublicKey(_constants.getKeyStore().loadPEK()); } catch (<API key> ex) { throw new RuntimeException("Error loading the PEK from the KeyStore."); } ballotCrypter = new BallotCrypter<>(cryptoType); System.out.println("Crypto set!"); try { System.out.println("Setting ballot file!"); /* Set ballot file */ _currentBallotFile = new File(path, "ballot.zip"); <API key> = _currentBallotFile; /* Write the ballot to file output */ FileOutputStream fout = new FileOutputStream(_currentBallotFile); byte[] ballot = e.getBallot(); fout.write(ballot); /* Takes ballot file, unzips, and unloads them into a directory to create temp directory */ Driver.unzip(new File(path, "ballot.zip").getAbsolutePath(), new File(path, "data").getAbsolutePath()); /* Sets up to delete temp directory */ Driver.<API key>(path.getAbsolutePath()); /* Starts a new voting session */ run(new File(path, "data").getAbsolutePath()); /* Broadcast current status */ broadcastStatus(); } catch (IOException e1) { throw new RuntimeException(e1); } } } /** * Handler for the ballot-received message. Show the next page on * the VB runtime (the ballot is being printed screen), and start a timer that * kills the runtime after a set amount of time (5 seconds), and * then shows the inactive screen. Also responds with its status. * * @see votebox.events.BallotReceivedEvent */ public void ballotReceived(BallotReceivedEvent e) { if (e.getTargetSerial() == mySerial && Arrays.equals(e.getNonce().toVerbatim(), nonce.toVerbatim())) { if (e.getTargetSerial() == mySerial && Arrays.equals(e.getNonce().toVerbatim(), nonce.toVerbatim())) { if (!committedBallot) throw new RuntimeException("Someone said the ballot was received, but this machine hasn't committed it yet. Maybe the supervisor is not configured properly?"); if (isProvisional) { try { /* Show provisional success page */ currentDriver.getView().drawPage(currentDriver.getView().getCurrentLayout().getProperties().getInteger(Properties.<API key>), false); } catch (<API key> e1) { e1.printStackTrace(); } } else currentDriver.getView().nextPage(); /* Show printing page */ nonce = null; voting = false; finishedVoting = false; committedBallot = false; broadcastStatus(); /* Create a timer to kill the runtime after 5 seconds */ killVBTimer = new Timer(_constants.<API key>(), new ActionListener() { public void actionPerformed(ActionEvent arg0) { currentDriver.kill(); currentDriver = null; /* Show inactive screen */ inactiveUI.setVisible(true); killVBTimer = null; /* Prompt for PIN for next voting session */ promptForPin("Enter Voting Authentication PIN"); } }); killVBTimer.setRepeats(false); killVBTimer.start(); } } } /** * Increment the number of connections when a machine joins the network * @see votebox.events.JoinEvent */ public void joined(JoinEvent e) { numConnections++; connected = true; if(e.getSerial()==superSerial) superOnline = true; } /** * Decrement the number of connections when a machine leaves the network * @see votebox.events.LeaveEvent */ public void left(LeaveEvent e) { numConnections if (numConnections == 0) connected = false; if(e.getSerial()==superSerial) superOnline = false; } /** * Handler for the override-cancel message. If it is referring to * this booth, and it is in a state that it can be overridden, send * the runtime to the proper override page and record the page the * user was previously on. * * @see votebox.events.OverrideCancelEvent */ public void overrideCancel(OverrideCancelEvent e) { if (mySerial == e.getTargetSerial() && e.getNonce().equals(nonce)) { try { /* Make sure voting is in progress */ if (voting && !finishedVoting && currentDriver != null) { /* Save the last page the voter was on before the override */ int page = currentDriver.getView().overrideCancel(); /* Go back if override is no good */ if (!override) { pageBeforeOverride = page; override = true; } } else { throw new RuntimeException("Received an override-cancel message when the user wasn't voting"); } } catch (<API key> e1) { Bugout.err("Incorrect type in overrideCancel handler"); } } } /** * Handler for the override-cast message. If it is referring to this * booth, and it is in a state that it can be overridden, send the * runtime to the proper override page and record the page the user * was previously on. * * @see votebox.events.OverrideCommitEvent */ public void overrideCommit(OverrideCommitEvent e) { /* See if this is the target of the event */ if(e.getTargetSerial() == mySerial){ try { /* Make sure voting is in progress */ if (voting && !finishedVoting && currentDriver != null) { /* Saves the last page the voter was on */ int page = currentDriver.getView().overrideCommit(); /* Go back if override is no good */ if (!override) { pageBeforeOverride = page; override = true; } } else { throw new RuntimeException("Received an override-cast message when the user wasn't voting"); } } catch (<API key> e1) { /* We don't want to bail once VoteBox is up and running, so report and continue in this case */ System.out.println("Incorrect type received in overrideCommit event: "+e1.getMessage()); e1.printStackTrace(System.err); } } } /** * Handler for Polls Open. If not voting, booth prompts for pin * @see votebox.events.PollsOpenEvent */ public void pollsOpen(PollsOpenEvent e) { if(!voting) promptForPin("Enter Authorization PIN"); } */ /* TODO: Search the log and extract an appropriate polls open message */ /* TODO need to know what this is for */ /** * Handles InvalidPinEvent and reprompts for PIN * @see votebox.events.InvalidPinEvent */ public void invalidPin(InvalidPinEvent e) { if(e.getTargetSerial() == mySerial) promptForPin("Invalid PIN: Enter Valid PIN"); } /** * Received by VoteBox booth when it joins the network after a polls open event. PIN prompt is executed. * @see votebox.events.PollStatusEvent */ public void pollStatus(PollStatusEvent pollStatusEvent) { /* Check if machine is voting, sitting with polls opened */ if(!voting && pollStatusEvent.getPollStatus() == 1) promptForPin("Enter Authorization PIN"); } /** * This indicates that the ballot was successfully printed and the voting session can safely end * @see votebox.events.<API key> */ public void ballotPrintSuccess(<API key> e){ if (e.getSerial() != mySerial && e.getBID().equals(bid) && Arrays.equals(e.getNonce().toVerbatim(), nonce.toVerbatim())) { /* This should never happen... */ if (!finishedVoting) throw new RuntimeException("Someone said the ballot was printed, but this machine hasn't finished voting yet"); broadcastStatus(); } } /** * Used as an intermittent poll on the status of this booth through auditorium * @see votebox.events.PollMachinesEvent */ public void pollMachines(PollMachinesEvent pollMachinesEvent) { broadcastStatus(); try { Thread.sleep(100); } catch (<API key> e) { e.printStackTrace(); } } /** * Handler for <API key> from supervisor. Generates ballot file path and stores ballot * @see votebox.events.<API key> */ public void <API key>(<API key> e) { if (e.getTargetSerial() == mySerial) { isProvisional = true; /* Check if already voting */ if (voting || currentDriver != null && killVBTimer == null) throw new RuntimeException("VoteBox was authorized-to-cast, but was already voting"); /* If last VB runtime is on thank you screen and counting down to when it disappears, kill it prematurely without showing inactive UI */ if (killVBTimer != null && currentDriver != null) { killVBTimer.stop(); killVBTimer = null; currentDriver.kill(); currentDriver = null; } nonce = e.getNonce(); /* Current working directory */ /* TODO path fixing */ File path = new File(System.getProperty("user.dir")); path = new File(path, "tmp"); path = new File(path, "ballots"); path = new File(path, "ballot"/* + protectedCount*/); path.mkdirs(); bid = String.valueOf(rand.nextInt(Integer.MAX_VALUE)); try { _currentBallotFile = new File(path, "ballot.zip"); <API key> = _currentBallotFile; FileOutputStream fout = new FileOutputStream(_currentBallotFile); byte[] ballot = e.getBallot(); fout.write(ballot); Driver.unzip(new File(path, "ballot.zip").getAbsolutePath(), new File(path, "data").getAbsolutePath()); Driver.<API key>(path.getAbsolutePath()); run(new File(path, "data").getAbsolutePath()); broadcastStatus(); } catch (IOException e1) { throw new RuntimeException(e1); } } } }); try { auditorium.connect(); auditorium.announce(getStatus()); } catch (NetworkException e1) { throw new RuntimeException(e1); } statusTimer.start(); } /** * Initializes a GUI dialog through which the user enters their assigned PIN. Returns with no action if * already prompting for PIN. * * @param message message displayed as the header of the PIN prompt e.g. "Please Enter Your PIN" */ public void promptForPin(String message) { /* Avoid prompting for PIN when already prompting */ if(promptingForPin) return; final PINAuthorizationGUI pinGUI = new PINAuthorizationGUI(_constants.getScreenCenterX(), _constants.getScreenCenterY()); /* Set the GUI's label to our message. */ pinGUI.setLabelText(message); /* Add a listener for the OK button so that when it gets clicked, it validates the pin. */ pinGUI.okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { /* Validate the PIN and kill the current prompt */ validatePin(pinGUI.getPin()); pinGUI.stop(); /* Tell VoteBox that the PIN is currently not being prompted */ promptingForPin = false; } }); /* Add a listener for the pin text field so that when the Enter key gets pressed, it validates the PIN. */ pinGUI.pinTextField.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent arg0) { if(arg0.getKeyCode() == KeyEvent.VK_ENTER) { /* Validate the PIN and kill the current prompt */ validatePin(pinGUI.getPin()); pinGUI.stop(); /* Tell VoteBox that the PIN is currently not being prompted */ promptingForPin = false; } } }); /* Start up the PIN prompt */ pinGUI.start(); /* Tell VoteBox that the PIN is currently being prompted */ promptingForPin = true; } /** * Generates a new PINEnteredEvent and sends over the network for validation by supervisor. * @param pin 4-digit, decimal PIN to be validated */ public void validatePin(String pin) { auditorium.announce(new PINEnteredEvent(mySerial, pin)); } /** * Renders images for write-in candidates. It gets candidate name(s) from the write-in * prompt, along with the corresponding uid (to get the filename) and type (so that this * method knows how many names to read), and uses the names to render ballot images for * the write-in candidate that contain his/her name. * * @param uid the uid of the candidate * @param type the type of the candidate ("Regular" or "Presidential") * @param names the name(s) of the candidate */ public static void renderWriteInImages(String uid, String type, String... names) { /* Render the images for the candidate names. */ BufferedImage writeInToggleButton = RenderingUtils.renderToggleButton(names[0], type.equals("Presidential") ? names[1] : "", "", 20, 600, false, false, false); BufferedImage <API key> = RenderingUtils.renderToggleButton(names[0], type.equals("Presidential") ? names[1] : "", "", 20, 600, false, false, true); BufferedImage <API key> = RenderingUtils.renderToggleButton(names[0], type.equals("Presidential") ? names[1] : "", "", 20, 600, false, true, false); BufferedImage <API key> = RenderingUtils.renderToggleButton(names[0], type.equals("Presidential") ? names[1] : "", "", 20, 600, false, true, true); BufferedImage printable = RenderingUtils.renderPrintButton(uid, names[0], type.equals("Presidential") ? names[1] : "", "", 20, 600, false, true); /* TODO Change the hardcoded font sizes? */ BufferedImage reviewButton = RenderingUtils.renderButton(names[0] + (type.equals("Presidential") ? "\n" + names[1] : ""), 12, false, true, 330, Color.WHITE, false); BufferedImage focusedReviewButton = RenderingUtils.renderButton(names[0] + (type.equals("Presidential") ? "\n" + names[1] : ""), 12, false, true, 330, Color.WHITE, true); /* Save the images to files, overwriting the previous write-in candidate images for this UID. */ String fileSeparator = System.getProperty("file.separator"); String filePath = <API key>.getAbsolutePath().substring(0, <API key>.getAbsolutePath().lastIndexOf(fileSeparator)) + fileSeparator + "media" + fileSeparator; for (Language language : Language.getAllLanguages()) { try { ImageIO.write(writeInToggleButton, "png", new File(filePath + uid + File.separator + uid + "_" + language.getShortName() + ".png")); ImageIO.write(<API key>, "png", new File(filePath + uid + File.separator + uid + "_focused_" + language.getShortName() + ".png")); ImageIO.write(<API key>, "png", new File(filePath + uid + File.separator + uid + "_selected_" + language.getShortName() + ".png")); ImageIO.write(<API key>, "png", new File(filePath + uid + File.separator + uid + "_focusedSelected_" + language.getShortName() + ".png")); ImageIO.write(reviewButton, "png", new File(filePath + uid + File.separator + uid + "_review_" + language.getShortName() + ".png")); ImageIO.write(focusedReviewButton, "png", new File(filePath + uid + File.separator + uid + "_review_focused_" + language.getShortName() + ".png")); ImageIO.write(printable, "png", new File(filePath + uid + File.separator + uid + "_printable_" + language.getShortName() + ".png")); } catch (IOException e) { System.err.println("Unable to render write-in candidate images!"); return; } } } /** * A getter method to send the BallotFile to the printer * * @return _currentBallotFile - the current ballot */ public File <API key>(){ return _currentBallotFile; } /** * Main entry point into the program. If an argument is given, it will be * the serial number, otherwise VoteBox will load a serial from its config file. * * @param args */ public static void main(String[] args) { String launchCode = ""; while (launchCode == null || launchCode.equals("")) launchCode = JOptionPane.showInputDialog(null, "Please enter today's election launch code:", "Launch Code", JOptionPane.QUESTION_MESSAGE); if (args.length == 1) new VoteBox(Integer.parseInt(args[0]), launchCode).start(); else /* Tell VoteBox to refer to its config file for the serial number */ new VoteBox().start(); } }
layout: "docs" page_title: "Commands" sidebar_current: "docs-commands" description: |- Consul is controlled via a very easy to use command-line interface (CLI). Consul is only a single command-line application: `consul`. This application then takes a subcommand such as agent or members. The complete list of subcommands is in the navigation to the left. # Consul Commands (CLI) Consul is controlled via a very easy to use command-line interface (CLI). Consul is only a single command-line application: `consul`. This application then takes a subcommand such as "agent" or "members". The complete list of subcommands is in the navigation to the left. The `Consul` CLI is a well-behaved command line application. In erroneous cases, a non-zero exit status will be returned. It also responds to `-h` and `--help` as you'd most likely expect. And some commands that expect input accept "-" as a parameter to tell Consul to read the input from stdin. To view a list of the available commands at any time, just run `consul` with no arguments: text $ consul usage: consul [--version] [--help] <command> [<args>] Available commands are: agent Runs a Consul agent configtest Validate config file event Fire a new event exec Executes a command on Consul nodes force-leave Forces a member of the cluster to enter the "left" state info Provides debugging information for operators join Tell Consul agent to join cluster keygen Generates a new encryption key keyring Manages gossip layer encryption keys kv Interact with the KV store leave Gracefully leaves the Consul cluster and shuts down lock Execute a command holding a lock maint Controls node or service maintenance mode members Lists the members of a Consul cluster monitor Stream logs from a Consul agent operator Provides cluster-level tools for Consul operators reload Triggers the agent to reload configuration files rtt Estimates network round trip time between nodes version Prints the Consul version watch Watch for changes in Consul To get help for any specific command, pass the `-h` flag to the relevant subcommand. For example, to see help about the `join` subcommand: text $ consul join -h Usage: consul join [options] address ... Tells a running Consul agent (with "consul agent") to join the cluster by specifying at least one existing member. HTTP API Options -http-addr=<address> The `address` and port of the Consul HTTP agent. The value can be an IP address or DNS address, but it must also include the port. This can also be specified via the CONSUL_HTTP_ADDR environment variable. The default value is http://127.0.0.1:8500. The scheme can also be set to HTTPS by setting the environment variable CONSUL_HTTP_SSL=true. -token=<value> ACL token to use in the request. This can also be specified via the CONSUL_HTTP_TOKEN environment variable. If unspecified, the query will default to the token of the Consul agent at the HTTP address. Command Options -wan Joins a server to another server in the WAN pool. ## Environment Variables In addition to CLI flags, Consul reads environment variables for behavior defaults. CLI flags always take precedence over environment variables, but it is often helpful to use environment variables to configure the Consul agent, particularly with configuration management and init systems. These environment variables and their purpose are described below: ## `CONSUL_HTTP_ADDR` This is the HTTP API address to the *local* Consul agent (not the remote server) specified as a URI: CONSUL_HTTP_ADDR=127.0.0.1:8500 or as a Unix socket path: CONSUL_HTTP_ADDR=unix://var/run/consul_http.sock `CONSUL_HTTP_TOKEN` This is the API access token required when access control lists (ACLs) are enabled, for example: CONSUL_HTTP_<API key> `CONSUL_HTTP_AUTH` This specifies HTTP Basic access credentials as a username:password pair: CONSUL_HTTP_AUTH=operations:JPIMCmhDHzTukgO6 `CONSUL_HTTP_SSL` This is a boolean value (default is false) that enables the HTTPS URI scheme and SSL connections to the HTTP API: CONSUL_HTTP_SSL=true `<API key>` This is a boolean value (default true) to specify SSL certificate verification; setting this value to `false` is not recommended for production use. Example for development purposes: <API key>=false
package com.bfh.logisim.fpgaboardeditor; import java.util.Iterator; import java.util.LinkedList; public class FPGAClass { public static char getId(String identifier) { char result = 0; LinkedList<String> thelist = FPGAClass.getStrings(); Iterator<String> iter = thelist.iterator(); result = 0; while (iter.hasNext()) { if (iter.next().toUpperCase().equals(identifier.toUpperCase())) return result; result++; } return VendorUnknown; } public static LinkedList<String> getStrings() { LinkedList<String> result = new LinkedList<String>(); result.add(Vendors[0]); result.add(Vendors[1]); result.add(Vendors[2]); return result; } public static char VendorAltera = 0; public static char VendorXilinx = 1; public static char VendorVivado = 2; public static char VendorUnknown = 255; public static String[] Vendors = { "Altera", "Xilinx", "Vivado" }; private long ClockFrequency; private String ClockPinLocation; private char ClockPullBehavior; private char ClockIOStandard; private String Technology; private String Part; private String Package; private String SpeedGrade; private char Vendor; private char UnusedPinsBehavior; private boolean FPGADefined; private boolean USBTMCDownload; private int JTAGPos; private String FlashName; private int FlashPos; private boolean FlashDefined; public FPGAClass() { ClockFrequency = 0; ClockPinLocation = null; ClockPullBehavior = 0; ClockIOStandard = 0; Technology = null; Part = null; Package = null; SpeedGrade = null; Vendor = 0; FPGADefined = false; UnusedPinsBehavior = 0; USBTMCDownload = false; JTAGPos = 1; FlashName = null; FlashPos = 2; FlashDefined = false; } public void clear() { ClockFrequency = 0; ClockPinLocation = null; ClockPullBehavior = 0; ClockIOStandard = 0; Technology = null; Part = null; Package = null; SpeedGrade = null; Vendor = 0; FPGADefined = false; UnusedPinsBehavior = 0; USBTMCDownload = false; JTAGPos = 1; FlashName = null; FlashPos = 2; FlashDefined = false; } public boolean FpgaInfoPresent() { return FPGADefined; } public long getClockFrequency() { return ClockFrequency; } public String getClockPinLocation() { return ClockPinLocation; } public char getClockPull() { return ClockPullBehavior; } public char getClockStandard() { return ClockIOStandard; } public String getPackage() { return Package; } public String getPart() { return Part; } public String getSpeedGrade() { return SpeedGrade; } public String getTechnology() { return Technology; } public char <API key>() { return UnusedPinsBehavior; } public char getVendor() { return Vendor; } public int <API key>() { return JTAGPos; } public void Set(long frequency, String pin, String pull, String standard, String tech, String device, String box, String speed, String vend, String unused, boolean UsbTmc, String JTAGPos, String flashName, String flashPos) { ClockFrequency = frequency; ClockPinLocation = pin; ClockPullBehavior = PullBehaviors.getId(pull); ClockIOStandard = IoStandards.getId(standard); Technology = tech; Part = device; Package = box; SpeedGrade = speed; Vendor = getId(vend); FPGADefined = true; UnusedPinsBehavior = PullBehaviors.getId(unused); USBTMCDownload = UsbTmc; this.JTAGPos = Integer.valueOf(JTAGPos); this.FlashName = flashName; this.FlashPos = Integer.valueOf(flashPos); this.FlashDefined = (flashName != null) && (!flashName.isEmpty()) && (this.FlashPos != 0); } public Boolean <API key>() { return USBTMCDownload; } public String getFlashName() { return FlashName; } public int <API key>() { return FlashPos; } public boolean isFlashDefined() { return FlashDefined; } }
<?php // This file keeps track of upgrades to // the certificate module // Sometimes, changes between versions involve // alterations to database structures and other // major things that may break installations. // The upgrade function in this file will attempt // to perform all the necessary actions to upgrade // your older installation to the current version. // If there's something it cannot do itself, it // will tell you what you need to do. // The commands in here will all be database-neutral, // using the functions defined in lib/ddllib.php function <API key>($oldversion=0) { global $CFG, $THEME, $DB; $dbman = $DB->get_manager(); if ($oldversion < 2013053102) { $table = new xmldb_table('customcertificate'); // Changing type of field certdatefmt on table customcertificate to char $field = new xmldb_field('certdatefmt', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, 'certdate'); // Launch change of type for field certdatefmt $dbman->change_field_type($table, $field); // customcertificate savepoint reached <API key>(true, 2013053102, 'customcertificate'); } return true; }
package se.idega.idegaweb.commune.presentation; import java.util.Collection; import java.util.Iterator; import com.idega.core.builder.data.ICPage; import com.idega.data.IDOLookup; import com.idega.presentation.ExceptionWrapper; import com.idega.presentation.IWContext; import com.idega.presentation.PresentationObject; import com.idega.presentation.Table; import com.idega.presentation.text.Break; import com.idega.presentation.text.Link; import com.idega.presentation.text.Text; import com.idega.presentation.ui.Form; import com.idega.user.business.GroupBusiness; import com.idega.user.data.Group; import com.idega.user.data.GroupHome; import com.idega.util.StringHandler; /** * @author <a href="mailto:tryggvi@idega.is">Tryggvi Larusson</a> * @version 1.0 */ public class <API key> extends CommuneBlock { private final static String <API key> = "se.idega.idegaweb.commune"; private final static int <API key> = 2; private final static int <API key> = 3; //final static String PARAM_MANAGER_ID = ManagerView.PARAM_MANAGER_ID; final static String <API key>="comm_manvw_gr_id"; private Table mainTable = null; private int managerListPageID = -1; private int topGroupID=-1; private boolean addHeader=false; public String getBundleIdentifier() { return <API key>; } public void main(IWContext iwc)throws Exception { try { int action = parseAction(iwc); initGroupID(iwc); //System.out.println("main: action="+action); switch (action) { case <API key> : viewManagerList(iwc); break; case <API key> : viewManagerGroup(); break; default : viewNoGroups(); break; } super.add(mainTable); } catch (Exception e) { super.add(new ExceptionWrapper(e, this)); } } /** * Method viewNoGroups. * @param iwc */ private void viewNoGroups() { add(getSmallText(localize("<API key>.<API key>", "No management group set"))); } /** * Method initGroupID. * @param iwc */ private void initGroupID(IWContext iwc) { if(iwc.isParameterSet(<API key>)){ try{ int i = Integer.parseInt(iwc.getParameter(<API key>)); topGroupID=i; } catch(<API key> ne){ } } } public Object clone(){ <API key> view = (<API key>)super.clone(); if(mainTable!=null){ view.mainTable=(Table)mainTable.clone(); } return view; } public void add(PresentationObject po) { if (mainTable == null) { mainTable = new Table(); mainTable.setCellpadding(14); mainTable.setCellspacing(0); mainTable.setColor(getBackgroundColor()); mainTable.setWidth(600); } mainTable.add(po); } private int parseAction(IWContext iwc) { int action = -1; if(topGroupID!=-1){ //if topGroupID==-1 then it cant vew a manager list action=<API key>; } if(iwc.isParameterSet(<API key>)){ action = <API key>; } return action; } private void viewManagerList(IWContext iwc) throws Exception { //System.out.println("viewManagerList()"); if(addHeader){ add(getLocalizedHeader("<API key>.managergroups", "Managergroups:")); add(new Break(2)); } //if (iwc.isLoggedOn()) { //Collection users = <API key>(iwc).<API key>(); Group topGroup = getTopGroup(); Collection groups=null; groups = getGroupBusiness(iwc).getChildGroups(topGroup); //groups = topGroup.getChildGroups(); if (groups != null & !groups.isEmpty()) { Form f = new Form(); ColumnList messageList = new ColumnList(2); f.add(messageList); messageList.setBackroundColor("#e0e0e0"); messageList.setHeader(localize("<API key>.name", "Name"), 1); PresentationObject userName = null; //CheckBox deleteCheck = null; //boolean isRead = false; if (groups != null) { Iterator iter = groups.iterator(); while (iter.hasNext()) { try { Group group = (Group) iter.next(); Text tUserName = getSmallText(getStringOrDash(group.getName())); Link lUserName = new Link(tUserName); userName = lUserName; if(managerListPageID!=-1){ lUserName.setPage(managerListPageID); } lUserName.addParameter(<API key>,group.getPrimaryKey().toString()); messageList.add(userName); Text tDesc = getSmallText(getStringOrDash(group.getDescription())); messageList.add(tDesc); } catch (Exception e) { add(e); e.printStackTrace(); } //messageList.add(deleteCheck); } } messageList.skip(2); add(f); } else { add(getSmallText(localize("<API key>.no_managers", "No managers"))); } } /** * Returns the top group to display groups under. * @return Group */ private Group getTopGroup() { try{ GroupHome gHome = (GroupHome)IDOLookup.getHome(Group.class); return gHome.findByPrimaryKey(new Integer(getTopGroupID())); } catch(Exception e){ throw new RuntimeException(e.getMessage()); } } private void viewManagerGroup() throws Exception { //System.out.println("viewManager()"); add(new ManagerListView()); } /* Commented out since it is never used... private CaseBusiness getCaseBusiness(IWContext iwc) throws Exception { return (CaseBusiness) com.idega.business.IBOLookup.getServiceInstance(iwc, CaseBusiness.class); }*/ /* Commented out since it is never used... private CommuneCaseBusiness <API key>(IWContext iwc) throws Exception { return (CommuneCaseBusiness) com.idega.business.IBOLookup.getServiceInstance(iwc, CommuneCaseBusiness.class); }*/ /* Commented out since it is never used... private UserBusiness getUserBusiness(IWContext iwc) throws Exception { return (UserBusiness) com.idega.business.IBOLookup.getServiceInstance(iwc, UserBusiness.class); }*/ private GroupBusiness getGroupBusiness(IWContext iwc) throws Exception { return (GroupBusiness) com.idega.business.IBOLookup.getServiceInstance(iwc, GroupBusiness.class); } /* Commented out since it is never used... private CommuneUserBusiness <API key>(IWContext iwc) throws Exception { return (CommuneUserBusiness) com.idega.business.IBOLookup.getServiceInstance(iwc, CommuneUserBusiness.class); }*/ public void <API key>(ICPage page) { <API key>(((Integer)page.getPrimaryKey()).intValue()); } public void <API key>(int ib_page_id) { managerListPageID = ib_page_id; } public int <API key>() { return managerListPageID; } /** * Returns the groupID. * @return int */ public int getTopGroupID() { return topGroupID; } public void setTopGroup(Group group){ int groupID = ((Integer)group.getPrimaryKey()).intValue(); setTopGroupID(groupID); } /** * Sets the groupID. * @param groupID The groupID to set */ public void setTopGroupID(int groupID) { this.topGroupID = groupID; } /** * Returns the addHeader. * @return boolean */ public boolean isAddHeader() { return addHeader; } /** * Sets the addHeader. * @param addHeader The addHeader to set */ public void setAddHeader(boolean addHeader) { this.addHeader = addHeader; } /** * Returns a string or dash if there is no string * @param str String to check * @return String which is either a dash or a string if */ private String getStringOrDash(String str){ return StringHandler.getStringOrDash(str); } }
using EloBuddy; using LeagueSharp.SDK; namespace ExorAIO.Champions.Tristana { using System.Collections.Generic; using System.Linq; using LeagueSharp; using LeagueSharp.SDK; using LeagueSharp.SDK.Utils; <summary> The targets class. </summary> internal class Targets { #region Public Properties <summary> The jungle minion targets. </summary> public static List<Obj_AI_Minion> JungleMinions => GameObjects.Jungle.Where( m => m.IsValidTarget(GameObjects.Player.<API key>()) && (!GameObjects.JungleSmall.Contains(m) || m.BaseSkinName.Equals("Sru_Crab"))).ToList(); <summary> The minions target. </summary> public static List<Obj_AI_Minion> Minions => GameObjects.EnemyMinions.Where( m => m.IsMinion() && m.IsValidTarget(GameObjects.Player.<API key>())).ToList(); <summary> The main hero target. </summary> public static AIHeroClient Target => Variables.TargetSelector.GetTarget(GameObjects.Player.<API key>(), DamageType.Physical); #endregion } }
package com.moro.mtweaks.database.tools.customcontrols; import android.content.Context; import com.moro.mtweaks.database.Provider; import com.moro.mtweaks.utils.tools.customcontrols.Items; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class Controls extends Provider { public static final int VERSION = 1; public Controls(Context context) { super(context.getFilesDir() + "/controls.json", 1); } @Override public DBJsonItem getItem(JSONObject item) { return new ControlItem(item); } public void putItem(HashMap<String, Object> items) { JSONObject object = new JSONObject(); for (String key : items.keySet()) { try { object.put(key, items.get(key)); } catch (JSONException ignored) { } } putItem(object); } public List<ControlItem> getAllControls() { List<ControlItem> items = new ArrayList<>(); for (DBJsonItem item : getAllItems()) { items.add(new ControlItem(item.getItem())); } return items; } public static class ControlItem extends DBJsonItem { private ControlItem(JSONObject object) { super(object); } public String getId() { return getString("id"); } public int getUniqueId() { try { return getItem().getInt("uniqueId"); } catch (JSONException ignored) { return 0; } } public String getTitle() { return getString("title"); } public String getDescription() { return getString("description"); } public String getApply() { return getString("apply"); } public Items.Control getControl() { return Items.Control.getControl(getString("id")); } public boolean isOnBootEnabled() { try { return getItem().getBoolean("onboot"); } catch (JSONException ignored) { return false; } } public String getArguments() { return getString("arguments"); } public void enableOnBoot(boolean enable) { try { getItem().put("onboot", enable); } catch (JSONException ignored) { } } public void setArguments(String arguments) { try { getItem().put("arguments", arguments); } catch (JSONException ignored) { } } } }
#!/usr/bin/python # This file is part of Ansible # Ansible is free software: you can redistribute it and/or modify # (at your option) any later version. # Ansible is distributed in the hope that it will be useful, # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the import json import time import yaml try: import boto import boto.cloudformation.connection HAS_BOTO = True except ImportError: HAS_BOTO = False def boto_exception(err): '''generic error message handler''' if hasattr(err, 'error_message'): error = err.error_message elif hasattr(err, 'message'): error = err.message else: error = '%s: %s' % (Exception, err) return error def <API key>(version_tuple): parts = boto.Version.split('.') boto_version = [] try: for part in parts: boto_version.append(int(part)) except: boto_version.append(-1) return tuple(boto_version) >= tuple(version_tuple) def stack_operation(cfn, stack_name, operation): '''gets the status of a stack while it is created/updated/deleted''' existed = [] result = {} operation_complete = False while operation_complete == False: try: stack = <API key>(cfn.describe_stacks, stack_name)[0] existed.append('yes') except: if 'yes' in existed: result = dict(changed=True, output='Stack Deleted', events=map(str, list(stack.describe_events()))) else: result = dict(changed= True, output='Stack Not Found') break if '%s_COMPLETE' % operation == stack.stack_status: result = dict(changed=True, events = map(str, list(stack.describe_events())), output = 'Stack %s complete' % operation) break if 'ROLLBACK_COMPLETE' == stack.stack_status or '%s_ROLLBACK_COMPLETE' % operation == stack.stack_status: result = dict(changed=True, failed=True, events = map(str, list(stack.describe_events())), output = 'Problem with %s. Rollback complete' % operation) break elif '%s_FAILED' % operation == stack.stack_status: result = dict(changed=True, failed=True, events = map(str, list(stack.describe_events())), output = 'Stack %s failed' % operation) break elif '%s_ROLLBACK_FAILED' % operation == stack.stack_status: result = dict(changed=True, failed=True, events = map(str, list(stack.describe_events())), output = 'Stack %s rollback failed' % operation) break else: time.sleep(5) return result IGNORE_CODE = 'Throttling' MAX_RETRIES=3 def <API key>(function_ref, *argv): retries=0 while True: try: retval=function_ref(*argv) return retval except boto.exception.BotoServerError, e: if e.code != IGNORE_CODE or retries==MAX_RETRIES: raise e time.sleep(5 * (2**retries)) retries += 1 def main(): argument_spec = ec2_argument_spec() argument_spec.update(dict( stack_name=dict(required=True), template_parameters=dict(required=False, type='dict', default={}), state=dict(default='present', choices=['present', 'absent']), template=dict(default=None, required=False), stack_policy=dict(default=None, required=False), disable_rollback=dict(default=False, type='bool'), template_url=dict(default=None, required=False), template_format=dict(default='json', choices=['json', 'yaml'], required=False), tags=dict(default=None) ) ) module = AnsibleModule( argument_spec=argument_spec, mutually_exclusive=[['template_url', 'template']], ) if not HAS_BOTO: module.fail_json(msg='boto required for this module') if module.params['template'] is None and module.params['template_url'] is None: module.fail_json(msg='Either template or template_url expected') state = module.params['state'] stack_name = module.params['stack_name'] if module.params['template'] is None and module.params['template_url'] is None: if state == 'present': module.fail_json('Module parameter "template" or "template_url" is required if "state" is "present"') if module.params['template'] is not None: template_body = open(module.params['template'], 'r').read() else: template_body = None if module.params['template_format'] == 'yaml': if template_body is None: module.fail_json(msg='yaml format only supported for local templates') else: template_body = json.dumps(yaml.load(template_body), indent=2) if module.params['stack_policy'] is not None: stack_policy_body = open(module.params['stack_policy'], 'r').read() else: stack_policy_body = None disable_rollback = module.params['disable_rollback'] template_parameters = module.params['template_parameters'] tags = module.params['tags'] template_url = module.params['template_url'] region, ec2_url, aws_connect_kwargs = <API key>(module) kwargs = dict() if tags is not None: if not <API key>((2,6,0)): module.fail_json(msg='Module parameter "tags" requires at least Boto version 2.6.0') kwargs['tags'] = tags # convert the template parameters ansible passes into a tuple for boto <API key> = [(k, v) for k, v in template_parameters.items()] stack_outputs = {} try: cfn = boto.cloudformation.connect_to_region( region, **aws_connect_kwargs ) except boto.exception.NoAuthHandlerFound, e: module.fail_json(msg=str(e)) update = False result = {} operation = None # if state is present we are going to ensure that the stack is either # created or updated if state == 'present': try: cfn.create_stack(stack_name, parameters=<API key>, template_body=template_body, stack_policy_body=stack_policy_body, template_url=template_url, disable_rollback=disable_rollback, capabilities=['CAPABILITY_IAM'], **kwargs) operation = 'CREATE' except Exception, err: error_msg = boto_exception(err) if '<API key>' in error_msg or 'already exists' in error_msg: update = True else: module.fail_json(msg=error_msg) if not update: result = stack_operation(cfn, stack_name, operation) # if the state is present and the stack already exists, we try to update it # AWS will tell us if the stack template and parameters are the same and # don't need to be updated. if update: try: cfn.update_stack(stack_name, parameters=<API key>, template_body=template_body, stack_policy_body=stack_policy_body, disable_rollback=disable_rollback, template_url=template_url, capabilities=['CAPABILITY_IAM']) operation = 'UPDATE' except Exception, err: error_msg = boto_exception(err) if 'No updates are to be performed.' in error_msg: result = dict(changed=False, output='Stack is already up-to-date.') else: module.fail_json(msg=error_msg) if operation == 'UPDATE': result = stack_operation(cfn, stack_name, operation) # check the status of the stack while we are creating/updating it. # and get the outputs of the stack if state == 'present' or update: stack = <API key>(cfn.describe_stacks,stack_name)[0] for output in stack.outputs: stack_outputs[output.key] = output.value result['stack_outputs'] = stack_outputs # absent state is different because of the way delete_stack works. # problem is it it doesn't give an error if stack isn't found # so must describe the stack first if state == 'absent': try: <API key>(cfn.describe_stacks,stack_name) operation = 'DELETE' except Exception, err: error_msg = boto_exception(err) if 'Stack:%s does not exist' % stack_name in error_msg: result = dict(changed=False, output='Stack not found.') else: module.fail_json(msg=error_msg) if operation == 'DELETE': cfn.delete_stack(stack_name) result = stack_operation(cfn, stack_name, operation) module.exit_json(**result) # import module snippets from ansible.module_utils.basic import * from ansible.module_utils.ec2 import * main()
#! /bin/sh BEGIN INIT INFO # Provides: shutdownsw.sh # Required-Start: $local_fs $remote_fs # Required-Stop: # Default-Start: 2 3 4 5 # Default-Stop: 0 1 6 # Short-Description: Shutdown Switch Monitor # Description: Push the button then Shutdown Sqeuence be started. END INIT INFO # Please remove the "Author" lines above and replace them # with your own name if you copy and modify this script. # Do NOT "set -e"
package de.rwth.idsg.steve.ocpp; import lombok.Getter; import lombok.<API key>; /** * @author Sevket Goekay <goekay@dbis.rwth-aachen.de> * @since 24.03.2015 */ @<API key> @Getter public enum OcppProtocol { V_12_SOAP(OcppVersion.V_12, OcppTransport.SOAP), V_12_JSON(OcppVersion.V_12, OcppTransport.JSON), V_15_SOAP(OcppVersion.V_15, OcppTransport.SOAP), V_15_JSON(OcppVersion.V_15, OcppTransport.JSON); private final OcppVersion version; private final OcppTransport transport; public String getCompositeValue() { return version.getValue() + transport.getValue(); } }
<?php class <API key> extends Exception { }
package ast.declarations; import ast.ASTNode; import ast.expressions.Identifier; public class IdentifierDecl extends ASTNode { private IdentifierDeclType type; private Identifier name; public void addChild(ASTNode node) { if (node instanceof Identifier) setName((Identifier) node); else if (node instanceof IdentifierDeclType) setType((IdentifierDeclType) node); super.addChild(node); } private void setName(Identifier name) { this.name = name; } private void setType(IdentifierDeclType type) { this.type = type; } public Identifier getName() { return name; } public IdentifierDeclType getType() { return type; } }
#include <assert.h> #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <stdarg.h> #include "tvheadend.h" #include "htsbuf.h" void htsbuf_queue_init(htsbuf_queue_t *hq, unsigned int maxsize) { if(maxsize == 0) maxsize = INT32_MAX; TAILQ_INIT(&hq->hq_q); hq->hq_size = 0; hq->hq_maxsize = maxsize; } htsbuf_queue_t * htsbuf_queue_alloc(unsigned int maxsize) { htsbuf_queue_t *hq = malloc(sizeof(htsbuf_queue_t)); htsbuf_queue_init(hq, maxsize); return hq; } void htsbuf_data_free(htsbuf_queue_t *hq, htsbuf_data_t *hd) { TAILQ_REMOVE(&hq->hq_q, hd, hd_link); free(hd->hd_data); free(hd); } void htsbuf_queue_flush(htsbuf_queue_t *hq) { htsbuf_data_t *hd; hq->hq_size = 0; while((hd = TAILQ_FIRST(&hq->hq_q)) != NULL) htsbuf_data_free(hq, hd); } void htsbuf_append(htsbuf_queue_t *hq, const void *buf, size_t len) { htsbuf_data_t *hd = TAILQ_LAST(&hq->hq_q, htsbuf_data_queue); int c; hq->hq_size += len; if(hd != NULL) { /* Fill out any previous buffer */ c = MIN(hd->hd_data_size - hd->hd_data_len, len); memcpy(hd->hd_data + hd->hd_data_len, buf, c); hd->hd_data_len += c; buf += c; len -= c; } if(len == 0) return; hd = malloc(sizeof(htsbuf_data_t)); TAILQ_INSERT_TAIL(&hq->hq_q, hd, hd_link); c = MAX(len, 1000); /* Allocate 1000 bytes to support lots of small writes */ hd->hd_data = malloc(c); hd->hd_data_size = c; hd->hd_data_len = len; hd->hd_data_off = 0; memcpy(hd->hd_data, buf, len); } void <API key>(htsbuf_queue_t *hq, const void *buf, size_t len) { htsbuf_data_t *hd; hq->hq_size += len; hd = malloc(sizeof(htsbuf_data_t)); TAILQ_INSERT_TAIL(&hq->hq_q, hd, hd_link); hd->hd_data = (void *)buf; hd->hd_data_size = len; hd->hd_data_len = len; hd->hd_data_off = 0; } size_t htsbuf_read(htsbuf_queue_t *hq, void *buf, size_t len) { size_t r = 0; int c; htsbuf_data_t *hd; while(len > 0) { hd = TAILQ_FIRST(&hq->hq_q); if(hd == NULL) break; c = MIN(hd->hd_data_len - hd->hd_data_off, len); memcpy(buf, hd->hd_data + hd->hd_data_off, c); r += c; buf += c; len -= c; hd->hd_data_off += c; hq->hq_size -= c; if(hd->hd_data_off == hd->hd_data_len) htsbuf_data_free(hq, hd); } return r; } size_t htsbuf_find(htsbuf_queue_t *hq, uint8_t v) { htsbuf_data_t *hd; int i, o = 0; TAILQ_FOREACH(hd, &hq->hq_q, hd_link) { for(i = hd->hd_data_off; i < hd->hd_data_len; i++) { if(hd->hd_data[i] == v) return o + i - hd->hd_data_off; } o += hd->hd_data_len - hd->hd_data_off; } return -1; } size_t htsbuf_peek(htsbuf_queue_t *hq, void *buf, size_t len) { size_t r = 0; int c; htsbuf_data_t *hd = TAILQ_FIRST(&hq->hq_q); while(len > 0 && hd != NULL) { c = MIN(hd->hd_data_len - hd->hd_data_off, len); memcpy(buf, hd->hd_data + hd->hd_data_off, c); r += c; buf += c; len -= c; hd = TAILQ_NEXT(hd, hd_link); } return r; } size_t htsbuf_drop(htsbuf_queue_t *hq, size_t len) { size_t r = 0; int c; htsbuf_data_t *hd; while(len > 0) { hd = TAILQ_FIRST(&hq->hq_q); if(hd == NULL) break; c = MIN(hd->hd_data_len - hd->hd_data_off, len); len -= c; hd->hd_data_off += c; hq->hq_size -= c; r += c; if(hd->hd_data_off == hd->hd_data_len) htsbuf_data_free(hq, hd); } return r; } /** * Inspired by vsnprintf man page */ void htsbuf_vqprintf(htsbuf_queue_t *hq, const char *fmt, va_list ap0) { // First try to format it on-stack va_list ap; int n, size; char buf[100], *p, *np; va_copy(ap, ap0); n = vsnprintf(buf, sizeof(buf), fmt, ap); if(n > -1 && n < sizeof(buf)) { htsbuf_append(hq, buf, n); return; } // Else, do allocations size = sizeof(buf) * 2; p = malloc(size); while (1) { /* Try to print in the allocated space. */ va_copy(ap, ap0); n = vsnprintf(p, size, fmt, ap); if(n > -1 && n < size) { <API key>(hq, p, n); return; } /* Else try again with more space. */ if (n > -1) /* glibc 2.1 */ size = n+1; /* precisely what is needed */ else /* glibc 2.0 */ size *= 2; /* twice the old size */ if ((np = realloc (p, size)) == NULL) { free(p); abort(); } else { p = np; } } } void htsbuf_qprintf(htsbuf_queue_t *hq, const char *fmt, ...) { va_list ap; va_start(ap, fmt); htsbuf_vqprintf(hq, fmt, ap); va_end(ap); } void htsbuf_appendq(htsbuf_queue_t *hq, htsbuf_queue_t *src) { htsbuf_data_t *hd; hq->hq_size += src->hq_size; src->hq_size = 0; while((hd = TAILQ_FIRST(&src->hq_q)) != NULL) { TAILQ_REMOVE(&src->hq_q, hd, hd_link); TAILQ_INSERT_TAIL(&hq->hq_q, hd, hd_link); } } void <API key>(htsbuf_queue_t *hq) { htsbuf_data_t *hd; char n = '\n'; TAILQ_FOREACH(hd, &hq->hq_q, hd_link) { if(write(2, hd->hd_data + hd->hd_data_off, hd->hd_data_len - hd->hd_data_off) != hd->hd_data_len - hd->hd_data_off) break; } if(write(2, &n, 1) != 1) return; } void htsbuf_hexdump(htsbuf_queue_t *hq, const char *prefix) { void *r = malloc(hq->hq_size); htsbuf_peek(hq, r, hq->hq_size); hexdump(prefix, r, hq->hq_size); free(r); } void <API key>(htsbuf_queue_t *hq, const char *s) { const char *c = s; const char *e = s + strlen(s); if(e == s) return; while(1) { const char *esc; switch(*c++) { case '<': esc = "&lt;"; break; case '>': esc = "&gt;"; break; case '&': esc = "&amp;"; break; case '\'': esc = "&apos;"; break; case '"': esc = "&quot;"; break; default: esc = NULL; break; } if(esc != NULL) { htsbuf_append(hq, s, c - s - 1); htsbuf_append(hq, esc, strlen(esc)); s = c; } if(c == e) { htsbuf_append(hq, s, c - s); break; } } } void <API key>(htsbuf_queue_t *hq, const char *s) { const char *c = s; const char *e = s + strlen(s); char C; if(e == s) return; while(1) { const char *esc; C = *c++; if((C >= '0' && C <= '9') || (C >= 'a' && C <= 'z') || (C >= 'A' && C <= 'Z') || C == '_' || C == '~' || C == '.' || C == '-') { esc = NULL; } else { static const char hexchars[16] = "0123456789ABCDEF"; char buf[4]; buf[0] = '%'; buf[1] = hexchars[(C >> 4) & 0xf]; buf[2] = hexchars[C & 0xf];; buf[3] = 0; esc = buf; } if(esc != NULL) { htsbuf_append(hq, s, c - s - 1); htsbuf_append(hq, esc, strlen(esc)); s = c; } if(c == e) { htsbuf_append(hq, s, c - s); break; } } } void <API key>(htsbuf_queue_t *hq, const char *str) { const char *s = str; htsbuf_append(hq, "\"", 1); while(*s != 0) { if(*s == '"' || *s == '\\' || *s == '\n' || *s == '\r' || *s == '\t') { htsbuf_append(hq, str, s - str); if(*s == '"') htsbuf_append(hq, "\\\"", 2); else if(*s == '\n') htsbuf_append(hq, "\\n", 2); else if(*s == '\r') htsbuf_append(hq, "\\r", 2); else if(*s == '\t') htsbuf_append(hq, "\\t", 2); else htsbuf_append(hq, "\\\\", 2); s++; str = s; } else { s++; } } htsbuf_append(hq, str, s - str); htsbuf_append(hq, "\"", 1); } char * htsbuf_to_string(htsbuf_queue_t *hq) { char *r = malloc(hq->hq_size + 1); r[hq->hq_size] = 0; htsbuf_read(hq, r, hq->hq_size); return r; }
<?php // Moodle is free software: you can redistribute it and/or modify // (at your option) any later version. // Moodle is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the defined('MOODLE_INTERNAL') || die(); $string['admindirname'] = 'Direutoriu d\'alministración'; $string['availablelangs'] = 'Paquetes d\'idioma disponibles'; $string['chooselanguagehead'] = 'Escueya idioma'; $string['chooselanguagesub'] = 'Escueya un idioma NAMÁS pa la instalación. va poder escoyer l\'idioma del sitiu y l\'idioma d\'usuariu nes pantayes vinientes.'; $string['dataroot'] = 'Direutoriu de datos'; $string['dbprefix'] = 'Prefixu de les tables'; $string['dirroot'] = 'Direutoriu Moodle'; $string['environmenthead'] = 'Verificando\'l so ámbitu ...'; $string['installation'] = 'Instalación'; $string['langdownloaderror'] = 'Desgraciadamente l\'idioma "{$a}" nun ta instaláu. El procesu d\'instalación va siguir n\'inglés.'; $string['memorylimithelp'] = '<p>La llende de memoria del PHP del so servidor ta actualmente establecida en {$a}.</p> <p>Esto va facer que Moodle tenga problemes de memoria más tarde, especialmente si tien munchos módulos y/o munchos usuarios.</p> <p>Recomendamos que configure PHP con una llende más grande si ye posible, como por exemplu 40M. Esisten varies formes nes que pue intentar facer esta modificación:</p> <ol> <li>Si pue, recompile PHP con <i>--enable-memory-limit</i>. Esto va permitir que\'l propiu Moodle modifique la llende de memoria.</li> <li>Si tien accesu al so ficheru php.ini pue modificar el valor de <b>memory_limit</b> a daqué paecío a 40M. Si nun tien accesu a esi ficheru igual pue pidir al alministrador del sistema que lo faiga.</li> <li>En dellos servidores PHP pue crear un ficheru .htaccess nel direutoriu Moodle cola ringlera que vien darréu: <p><blockquote>php_value memory_limit 40M</blockquote></p> <p>De toles maneres, en dellos servidores esto va provocar que <b>nun funcione nenguna</b>páxina en PHP (va ver erros de la qu\'intente ver les páxines) polo que va tener qu\'esborrar el ficheru .htaccess.</p></li> </ol>'; $string['phpversion'] = 'Versión PHP'; $string['phpversionhelp'] = '<p>Moodle necesita una versión de PHP de 4.3.0 como mínimo o 5.1.0 (5.0.x tien problemes conocíos).</p> <p>Actualmente tien instalada la versión {$a}</p> <p>Tien d\'actualizar el PHP o migrar a otru servidor con una versión más nueva de PHP!<br/> (Nel casu de tener una versión 5.0.x pue tornar a una versión 4.4.x)</p>'; $string['welcomep10'] = '{$a->installername} ({$a->installerversion})'; $string['welcomep20'] = 'Ta viendo esta páxina porque consiguió instalar y arrancar el paquete <strong>{$a->packname} {$a->packversion}</strong> nel so ordeandor. ¡Felicidaes!'; $string['welcomep30'] = 'Esta versión de <strong>{$a->installername}</strong> inclúi les aplicaciones pa crear l\'ámbitu nel que <strong>Moodle</strong> pue funcionar, llamaes:'; $string['welcomep40'] = 'El paquete tamién inclúi <strong>Moodle {$a->moodlerelease} ({$a->moodleversion})</strong>.'; $string['welcomep50'] = 'L\'usu de toles aplicaciones d\'esti paquete ta reguláu poles respeutives llicencies. El paquete <strong>{$a->installername}</strong> completu ye <a href="http: $string['welcomep60'] = 'Les páxines siguientes van llevalu per dellos pasos fáciles de siguir pa configurar <strong>Moodle</strong> nel ordenador. Pue aceptar la configuración por defeutu o, opcionalmente, usar otres más adaptaes a les sos necesidaes.'; $string['welcomep70'] = 'Calque\'l botón "Siguiente" qu\'hai embaxo pa siguir cola configuración de <strong>Moodle</strong>.'; $string['wwwroot'] = 'Direición web';
package edu.grinnell.csc207.gaocharl17.utils; import static org.junit.Assert.*; import java.math.BigInteger; import org.junit.Test; import edu.grinnell.csc207.gaocharl17.utils.Fraction; public class StringUtilsTest { @Test public void testSplitAt() { assertArrayEquals(new String[] { "a", "b", "c" }, StringUtils.splitAt("a:b:c", ':')); } @Test public void testSplitAt2() { assertArrayEquals(new String[] { "a", "b", "c" }, StringUtils.splitAt("a b c", ' ')); } @Test public void testSplitAt3() { assertArrayEquals(new String[] {"a b c"}, StringUtils.splitAt("a b c", ';')); } @Test public void testSplitAt4() { assertArrayEquals(new String[] {"a", "b", "c", "/", "p"}, StringUtils.splitAt("arbrcr/rp", 'r')); } @Test public void testSplitAt5() { assertArrayEquals(new String[] { "a", "b", "c" }, StringUtils.splitCSV("a,b,c")); } @Test public void testSplitAt6() { assertArrayEquals(new String[] { "a,b", "c" }, StringUtils.splitCSV("\"a,b\",c")); } @Test public void testSplitAt7() { assertArrayEquals(new String[] { "a", "b,b\"", "c" }, StringUtils.splitCSV("a,\"b,b\"\"\",c")); } @Test public void testSplitAt8() { assertArrayEquals(new String[] { "a", "b\"b", "c" }, StringUtils.splitCSV("a,\"b\"\"b\",c")); } @Test public void testCalcAt9() { assertEquals(BigInteger.valueOf(0), StringUtils.calculatorEval0("0")); } @Test public void testSplitAt10() { assertEquals(BigInteger.valueOf(2), StringUtils.calculatorEval0("1 + 1")); } @Test public void testSplitAt11() { assertEquals(BigInteger.valueOf(4), StringUtils.calculatorEval0("1 + 2 + 1")); } @Test public void testSplitAt12() { assertEquals(BigInteger.valueOf(9), StringUtils.calculatorEval0("1 + 2 * 3")); } @Test public void testCalcAt13() { assertEquals(new Fraction("1/1").toString(), StringUtils.calculatorEval1("1/2 + 1/2").toString()); } @Test public void testCalcAt14() { assertEquals(new Fraction("4/5").toString(), StringUtils.calculatorEval1("1/1 - 1/5").toString()); } @Test public void testCalcAt15() { assertEquals(new Fraction("4/5").toString(), StringUtils.calculatorEval1("2/5 * 2/1").toString()); } }
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_77) on Fri Apr 01 12:47:18 CEST 2016 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>net.sf.jclal.sampling.unsupervised (JCLAL framework 1.1 API)</title> <meta name="date" content="2016-04-01"> <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="net.sf.jclal.sampling.unsupervised (JCLAL framework 1.1 API)"; } } catch(err) { } </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <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 class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-use.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/jclal/sampling/supervised/package-summary.html">Prev&nbsp;Package</a></li> <li><a href="../../../../../net/sf/jclal/util/dataset/package-summary.html">Next&nbsp;Package</a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?net/sf/jclal/sampling/unsupervised/package-summary.html" target="_top">Frames</a></li> <li><a href="package-summary.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip.navbar.top"> </a></div> <div class="header"> <h1 title="Package" class="title">Package&nbsp;net.sf.jclal.sampling.unsupervised</h1> <div class="docSummary"> <div class="block">The package contains the sampling's class used to construct the initial labeled set.</div> </div> <p>See:&nbsp;<a href="#package.description">Description</a></p> </div> <div class="contentContainer"> <ul class="blockList"> <li class="blockList"> <table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation"> <caption><span>Class Summary</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Class</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="../../../../../net/sf/jclal/sampling/unsupervised/Resample.html" title="class in net.sf.jclal.sampling.unsupervised">Resample</a></td> <td class="colLast"> <div class="block">Produces a random subsample of a dataset using either sampling with replacement or without replacement.</div> </td> </tr> </tbody> </table> </li> </ul> <a name="package.description"> </a> <h2 title="Package net.sf.jclal.sampling.unsupervised Description">Package net.sf.jclal.sampling.unsupervised Description</h2> <div class="block">The package contains the sampling's class used to construct the initial labeled set.</div> </div> <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 class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-use.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/jclal/sampling/supervised/package-summary.html">Prev&nbsp;Package</a></li> <li><a href="../../../../../net/sf/jclal/util/dataset/package-summary.html">Next&nbsp;Package</a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?net/sf/jclal/sampling/unsupervised/package-summary.html" target="_top">Frames</a></li> <li><a href="package-summary.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip.navbar.bottom"> </a></div> <p class="legalCopy"><small>Copyright & </body> </html>
// Project ProjectForge Community Edition // This community edition is free software; you can redistribute it and/or // This community edition is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General package org.projectforge.plugins.skillmatrix; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Transient; import org.hibernate.search.annotations.Field; import org.hibernate.search.annotations.Index; import org.hibernate.search.annotations.Indexed; import org.hibernate.search.annotations.IndexedEmbedded; import org.hibernate.search.annotations.Store; import org.projectforge.core.DefaultBaseDO; import org.projectforge.core.PropertyInfo; import org.projectforge.core.UserPrefParameter; import org.projectforge.database.Constants; /** * A skill usable for a skill-matrix. * @author Billy Duong (b.duong@micromata.de) * */ @Entity @Indexed @Table(name = "T_PLUGIN_SKILL") public class SkillDO extends DefaultBaseDO { private static final long serialVersionUID = <API key>; @PropertyInfo(i18nKey = "plugins.skillmatrix.skill.title") @Field(index = Index.TOKENIZED, store = Store.NO) private String title; // Null if this skill is a top level skill. @PropertyInfo(i18nKey = "plugins.skillmatrix.skill.parent") @IndexedEmbedded(depth = 1) private SkillDO parent; @PropertyInfo(i18nKey = "plugins.skillmatrix.skill.description") @UserPrefParameter(i18nKey = "description", multiline = true) @Field(index = Index.TOKENIZED, store = Store.NO) private String description; @PropertyInfo(i18nKey = "plugins.skillmatrix.skill.comment") @UserPrefParameter(i18nKey = "comment", multiline = true) @Field(index = Index.TOKENIZED, store = Store.NO) private String comment; @PropertyInfo(i18nKey = "plugins.skillmatrix.skill.rateable") private boolean rateable = true; private String fullAccessGroupIds, <API key>, trainingGroupsIds; @Column(length = 255) public String getTitle() { return title; } /** * @param title * @return this for chaining. */ public SkillDO setTitle(final String title) { this.title = title; return this; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "parent_fk") public SkillDO getParent() { return parent; } @Transient public Integer getParentId() { return parent != null ? parent.getId() : null; } /** * @param parent * @return this for chaining. */ public SkillDO setParent(final SkillDO parent) { this.parent = parent; return this; } @Column(length = Constants.LENGTH_TEXT) public String getComment() { return comment; } /** * @return this for chaining. */ public SkillDO setComment(final String comment) { this.comment = comment; return this; } /** * This value should be false for skills which should be used as categories or sub categories for which a rating isn't useful. But for * some categories is it useful to define them as rateable (e. g. for Programming languages -> Java -> J2EE the skill Java should be * rateable). */ @Column public boolean isRateable() { return rateable; } /** * @return this for chaining. */ public SkillDO setRateable(final boolean rateable) { this.rateable = rateable; return this; } @Column(length = Constants.LENGTH_TEXT) public String getDescription() { return description; } /** * @return this for chaining. */ public SkillDO setDescription(final String description) { this.description = description; return this; } /** * Members of these groups have full read/write access to this skill and related trainings. * @return the fullAccessGroupIds */ @Column(name = "<API key>", length = 4000, nullable = true) public String <API key>() { return fullAccessGroupIds; } /** * These users have full read/write access to this skill. * @param fullAccessGroupIds the fullAccessGroupIds to set * @return this for chaining. */ public SkillDO <API key>(final String fullAccessGroupIds) { this.fullAccessGroupIds = fullAccessGroupIds; return this; } /** * Members of these groups have full read-only access to this skill. * @return the <API key> */ @Column(name = "<API key>", length = 4000, nullable = true) public String <API key>() { return <API key>; } /** * @param <API key> the <API key> to set * @return this for chaining. */ public SkillDO <API key>(final String <API key>) { this.<API key> = <API key>; return this; } /** * Members of these groups have full read/write access to trainings of this skill. * @return the trainingGroupsIds */ @Column(name = "<API key>", length = 4000, nullable = true) public String <API key>() { return trainingGroupsIds; } /** * These users have full read/write access to trainings of this skill. * @param trainingGroupsIds the trainingGroupsIds to set * @return this for chaining. */ public SkillDO <API key>(final String trainingGroupsIds) { this.trainingGroupsIds = trainingGroupsIds; return this; } }
#import "THPaletteItem.h" #import "<API key>.h" @interface THTimerPaletteItem : <API key> @end
#include "stdafx.h" #include "eVehicle.h" #include "MercApi.h" #include "VehicleApi.h" #include "../../main/Logger.h" #include "../../httpclient/UrlEncode.h" #include "../../httpclient/HTTPClient.h" #include "../../main/json_helper.h" #include "../../main/Helper.h" #include "../../main/SQLHelper.h" #include "../../webserver/Base64.h" #include <sstream> #include <iomanip> // Assumes that one has a registered Mercedes ME account and using the MB developer portal // registers for the following BYOCAR (Bring Your Own CAR) API's: // - Fuel Status // - Pay as you drive // - Vehicle Lock status // - Vehicle status // - Electric Vehicle status (even possible for non-electric/hybrid vehicles) // so use the following 5 scope's: mb:vehicle:mbdata:vehiclestatus mb:vehicle:mbdata:fuelstatus mb:vehicle:mbdata:payasyoudrive mb:vehicle:mbdata:vehiclelock mb:vehicle:mbdata:evstatus // and we need the additional scope to get a refresh token: offline_access #define MERC_URL_AUTH "https://id.mercedes-benz.com" #define MERC_API_TOKEN "/as/token.oauth2" #define MERC_URL "https://api.mercedes-benz.com" #define MERC_API "/vehicledata/v2/vehicles" #define MERC_APITIMEOUT (30) #define <API key> "Refreshtoken cleared because it was invalid!" #define <API key> "<API key>" CMercApi::CMercApi(const std::string &username, const std::string &password, const std::string &vinnr) { m_username = username; m_password = base64_encode(username); m_VIN = vinnr; m_authtoken = password; m_accesstoken = ""; m_refreshtoken = ""; m_uservar_refresh<API key>; <API key> = 0; m_authenticating = false; m_carid = 0; m_config.car_name = ""; m_config.unit_miles = false; m_config.distance_unit = "km"; m_config.home_latitude = 0; m_config.home_longitude = 0; m_crc = 0; m_fields = ""; m_fieldcnt = -1; m_capabilities.has_battery_level = true; m_capabilities.has_charge_command = false; m_capabilities.has_climate_command = false; m_capabilities.has_defrost_command = false; m_capabilities.has_inside_temp = false; m_capabilities.has_outside_temp = false; m_capabilities.has_odo = true; m_capabilities.has_lock_status = true; m_capabilities.has_charge_limit = false; m_capabilities.has_custom_data = true; m_capabilities.seconds_to_sleep = 0; m_capabilities.<API key> = 60; std::vector<std::vector<std::string> > result; result = m_sql.safe_query("SELECT ID, Value FROM UserVariables WHERE (Name=='%q')", <API key>.c_str()); if (result.empty()) { m_sql.safe_query("INSERT INTO UserVariables (Name, ValueType, Value) VALUES ('%q',%d,'%q')", <API key>.c_str(), USERVARTYPE_STRING, m_refreshtoken.c_str()); result = m_sql.safe_query("SELECT ID, Value FROM UserVariables WHERE (Name=='%q')", <API key>.c_str()); if (result.empty()) return; } <API key> = atoi(result[0][0].c_str()); m_refreshtoken = result[0][1]; } bool CMercApi::Login() { bool bSuccess = false; std::string sLastUpdate = TimeToString(nullptr, TF_DateTime); if (m_refreshtoken.empty() || m_refresh<API key>) { m_pBase->Log(LOG_NORM, "Attempting login (using provided Authorization code)."); m_authenticating = true; if (GetAuthToken(m_username, m_authtoken, false)) { m_pBase->Log(LOG_NORM, "Login successful."); m_sql.safe_query("UPDATE UserVariables SET Value='%q', LastUpdate='%q' WHERE (ID==%d)", m_refreshtoken.c_str(), sLastUpdate.c_str(), <API key>); bSuccess = true; } else { m_pBase->Log(LOG_ERROR, "Login unsuccessful!"); } m_authenticating = false; } else { m_pBase->Log(LOG_NORM, "Attempting (re)login (using stored refresh token!)."); bSuccess = RefreshLogin(); } return bSuccess; } bool CMercApi::RefreshLogin() { bool bSuccess = false; std::string sLastUpdate = TimeToString(nullptr, TF_DateTime); m_pBase->Debug(DEBUG_NORM, "Refreshing login credentials."); m_authenticating = true; if (GetAuthToken("", "", true)) { m_pBase->Log(LOG_NORM, "Login credentials Refresh successful."); bSuccess = true; } else { m_pBase->Log(LOG_ERROR, "Failed to refresh login credentials."); m_accesstoken = ""; if (!m_refreshtoken.empty()) { m_refresh<API key>; } } m_authenticating = false; m_sql.safe_query("UPDATE UserVariables SET Value='%q', LastUpdate='%q' WHERE (ID==%d)", m_refreshtoken.c_str(), sLastUpdate.c_str(), <API key>); return bSuccess; } bool CMercApi::GetAllData(tAllCarData& data) { bool bSucces = false; bSucces = GetVehicleData(data.vehicle); bSucces = bSucces && GetLocationData(data.location); bSucces = bSucces && GetChargeData(data.charge); bSucces = bSucces && GetClimateData(data.climate); bSucces = bSucces && GetCustomData(data.custom); return bSucces; } bool CMercApi::GetLocationData(tLocationData& data) { return true; // not implemented for Mercedes /* Json::Value reply; if (GetData("drive_state", reply)) { GetLocationData(reply["response"], data); return true; } return false; */ } void CMercApi::GetLocationData(Json::Value& jsondata, tLocationData& data) { /* std::string CarLatitude = jsondata["latitude"].asString(); std::string CarLongitude = jsondata["longitude"].asString(); data.speed = jsondata["speed"].asInt(); data.is_driving = data.speed > 0; data.latitude = std::stod(CarLatitude); data.longitude = std::stod(CarLongitude); */ } bool CMercApi::GetChargeData(CVehicleApi::tChargeData& data) { Json::Value reply; bool bData = false; if (GetData("electricvehicle", reply)) { data.battery_level = 255.0F; // Initialize at 'no reading' if (reply.empty()) { bData = true; // This occurs when the API call return a 204 (No Content). So everything is valid/ok, just no data } else { if (!reply.isArray()) { m_pBase->Log(LOG_ERROR, "Unexpected reply from ElectricVehicle."); } else { GetChargeData(reply, data); bData = true; } } } else { if (m_httpresultcode == 403) { m_pBase->Log(LOG_STATUS, "Access has been denied to the ElectricVehicle data!"); bData = true; // We should see if we can continue with the rest } } return bData; } void CMercApi::GetChargeData(Json::Value& jsondata, CVehicleApi::tChargeData& data) { uint8_t cnt = 0; do { Json::Value iter; iter = jsondata[cnt]; for (auto const& id : iter.getMemberNames()) { if(!(iter[id].isNull())) { m_pBase->Debug(DEBUG_NORM, "Found non empty field %s", id.c_str()); if (id == "soc") { Json::Value iter2; iter2 = iter[id]; if(!iter2["value"].empty()) { m_pBase->Debug(DEBUG_NORM, "SoC has value %s", iter2["value"].asString().c_str()); data.battery_level = static_cast<float>(atof(iter2["value"].asString().c_str())); } } if (id == "rangeelectric") { Json::Value iter2; iter2 = iter[id]; if(!iter2["value"].empty()) { m_pBase->Debug(DEBUG_NORM, "RangeElectric has value %s", iter2["value"].asString().c_str()); data.status_string = "Approximate range " + iter2["value"].asString() + " " + m_config.distance_unit; } } } } cnt++; } while (!jsondata[cnt].empty()); } bool CMercApi::GetClimateData(tClimateData& data) { return true; // not implemented for Mercedes /* Json::Value reply; if (GetData("climate_state", reply)) { GetClimateData(reply["response"], data); return true; } return false; */ } void CMercApi::GetClimateData(Json::Value& jsondata, tClimateData& data) { /* data.inside_temp = jsondata["inside_temp"].asFloat(); data.outside_temp = jsondata["outside_temp"].asFloat(); data.is_climate_on = jsondata["is_climate_on"].asBool(); data.is_defrost_on = (jsondata["defrost_mode"].asInt() != 0); */ } bool CMercApi::GetVehicleData(tVehicleData& data) { Json::Value reply; bool bData = false; if (GetData("vehiclelockstatus", reply)) { if (reply.empty()) { bData = true; // This occurs when the API call return a 204 (No Content). So everything is valid/ok, just no data } else { if (!reply.isArray()) { m_pBase->Log(LOG_ERROR, "Unexpected reply from VehicleLockStatus."); } else { GetVehicleData(reply, data); bData = true; } } } else { if (m_httpresultcode == 403) { m_pBase->Log(LOG_STATUS, "Access has been denied to the VehicleLockStatus data!"); bData = true; // We should see if we can continue with the rest } } reply.clear(); if (GetData("payasyoudrive", reply)) { if (reply.empty()) { bData = true; // This occurs when the API call return a 204 (No Content). So everything is valid/ok, just no data } else { if (!reply.isArray()) { m_pBase->Log(LOG_ERROR, "Unexpected reply from PayasyouDrive."); } else { GetVehicleData(reply, data); bData = true; } } } else { if (m_httpresultcode == 403) { m_pBase->Log(LOG_STATUS, "Access has been denied to the PayAsYouDrive data!"); bData = true; // We should see if we can continue with the rest } } return bData; } bool CMercApi::GetCustomData(tCustomData& data) { Json::Value reply; std::vector<std::string> strarray; if (m_capabilities.has_custom_data) { m_fieldcnt StringSplit(m_fields, ",", strarray); if(m_fieldcnt < 0) { m_fieldcnt = static_cast<int16_t>(strarray.size()); m_pBase->Debug(DEBUG_NORM, "Reset Customfield count to %d", m_fieldcnt); } else { if (GetResourceData(strarray[m_fieldcnt], reply)) { if (reply.empty()) { m_pBase->Debug(DEBUG_NORM, "Got empty data for resource %s", strarray[m_fieldcnt].c_str()); } else { m_pBase->Debug(DEBUG_RECEIVED, "Got data for resource %s :\n%s", strarray[m_fieldcnt].c_str(),reply.toStyledString().c_str()); if (!reply[strarray[m_fieldcnt]].empty()) { if (reply[strarray[m_fieldcnt]].isMember("value")) { std::string resourceValue = reply[strarray[m_fieldcnt]]["value"].asString(); Json::Value customItem; customItem["id"] = m_fieldcnt; customItem["value"] = resourceValue; customItem["label"] = strarray[m_fieldcnt]; data.customdata.append(customItem); m_pBase->Debug(DEBUG_NORM, "Got data for resource (%d) %s : %s", m_fieldcnt, strarray[m_fieldcnt].c_str(), resourceValue.c_str()); } } } } else { m_pBase->Debug(DEBUG_NORM,"Failed to retrieve data for resource %s!", strarray[m_fieldcnt].c_str()); } } } return true; } void CMercApi::GetVehicleData(Json::Value& jsondata, tVehicleData& data) { uint8_t cnt = 0; do { Json::Value iter; iter = jsondata[cnt]; for (auto const& id : iter.getMemberNames()) { if(!(iter[id].isNull())) { m_pBase->Debug(DEBUG_NORM, "Found non empty field %s", id.c_str()); if (id == "<API key>") { Json::Value iter2; iter2 = iter[id]; if(!iter2["value"].empty()) { m_pBase->Debug(DEBUG_NORM, "<API key> has value %s", iter2["value"].asString().c_str()); data.car_open = (iter2["value"].asString() == "1" || iter2["value"].asString() == "2" ? false : true); if(iter2["value"].asString() == "3") { data.car_open_message = "Your Mercedes is partly unlocked"; } else { data.car_open_message = (data.car_open ? "Your Mercedes is open" : "Your Mercedes is locked"); } } } if (id == "odo") { Json::Value iter2; iter2 = iter[id]; if(!iter2["value"].empty()) { m_pBase->Debug(DEBUG_NORM, "Odo has value %s", iter2["value"].asString().c_str()); data.odo = static_cast<float>(atof(iter2["value"].asString().c_str())); } } } } cnt++; } while (!jsondata[cnt].empty()); } bool CMercApi::GetData(const std::string &datatype, Json::Value &reply) { std::stringstream ss; ss << MERC_URL << MERC_API << "/" << m_VIN << "/containers/" << datatype; std::string _sUrl = ss.str(); std::string _sResponse; if (!SendToApi(Get, _sUrl, "", _sResponse, *(new std::vector<std::string>()), reply, true)) { m_pBase->Log(LOG_ERROR, "Failed to get data %s.", datatype.c_str()); return false; } m_pBase->Debug(DEBUG_NORM, "Get data %s received reply: %s", datatype.c_str(), _sResponse.c_str()); return true; } bool CMercApi::GetResourceData(const std::string &datatype, Json::Value &reply) { std::stringstream ss; ss << MERC_URL << MERC_API << "/" << m_VIN << "/resources/" << datatype; std::string _sUrl = ss.str(); std::string _sResponse; if (!SendToApi(Get, _sUrl, "", _sResponse, *(new std::vector<std::string>()), reply, true, (MERC_APITIMEOUT / 2))) { m_pBase->Log(LOG_ERROR, "Failed to get resource data %s.", datatype.c_str()); return false; } m_pBase->Debug(DEBUG_NORM, "Get resource data %s received reply: %s", datatype.c_str(), _sResponse.c_str()); return true; } bool CMercApi::IsAwake() { // Current Mercedes Me (API) does not have an 'Awake' state // So we fake one, we just request the list of all available resources that are available for the current (BYO)CAR std::stringstream ss; ss << MERC_URL << MERC_API << "/" << m_VIN << "/resources"; std::string _sUrl = ss.str(); std::string _sResponse; Json::Value _jsRoot; bool is_awake = false; int nr_retry = 0; while (!SendToApi(Get, _sUrl, "", _sResponse, *(new std::vector<std::string>()), _jsRoot, true, 10)) { nr_retry++; if (nr_retry == 4) { m_pBase->Log(LOG_ERROR, "Failed to get awake state (available resources)!"); return false; } } if (!<API key>(_jsRoot)) { m_pBase->Log(LOG_ERROR, "Unable to process list of available resources!"); } else { is_awake = true; m_pBase->Debug(DEBUG_NORM, "Awake state checked. We are awake."); } return(is_awake); } bool CMercApi::<API key>(Json::Value& jsondata) { bool bProcessed = false; uint8_t cnt = 0; uint32_t crc = 0; std::stringstream ss; crc = jsondata.size(); // hm.. not easy to create something of a real crc32 of JSON content.. so for now we just compare the amount of 'keys' if (crc == m_crc) { m_pBase->Debug(DEBUG_NORM, "CRC32 of content is the same.. skipping processing"); return true; } m_pBase->Debug(DEBUG_NORM, "CRC32 of content is the not the same (%d).. start processing", crc); try { do { Json::Value iter; iter = jsondata[cnt]; for (auto const& id : iter.getMemberNames()) { if(!(iter[id].isNull())) { Json::Value iter2; iter2 = iter[id]; //m_pBase->Debug(DEBUG_NORM, "Field (%d) %s has value %s",cnt, id.c_str(), iter2.asString().c_str()); if (id == "name") { if (cnt > 0) { ss << ","; } ss << iter2.asString(); } if (id == "version" && iter2.asString() != "1.0") { m_pBase->Log(LOG_STATUS, "Found resources with another version (%s) than expected 1.0! Continueing but results may be wrong!", iter2.asString().c_str()); } } } cnt++; } while (!jsondata[cnt].empty()); if (ss.str().length() > 0) { std::vector<std::string> strarray; m_fields = ss.str(); StringSplit(m_fields, ",", strarray); m_fieldcnt = static_cast<int16_t>(strarray.size()); m_pBase->Log(LOG_STATUS, "Found %d resource fields: %s", m_fieldcnt, m_fields.c_str()); m_crc = crc; bProcessed = true; } else { m_pBase->Debug(DEBUG_NORM, "Found %d resource fields but none called name!",cnt); } } catch(const std::exception& e) { std::string what = e.what(); m_pBase->Log(LOG_ERROR, "Crashed during processing of resources: %s", what.c_str()); } return bProcessed; } bool CMercApi::SendCommand(eCommandType command, std::string parameter) { return true; // Not implemented /* std::string command_string; Json::Value reply; std::string parameters = ""; switch (command) { case Charge_Start: command_string = "charge_start"; break; case Charge_Stop: command_string = "charge_stop"; break; case Climate_Off: command_string = "<API key>"; break; case Climate_On: command_string = "<API key>"; break; case Climate_Defrost: command_string = "<API key>"; parameters = "on=true"; break; case Climate_Defrost_Off: command_string = "<API key>"; parameters = "on=false"; break; case Wake_Up: command_string = "wake_up"; break; case Set_Charge_Limit: if (parameter == "0") command_string = "charge_standard"; else if(parameter == "100") command_string = "charge_max_range"; else { command_string = "set_charge_limit"; parameters = "percent=" + parameter; } break; } if (SendCommand(command_string, reply, parameters)) { if (command == Wake_Up) { if (reply["response"]["state"].asString() == "online") return true; } else { if (reply["response"]["result"].asString() == "true") return true; } } return false; */ } bool CMercApi::SendCommand(const std::string &command, Json::Value &reply, const std::string &parameters) { /* std::stringstream ss; if (command == "wake_up") ss << TESLA_URL << TESLA_API << "/" << m_carid << "/" << command; else ss << TESLA_URL << TESLA_API << "/" << m_carid << TESLA_API_COMMAND << command; std::string _sUrl = ss.str(); std::string _sResponse; std::stringstream parss; parss << parameters; std::string sPostData = parss.str(); if (!SendToApi(Post, _sUrl, sPostData, _sResponse, *(new std::vector<std::string>()), reply, true)) { m_pBase->Log(LOG_ERROR, "Failed to send command %s.", command.c_str()); return false; } //m_pBase->Log(LOG_NORM, "Command %s received reply: %s", command.c_str(), _sResponse.c_str()); m_pBase->Debug(DEBUG_NORM, "Command %s received reply: %s", command.c_str(), _sResponse.c_str()); */ return true; } // Requests an access token from the MB OAuth Api. bool CMercApi::GetAuthToken(const std::string &username, const std::string &password, const bool refreshUsingToken) { if (!refreshUsingToken && username.empty()) { m_pBase->Log(LOG_ERROR, "No username specified."); return false; } if (!refreshUsingToken && password.empty()) { m_pBase->Log(LOG_ERROR, "No password specified."); return false; } if (refreshUsingToken && (m_refreshtoken.empty() || m_refresh<API key>)) { m_pBase->Log(LOG_ERROR, "No refresh token to perform refresh!"); return false; } std::stringstream ss; ss << MERC_URL_AUTH << MERC_API_TOKEN; std::string _sUrl = ss.str(); std::ostringstream s; std::string _sGrantType = (refreshUsingToken ? "refresh_<API key>); s << "grant_type=" << _sGrantType; if (refreshUsingToken) { s << "&refresh_token=" << m_refreshtoken; } else { s << "&code=" << password; s << "&redirect_uri=https://localhost"; } std::string sPostData = s.str(); std::vector<std::string> _vExtraHeaders; _vExtraHeaders.push_back("Content-Type: application/<API key>"); _vExtraHeaders.push_back("Authorization: Basic " + m_password); std::string _sResponse; Json::Value _jsRoot; if (!SendToApi(Post, _sUrl, sPostData, _sResponse, _vExtraHeaders, _jsRoot, false)) { m_pBase->Log(LOG_ERROR, "Failed to get token."); return false; } if(!_jsRoot["error"].empty()) { m_pBase->Log(LOG_ERROR, "Received error response (%s).", _jsRoot["error"].asString().c_str()); return false; } m_accesstoken = _jsRoot["access_token"].asString(); if (m_accesstoken.empty()) { m_pBase->Log(LOG_ERROR, "Received access token is zero length."); return false; } m_refreshtoken = _jsRoot["refresh_token"].asString(); if (m_refreshtoken.empty()) { m_pBase->Log(LOG_ERROR, "Received refresh token is zero length."); return false; } m_pBase->Log(LOG_STATUS, "Received new refresh token %s .", m_refreshtoken.c_str()); m_pBase->Debug(DEBUG_NORM, "Received access token from API."); return true; } // Sends a request to the MB API. bool CMercApi::SendToApi(const eApiMethod eMethod, const std::string& sUrl, const std::string& sPostData, std::string& sResponse, const std::vector<std::string>& vExtraHeaders, Json::Value& jsDecodedResponse, const bool bSendAuthHeaders, const int timeout) { m_httpresultcode = 0; // Reset to 0 // If there is no token stored then there is no point in doing a request. Unless we specifically // decide not to do authentication. if (m_accesstoken.empty() && bSendAuthHeaders) { m_pBase->Log(LOG_ERROR, "No access token available."); return false; } try { // Prepare the headers. Copy supplied vector. std::vector<std::string> _vExtraHeaders = vExtraHeaders; // If the supplied postdata validates as json, add an appropriate content type header if (!sPostData.empty()) if (ParseJSon(sPostData, *(new Json::Value))) _vExtraHeaders.push_back("Content-Type: application/json"); // Prepare the authentication headers if requested. if (bSendAuthHeaders) _vExtraHeaders.push_back("Authorization: Bearer " + m_accesstoken); // In/Decrease default timeout if(timeout == 0) { HTTPClient::<API key>(MERC_APITIMEOUT); HTTPClient::SetTimeout(MERC_APITIMEOUT); } else { HTTPClient::<API key>(timeout); HTTPClient::SetTimeout(timeout); } std::vector<std::string> _vResponseHeaders; std::stringstream <API key>; uint16_t _iHttpCode; m_pBase->Debug(DEBUG_RECEIVED, "Performing request to Api: %s", sUrl.c_str()); switch (eMethod) { case Post: if (!HTTPClient::POST(sUrl, sPostData, _vExtraHeaders, sResponse, _vResponseHeaders)) { _iHttpCode = <API key>(_vResponseHeaders[0]); m_pBase->Log(LOG_ERROR, "Failed to perform POST request (%d)!", _iHttpCode); } break; case Get: if (!HTTPClient::GET(sUrl, _vExtraHeaders, sResponse, _vResponseHeaders, true)) { _iHttpCode = <API key>(_vResponseHeaders[0]); m_pBase->Log(LOG_ERROR, "Failed to perform GET request (%d)!", _iHttpCode); } break; default: { m_pBase->Log(LOG_ERROR, "Unknown method specified."); return false; } } m_httpresultcode = <API key>(_vResponseHeaders[0]); // Debug response for (auto &_vResponseHeader : _vResponseHeaders) <API key> << _vResponseHeader; m_pBase->Debug(DEBUG_RECEIVED, "Performed request to Api: (%d)\n%s\nResponse headers: %s", m_httpresultcode, sResponse.c_str(), <API key>.str().c_str()); switch(m_httpresultcode) { case 28: m_pBase->Log(LOG_STATUS, "Received (Curl) returncode 28.. API request response took too long, timed-out!"); return false; break; case 35: m_pBase->Log(LOG_STATUS, "Received (Curl) returncode 35.. Trouble with HTTPS/SSL! (%s)", <API key>.str().c_str()); return false; break; case 200: break; // Ok, continue to process content case 204: m_pBase->Log(LOG_STATUS, "Received (204) No Content.. likely because of no activity/updates in the last 12 hours!"); return true; // OK and directly return as there is no content to actually process break; case 400: m_pBase->Log(LOG_STATUS, "Received (400) Bad Request.. Unexpected unless something has changed! (%s)", sResponse.c_str()); return false; break; case 401: if(!m_authenticating) { m_pBase->Log(LOG_STATUS, "Received 401.. Let's try to (re)authorize again!"); RefreshLogin(); } else { m_pBase->Log(LOG_STATUS, "Received 401.. During authorisation proces. Aborting!"); } return false; break; case 403: if(!m_authenticating) { m_pBase->Log(LOG_STATUS, "Received 403.. Access has been denied!"); } else { m_pBase->Log(LOG_STATUS, "Received 403.. Access denied during authorisation proces. Aborting!"); } return false; break; case 429: m_pBase->Log(LOG_STATUS, "Received 429.. Too many request... we need to back off!"); return false; break; case 500: case 503: m_pBase->Log(LOG_STATUS, "Received 500/503.. Service is not available!"); return false; break; default: m_pBase->Log(LOG_STATUS, "Received unhandled HTTP returncode %d !", m_httpresultcode); return false; } if (sResponse.empty()) { m_pBase->Log(LOG_ERROR, "Received an empty response from Api (HTTP %d).", m_httpresultcode); return false; } if (!ParseJSon(sResponse, jsDecodedResponse)) { m_pBase->Log(LOG_ERROR, "Failed to decode Json response from Api (HTTP %d).", m_httpresultcode); return false; } } catch (std::exception & e) { std::string what = e.what(); m_pBase->Log(LOG_ERROR, "Error sending information to Api: %s", what.c_str()); return false; } return true; } // Interpret the return message headers to extract the HTTP resultcode uint16_t CMercApi::<API key>(const std::string& <API key>) { uint16_t iHttpCode = 9999; uint8_t iHttpCodeStartPos = 0; if(!<API key>.empty()) { if (<API key>.find("HTTP") == 0) // Ok, so this header indeeds starts with HTTP { if (<API key>.find_first_of(' ') != std::string::npos) { iHttpCodeStartPos = (uint8_t)<API key>.find_first_of(' ') + 1; // So look for a SPACE as the seperator (RFC2616) iHttpCode = (uint16_t)std::stoi(<API key>.substr(iHttpCodeStartPos, 3)); if (iHttpCode < 100 || iHttpCode > 599) // Check valid resultcode range { m_pBase->Log(LOG_STATUS, "Found non-standard resultcode (%d) in HTTP response statusline: %s", iHttpCode, <API key>.c_str()); } } } } return iHttpCode; }
<!DOCTYPE HTML PUBLIC "- <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="generator" content="PHPDoctor 2RC4 (http://peej.github.com/phpdoctor/)"> <meta name="when" content="Fri, 21 Jan 2011 04:30:38 +0000"> <link rel="stylesheet" type="text/css" href="../stylesheet.css"> <link rel="start" href="../overview-summary.html"> <title>jqmControlgroup.php (jqmPhp)</title> </head> <body id="file" onload="parent.document.title=document.title;"> <div class="header"> <h1>jqmPhp</h1> <ul> <li><a href="../overview-summary.html">Overview</a></li> <li>Package</li><li>Class</li><li>Tree</li><li><a href="../overview-files.html">Files</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li><a href="../todo-list.html">Todo</a></li> <li><a href="../index-all.html">Index</a></li> </ul> </div> <div class="small_links"> <a href="../index.html" target="_top">Frames</a> <a href="../source/jqmcontrolgroup.php.html" target="_top">No frames</a> </div> <hr> <h1>jqmControlgroup.php</h1> <hr> <a name="line1"></a><pre><?php <a name="line31"></a>class jqmControlgroup extends jqmTag { <a name="line32"></a> private $_role; <a name="line33"></a> private $_dataType; <a name="line34"></a> /** <a name="line35"></a> * <a name="line36"></a> * @param string $id <a name="line37"></a> * @param array $attributes <a name="line38"></a> * @param array $items <a name="line39"></a> * @param string $theme <a name="line40"></a> * @param string $dataType <a name="line41"></a> */ <a name="line42"></a> function __construct($id='', $attributes=array(), $items=array(), $theme='', $dataType='vertical') { <a name="line43"></a> parent::__construct('div', $id, $attributes, $items, $theme); <a name="line44"></a> $this->_role = $this->attribute('data-role', 'controlgroup', true); <a name="line45"></a> $this->_dataType = $this->attribute('data-type', $dataType, true); <a name="line46"></a> } <a name="line47"></a> /** <a name="line48"></a> * @access private <a name="line49"></a> * @param string $value <a name="line50"></a> * @return string|jqmControlgroup <a name="line51"></a> */ <a name="line52"></a> function role() { <a name="line53"></a> if (func_num_args() == 0) return $this->_role->value(); <a name="line54"></a> $this->_role->value(func_get_arg(0)); <a name="line55"></a> return $this; <a name="line56"></a> } <a name="line57"></a> /** <a name="line58"></a> * Gets and sets the dataType property (data-type="vertical"). <a name="line59"></a> * @param string $value <a name="line60"></a> * @return string|jqmControlgroup <a name="line61"></a> */ <a name="line62"></a> function dataType() { <a name="line63"></a> if (func_num_args() == 0) return $this->_dataType->value(); <a name="line64"></a> $this->_dataType->value(func_get_arg(0)); <a name="line65"></a> return $this; <a name="line66"></a> } <a name="line67"></a>} <a name="line68"></a>?></pre> <div class="header"> <h1>jqmPhp</h1> <ul> <li><a href="../overview-summary.html">Overview</a></li> <li>Package</li><li>Class</li><li>Tree</li><li><a href="../overview-files.html">Files</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li><a href="../todo-list.html">Todo</a></li> <li><a href="../index-all.html">Index</a></li> </ul> </div> <div class="small_links"> <a href="../index.html" target="_top">Frames</a> <a href="../source/jqmcontrolgroup.php.html" target="_top">No frames</a> </div> <hr> <p id="footer">This document was generated by <a href="http://peej.github.com/phpdoctor/">PHPDoctor: The PHP Documentation Creator</a></p> </body> </html>
<?php namespace Base; use \OcOrderProduct as ChildOcOrderProduct; use \OcOrderProductQuery as <API key>; use \Exception; use \PDO; use Map\<API key>; use Propel\Runtime\Propel; use Propel\Runtime\ActiveQuery\Criteria; use Propel\Runtime\ActiveQuery\ModelCriteria; use Propel\Runtime\Collection\ObjectCollection; use Propel\Runtime\Connection\ConnectionInterface; use Propel\Runtime\Exception\PropelException; /** * Base class that represents a query for the 'oc_order_product' table. * * * * @method <API key> <API key>($order = Criteria::ASC) Order by the order_product_id column * @method <API key> orderByOrderId($order = Criteria::ASC) Order by the order_id column * @method <API key> orderByProductId($order = Criteria::ASC) Order by the product_id column * @method <API key> orderByName($order = Criteria::ASC) Order by the name column * @method <API key> orderByModel($order = Criteria::ASC) Order by the model column * @method <API key> orderByQuantity($order = Criteria::ASC) Order by the quantity column * @method <API key> orderByPrice($order = Criteria::ASC) Order by the price column * @method <API key> orderByTotal($order = Criteria::ASC) Order by the total column * @method <API key> orderByTax($order = Criteria::ASC) Order by the tax column * @method <API key> orderByReward($order = Criteria::ASC) Order by the reward column * * @method <API key> <API key>() Group by the order_product_id column * @method <API key> groupByOrderId() Group by the order_id column * @method <API key> groupByProductId() Group by the product_id column * @method <API key> groupByName() Group by the name column * @method <API key> groupByModel() Group by the model column * @method <API key> groupByQuantity() Group by the quantity column * @method <API key> groupByPrice() Group by the price column * @method <API key> groupByTotal() Group by the total column * @method <API key> groupByTax() Group by the tax column * @method <API key> groupByReward() Group by the reward column * * @method <API key> leftJoin($relation) Adds a LEFT JOIN clause to the query * @method <API key> rightJoin($relation) Adds a RIGHT JOIN clause to the query * @method <API key> innerJoin($relation) Adds a INNER JOIN clause to the query * * @method <API key> leftJoinWith($relation) Adds a LEFT JOIN clause and with to the query * @method <API key> rightJoinWith($relation) Adds a RIGHT JOIN clause and with to the query * @method <API key> innerJoinWith($relation) Adds a INNER JOIN clause and with to the query * * @method ChildOcOrderProduct findOne(ConnectionInterface $con = null) Return the first ChildOcOrderProduct matching the query * @method ChildOcOrderProduct findOneOrCreate(ConnectionInterface $con = null) Return the first ChildOcOrderProduct matching the query, or a new ChildOcOrderProduct object populated from the query conditions when no match is found * * @method ChildOcOrderProduct <API key>(int $order_product_id) Return the first ChildOcOrderProduct filtered by the order_product_id column * @method ChildOcOrderProduct findOneByOrderId(int $order_id) Return the first ChildOcOrderProduct filtered by the order_id column * @method ChildOcOrderProduct findOneByProductId(int $product_id) Return the first ChildOcOrderProduct filtered by the product_id column * @method ChildOcOrderProduct findOneByName(string $name) Return the first ChildOcOrderProduct filtered by the name column * @method ChildOcOrderProduct findOneByModel(string $model) Return the first ChildOcOrderProduct filtered by the model column * @method ChildOcOrderProduct findOneByQuantity(int $quantity) Return the first ChildOcOrderProduct filtered by the quantity column * @method ChildOcOrderProduct findOneByPrice(string $price) Return the first ChildOcOrderProduct filtered by the price column * @method ChildOcOrderProduct findOneByTotal(string $total) Return the first ChildOcOrderProduct filtered by the total column * @method ChildOcOrderProduct findOneByTax(string $tax) Return the first ChildOcOrderProduct filtered by the tax column * @method ChildOcOrderProduct findOneByReward(int $reward) Return the first ChildOcOrderProduct filtered by the reward column * * @method ChildOcOrderProduct requirePk($key, ConnectionInterface $con = null) Return the ChildOcOrderProduct by primary key and throws \Propel\Runtime\Exception\<API key> when not found * @method ChildOcOrderProduct requireOne(ConnectionInterface $con = null) Return the first ChildOcOrderProduct matching the query and throws \Propel\Runtime\Exception\<API key> when not found * * @method ChildOcOrderProduct <API key>(int $order_product_id) Return the first ChildOcOrderProduct filtered by the order_product_id column and throws \Propel\Runtime\Exception\<API key> when not found * @method ChildOcOrderProduct requireOneByOrderId(int $order_id) Return the first ChildOcOrderProduct filtered by the order_id column and throws \Propel\Runtime\Exception\<API key> when not found * @method ChildOcOrderProduct <API key>(int $product_id) Return the first ChildOcOrderProduct filtered by the product_id column and throws \Propel\Runtime\Exception\<API key> when not found * @method ChildOcOrderProduct requireOneByName(string $name) Return the first ChildOcOrderProduct filtered by the name column and throws \Propel\Runtime\Exception\<API key> when not found * @method ChildOcOrderProduct requireOneByModel(string $model) Return the first ChildOcOrderProduct filtered by the model column and throws \Propel\Runtime\Exception\<API key> when not found * @method ChildOcOrderProduct <API key>(int $quantity) Return the first ChildOcOrderProduct filtered by the quantity column and throws \Propel\Runtime\Exception\<API key> when not found * @method ChildOcOrderProduct requireOneByPrice(string $price) Return the first ChildOcOrderProduct filtered by the price column and throws \Propel\Runtime\Exception\<API key> when not found * @method ChildOcOrderProduct requireOneByTotal(string $total) Return the first ChildOcOrderProduct filtered by the total column and throws \Propel\Runtime\Exception\<API key> when not found * @method ChildOcOrderProduct requireOneByTax(string $tax) Return the first ChildOcOrderProduct filtered by the tax column and throws \Propel\Runtime\Exception\<API key> when not found * @method ChildOcOrderProduct requireOneByReward(int $reward) Return the first ChildOcOrderProduct filtered by the reward column and throws \Propel\Runtime\Exception\<API key> when not found * * @method ChildOcOrderProduct[]|ObjectCollection find(ConnectionInterface $con = null) Return ChildOcOrderProduct objects based on current ModelCriteria * @method ChildOcOrderProduct[]|ObjectCollection <API key>(int $order_product_id) Return ChildOcOrderProduct objects filtered by the order_product_id column * @method ChildOcOrderProduct[]|ObjectCollection findByOrderId(int $order_id) Return ChildOcOrderProduct objects filtered by the order_id column * @method ChildOcOrderProduct[]|ObjectCollection findByProductId(int $product_id) Return ChildOcOrderProduct objects filtered by the product_id column * @method ChildOcOrderProduct[]|ObjectCollection findByName(string $name) Return ChildOcOrderProduct objects filtered by the name column * @method ChildOcOrderProduct[]|ObjectCollection findByModel(string $model) Return ChildOcOrderProduct objects filtered by the model column * @method ChildOcOrderProduct[]|ObjectCollection findByQuantity(int $quantity) Return ChildOcOrderProduct objects filtered by the quantity column * @method ChildOcOrderProduct[]|ObjectCollection findByPrice(string $price) Return ChildOcOrderProduct objects filtered by the price column * @method ChildOcOrderProduct[]|ObjectCollection findByTotal(string $total) Return ChildOcOrderProduct objects filtered by the total column * @method ChildOcOrderProduct[]|ObjectCollection findByTax(string $tax) Return ChildOcOrderProduct objects filtered by the tax column * @method ChildOcOrderProduct[]|ObjectCollection findByReward(int $reward) Return ChildOcOrderProduct objects filtered by the reward column * @method ChildOcOrderProduct[]|\Propel\Runtime\Util\PropelModelPager paginate($page = 1, $maxPerPage = 10, ConnectionInterface $con = null) Issue a SELECT query based on the current ModelCriteria and uses a page and a maximum number of results per page to compute an offset and a limit * */ abstract class OcOrderProductQuery extends ModelCriteria { protected $<API key> = '\\Propel\\Runtime\\Exception\\<API key>'; /** * Initializes internal state of \Base\OcOrderProductQuery object. * * @param string $dbName The database name * @param string $modelName The phpName of a model, e.g. 'Book' * @param string $modelAlias The alias for the model in this query, e.g. 'b' */ public function __construct($dbName = 'default', $modelName = '\\OcOrderProduct', $modelAlias = null) { parent::__construct($dbName, $modelName, $modelAlias); } /** * Returns a new <API key> object. * * @param string $modelAlias The alias of a model in the query * @param Criteria $criteria Optional Criteria to build the query from * * @return <API key> */ public static function create($modelAlias = null, Criteria $criteria = null) { if ($criteria instanceof <API key>) { return $criteria; } $query = new <API key>(); if (null !== $modelAlias) { $query->setModelAlias($modelAlias); } if ($criteria instanceof Criteria) { $query->mergeWith($criteria); } return $query; } /** * Find object by primary key. * Propel uses the instance pool to skip the database if the object exists. * Go fast if the query is untouched. * * <code> * $obj = $c->findPk(12, $con); * </code> * * @param mixed $key Primary key to use for the query * @param ConnectionInterface $con an optional connection object * * @return ChildOcOrderProduct|array|mixed the result, formatted by the current formatter */ public function findPk($key, ConnectionInterface $con = null) { if ($key === null) { return null; } if ($con === null) { $con = Propel::getServiceContainer()->getReadConnection(<API key>::DATABASE_NAME); } $this->basePreSelect($con); if ( $this->formatter || $this->modelAlias || $this->with || $this->select || $this->selectColumns || $this->asColumns || $this->selectModifiers || $this->map || $this->having || $this->joins ) { return $this->findPkComplex($key, $con); } if ((null !== ($obj = <API key>::getInstanceFromPool(null === $key || is_scalar($key) || is_callable([$key, '__toString']) ? (string) $key : $key)))) { // the object is already in the instance pool return $obj; } return $this->findPkSimple($key, $con); } /** * Find object by primary key using raw SQL to go fast. * Bypass doSelect() and the object formatter by using generated code. * * @param mixed $key Primary key to use for the query * @param ConnectionInterface $con A connection object * * @throws \Propel\Runtime\Exception\PropelException * * @return ChildOcOrderProduct A model object, or null if the key is not found */ protected function findPkSimple($key, ConnectionInterface $con) { $sql = 'SELECT order_product_id, order_id, product_id, name, model, quantity, price, total, tax, reward FROM oc_order_product WHERE order_product_id = :p0'; try { $stmt = $con->prepare($sql); $stmt->bindValue(':p0', $key, PDO::PARAM_INT); $stmt->execute(); } catch (Exception $e) { Propel::log($e->getMessage(), Propel::LOG_ERR); throw new PropelException(sprintf('Unable to execute SELECT statement [%s]', $sql), 0, $e); } $obj = null; if ($row = $stmt->fetch(\PDO::FETCH_NUM)) { /** @var ChildOcOrderProduct $obj */ $obj = new ChildOcOrderProduct(); $obj->hydrate($row); <API key>::addInstanceToPool($obj, null === $key || is_scalar($key) || is_callable([$key, '__toString']) ? (string) $key : $key); } $stmt->closeCursor(); return $obj; } /** * Find object by primary key. * * @param mixed $key Primary key to use for the query * @param ConnectionInterface $con A connection object * * @return ChildOcOrderProduct|array|mixed the result, formatted by the current formatter */ protected function findPkComplex($key, ConnectionInterface $con) { // As the query uses a PK condition, no limit(1) is necessary. $criteria = $this->isKeepQuery() ? clone $this : $this; $dataFetcher = $criteria ->filterByPrimaryKey($key) ->doSelect($con); return $criteria->getFormatter()->init($criteria)->formatOne($dataFetcher); } /** * Find objects by primary key * <code> * $objs = $c->findPks(array(12, 56, 832), $con); * </code> * @param array $keys Primary keys to use for the query * @param ConnectionInterface $con an optional connection object * * @return ObjectCollection|array|mixed the list of results, formatted by the current formatter */ public function findPks($keys, ConnectionInterface $con = null) { if (null === $con) { $con = Propel::getServiceContainer()->getReadConnection($this->getDbName()); } $this->basePreSelect($con); $criteria = $this->isKeepQuery() ? clone $this : $this; $dataFetcher = $criteria ->filterByPrimaryKeys($keys) ->doSelect($con); return $criteria->getFormatter()->init($criteria)->format($dataFetcher); } /** * Filter the query by primary key * * @param mixed $key Primary key to use for the query * * @return $this|<API key> The current query, for fluid interface */ public function filterByPrimaryKey($key) { return $this->addUsingAlias(<API key>::<API key>, $key, Criteria::EQUAL); } /** * Filter the query by a list of primary keys * * @param array $keys The list of primary key to use for the query * * @return $this|<API key> The current query, for fluid interface */ public function filterByPrimaryKeys($keys) { return $this->addUsingAlias(<API key>::<API key>, $keys, Criteria::IN); } /** * Filter the query on the order_product_id column * * Example usage: * <code> * $query-><API key>(1234); // WHERE order_product_id = 1234 * $query-><API key>(array(12, 34)); // WHERE order_product_id IN (12, 34) * $query-><API key>(array('min' => 12)); // WHERE order_product_id > 12 * </code> * * @param mixed $orderProductId The value to use as filter. * Use scalar values for equality. * Use array values for in_array() equivalent. * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL * * @return $this|<API key> The current query, for fluid interface */ public function <API key>($orderProductId = null, $comparison = null) { if (is_array($orderProductId)) { $useMinMax = false; if (isset($orderProductId['min'])) { $this->addUsingAlias(<API key>::<API key>, $orderProductId['min'], Criteria::GREATER_EQUAL); $useMinMax = true; } if (isset($orderProductId['max'])) { $this->addUsingAlias(<API key>::<API key>, $orderProductId['max'], Criteria::LESS_EQUAL); $useMinMax = true; } if ($useMinMax) { return $this; } if (null === $comparison) { $comparison = Criteria::IN; } } return $this->addUsingAlias(<API key>::<API key>, $orderProductId, $comparison); } /** * Filter the query on the order_id column * * Example usage: * <code> * $query->filterByOrderId(1234); // WHERE order_id = 1234 * $query->filterByOrderId(array(12, 34)); // WHERE order_id IN (12, 34) * $query->filterByOrderId(array('min' => 12)); // WHERE order_id > 12 * </code> * * @param mixed $orderId The value to use as filter. * Use scalar values for equality. * Use array values for in_array() equivalent. * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL * * @return $this|<API key> The current query, for fluid interface */ public function filterByOrderId($orderId = null, $comparison = null) { if (is_array($orderId)) { $useMinMax = false; if (isset($orderId['min'])) { $this->addUsingAlias(<API key>::COL_ORDER_ID, $orderId['min'], Criteria::GREATER_EQUAL); $useMinMax = true; } if (isset($orderId['max'])) { $this->addUsingAlias(<API key>::COL_ORDER_ID, $orderId['max'], Criteria::LESS_EQUAL); $useMinMax = true; } if ($useMinMax) { return $this; } if (null === $comparison) { $comparison = Criteria::IN; } } return $this->addUsingAlias(<API key>::COL_ORDER_ID, $orderId, $comparison); } /** * Filter the query on the product_id column * * Example usage: * <code> * $query->filterByProductId(1234); // WHERE product_id = 1234 * $query->filterByProductId(array(12, 34)); // WHERE product_id IN (12, 34) * $query->filterByProductId(array('min' => 12)); // WHERE product_id > 12 * </code> * * @param mixed $productId The value to use as filter. * Use scalar values for equality. * Use array values for in_array() equivalent. * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL * * @return $this|<API key> The current query, for fluid interface */ public function filterByProductId($productId = null, $comparison = null) { if (is_array($productId)) { $useMinMax = false; if (isset($productId['min'])) { $this->addUsingAlias(<API key>::COL_PRODUCT_ID, $productId['min'], Criteria::GREATER_EQUAL); $useMinMax = true; } if (isset($productId['max'])) { $this->addUsingAlias(<API key>::COL_PRODUCT_ID, $productId['max'], Criteria::LESS_EQUAL); $useMinMax = true; } if ($useMinMax) { return $this; } if (null === $comparison) { $comparison = Criteria::IN; } } return $this->addUsingAlias(<API key>::COL_PRODUCT_ID, $productId, $comparison); } /** * Filter the query on the name column * * Example usage: * <code> * $query->filterByName('fooValue'); // WHERE name = 'fooValue' * $query->filterByName('%fooValue%', Criteria::LIKE); // WHERE name LIKE '%fooValue%' * </code> * * @param string $name The value to use as filter. * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL * * @return $this|<API key> The current query, for fluid interface */ public function filterByName($name = null, $comparison = null) { if (null === $comparison) { if (is_array($name)) { $comparison = Criteria::IN; } } return $this->addUsingAlias(<API key>::COL_NAME, $name, $comparison); } /** * Filter the query on the model column * * Example usage: * <code> * $query->filterByModel('fooValue'); // WHERE model = 'fooValue' * $query->filterByModel('%fooValue%', Criteria::LIKE); // WHERE model LIKE '%fooValue%' * </code> * * @param string $model The value to use as filter. * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL * * @return $this|<API key> The current query, for fluid interface */ public function filterByModel($model = null, $comparison = null) { if (null === $comparison) { if (is_array($model)) { $comparison = Criteria::IN; } } return $this->addUsingAlias(<API key>::COL_MODEL, $model, $comparison); } /** * Filter the query on the quantity column * * Example usage: * <code> * $query->filterByQuantity(1234); // WHERE quantity = 1234 * $query->filterByQuantity(array(12, 34)); // WHERE quantity IN (12, 34) * $query->filterByQuantity(array('min' => 12)); // WHERE quantity > 12 * </code> * * @param mixed $quantity The value to use as filter. * Use scalar values for equality. * Use array values for in_array() equivalent. * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL * * @return $this|<API key> The current query, for fluid interface */ public function filterByQuantity($quantity = null, $comparison = null) { if (is_array($quantity)) { $useMinMax = false; if (isset($quantity['min'])) { $this->addUsingAlias(<API key>::COL_QUANTITY, $quantity['min'], Criteria::GREATER_EQUAL); $useMinMax = true; } if (isset($quantity['max'])) { $this->addUsingAlias(<API key>::COL_QUANTITY, $quantity['max'], Criteria::LESS_EQUAL); $useMinMax = true; } if ($useMinMax) { return $this; } if (null === $comparison) { $comparison = Criteria::IN; } } return $this->addUsingAlias(<API key>::COL_QUANTITY, $quantity, $comparison); } /** * Filter the query on the price column * * Example usage: * <code> * $query->filterByPrice(1234); // WHERE price = 1234 * $query->filterByPrice(array(12, 34)); // WHERE price IN (12, 34) * $query->filterByPrice(array('min' => 12)); // WHERE price > 12 * </code> * * @param mixed $price The value to use as filter. * Use scalar values for equality. * Use array values for in_array() equivalent. * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL * * @return $this|<API key> The current query, for fluid interface */ public function filterByPrice($price = null, $comparison = null) { if (is_array($price)) { $useMinMax = false; if (isset($price['min'])) { $this->addUsingAlias(<API key>::COL_PRICE, $price['min'], Criteria::GREATER_EQUAL); $useMinMax = true; } if (isset($price['max'])) { $this->addUsingAlias(<API key>::COL_PRICE, $price['max'], Criteria::LESS_EQUAL); $useMinMax = true; } if ($useMinMax) { return $this; } if (null === $comparison) { $comparison = Criteria::IN; } } return $this->addUsingAlias(<API key>::COL_PRICE, $price, $comparison); } /** * Filter the query on the total column * * Example usage: * <code> * $query->filterByTotal(1234); // WHERE total = 1234 * $query->filterByTotal(array(12, 34)); // WHERE total IN (12, 34) * $query->filterByTotal(array('min' => 12)); // WHERE total > 12 * </code> * * @param mixed $total The value to use as filter. * Use scalar values for equality. * Use array values for in_array() equivalent. * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL * * @return $this|<API key> The current query, for fluid interface */ public function filterByTotal($total = null, $comparison = null) { if (is_array($total)) { $useMinMax = false; if (isset($total['min'])) { $this->addUsingAlias(<API key>::COL_TOTAL, $total['min'], Criteria::GREATER_EQUAL); $useMinMax = true; } if (isset($total['max'])) { $this->addUsingAlias(<API key>::COL_TOTAL, $total['max'], Criteria::LESS_EQUAL); $useMinMax = true; } if ($useMinMax) { return $this; } if (null === $comparison) { $comparison = Criteria::IN; } } return $this->addUsingAlias(<API key>::COL_TOTAL, $total, $comparison); } /** * Filter the query on the tax column * * Example usage: * <code> * $query->filterByTax(1234); // WHERE tax = 1234 * $query->filterByTax(array(12, 34)); // WHERE tax IN (12, 34) * $query->filterByTax(array('min' => 12)); // WHERE tax > 12 * </code> * * @param mixed $tax The value to use as filter. * Use scalar values for equality. * Use array values for in_array() equivalent. * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL * * @return $this|<API key> The current query, for fluid interface */ public function filterByTax($tax = null, $comparison = null) { if (is_array($tax)) { $useMinMax = false; if (isset($tax['min'])) { $this->addUsingAlias(<API key>::COL_TAX, $tax['min'], Criteria::GREATER_EQUAL); $useMinMax = true; } if (isset($tax['max'])) { $this->addUsingAlias(<API key>::COL_TAX, $tax['max'], Criteria::LESS_EQUAL); $useMinMax = true; } if ($useMinMax) { return $this; } if (null === $comparison) { $comparison = Criteria::IN; } } return $this->addUsingAlias(<API key>::COL_TAX, $tax, $comparison); } /** * Filter the query on the reward column * * Example usage: * <code> * $query->filterByReward(1234); // WHERE reward = 1234 * $query->filterByReward(array(12, 34)); // WHERE reward IN (12, 34) * $query->filterByReward(array('min' => 12)); // WHERE reward > 12 * </code> * * @param mixed $reward The value to use as filter. * Use scalar values for equality. * Use array values for in_array() equivalent. * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL * * @return $this|<API key> The current query, for fluid interface */ public function filterByReward($reward = null, $comparison = null) { if (is_array($reward)) { $useMinMax = false; if (isset($reward['min'])) { $this->addUsingAlias(<API key>::COL_REWARD, $reward['min'], Criteria::GREATER_EQUAL); $useMinMax = true; } if (isset($reward['max'])) { $this->addUsingAlias(<API key>::COL_REWARD, $reward['max'], Criteria::LESS_EQUAL); $useMinMax = true; } if ($useMinMax) { return $this; } if (null === $comparison) { $comparison = Criteria::IN; } } return $this->addUsingAlias(<API key>::COL_REWARD, $reward, $comparison); } /** * Exclude object from result * * @param ChildOcOrderProduct $ocOrderProduct Object to remove from the list of results * * @return $this|<API key> The current query, for fluid interface */ public function prune($ocOrderProduct = null) { if ($ocOrderProduct) { $this->addUsingAlias(<API key>::<API key>, $ocOrderProduct->getOrderProductId(), Criteria::NOT_EQUAL); } return $this; } /** * Deletes all rows from the oc_order_product table. * * @param ConnectionInterface $con the connection to use * @return int The number of affected rows (if supported by underlying database driver). */ public function doDeleteAll(ConnectionInterface $con = null) { if (null === $con) { $con = Propel::getServiceContainer()->getWriteConnection(<API key>::DATABASE_NAME); } // use transaction because $criteria could contain info // for more than one table or we could emulating ON DELETE CASCADE, etc. return $con->transaction(function () use ($con) { $affectedRows = 0; // initialize var to track total num of affected rows $affectedRows += parent::doDeleteAll($con); // Because this db requires some delete cascade/set null emulation, we have to // clear the cached instance *after* the emulation has happened (since // instances get re-added by the select statement contained therein). <API key>::clearInstancePool(); <API key>::<API key>(); return $affectedRows; }); } /** * Performs a DELETE on the database based on the current ModelCriteria * * @param ConnectionInterface $con the connection to use * @return int The number of affected rows (if supported by underlying database driver). This includes CASCADE-related rows * if supported by native driver or if emulated using Propel. * @throws PropelException Any exceptions caught during processing will be * rethrown wrapped into a PropelException. */ public function delete(ConnectionInterface $con = null) { if (null === $con) { $con = Propel::getServiceContainer()->getWriteConnection(<API key>::DATABASE_NAME); } $criteria = $this; // Set the correct dbName $criteria->setDbName(<API key>::DATABASE_NAME); // use transaction because $criteria could contain info // for more than one table or we could emulating ON DELETE CASCADE, etc. return $con->transaction(function () use ($con, $criteria) { $affectedRows = 0; // initialize var to track total num of affected rows <API key>::<API key>($criteria); $affectedRows += ModelCriteria::delete($con); <API key>::<API key>(); return $affectedRows; }); } } // OcOrderProductQuery
#ifndef <API key> #define <API key> #include <cctype> #include <locale> #include <limits> #include <string> #include <sstream> #include <iomanip> #include <iterator> // i/ostreambuf_iterator #include <exception> #include <boost/assert.hpp> #include <boost/lexical_cast.hpp> #include <boost/throw_exception.hpp> #include <boost/range/as_literal.hpp> #include <boost/algorithm/string/erase.hpp> #include <boost/algorithm/string/replace.hpp> #include <boost/date_time/compiler_config.hpp> #include <boost/date_time/date_facet.hpp> #include <boost/date_time/string_convert.hpp> #include <boost/date_time/special_defs.hpp> #include <boost/date_time/<API key>.hpp> // absolute_value namespace boost { namespace date_time { template <class CharT> struct time_formats { public: typedef CharT char_type; static const char_type <API key>[3]; static const char_type <API key>[3]; static const char_type <API key>[3]; static const char_type seconds_format[3]; static const char_type hours_format[3]; static const char_type <API key>[3]; static const char_type <API key>[3]; static const char_type <API key>[9]; // HH:MM:SS static const char_type <API key>[3]; static const char_type <API key>[6]; // HH:MM static const char_type standard_format[9]; // x X static const char_type zone_abbrev_format[3]; static const char_type zone_name_format[3]; static const char_type zone_iso_format[3]; static const char_type <API key>[3]; static const char_type <API key>[4]; static const char_type <API key>[3]; static const char_type <API key>[3]; static const char_type duration_seperator[2]; static const char_type negative_sign[2]; static const char_type positive_sign[2]; static const char_type <API key>[18]; static const char_type <API key>[22]; //default ptime format is YYYY-Mon-DD HH:MM:SS[.fff...][ zzz] static const char_type default_time_format[23]; // <API key> uses a <API key> instead of a time zone abbrev static const char_type <API key>[24]; //default time_duration format is HH:MM:SS[.fff...] static const char_type <API key>[11]; }; template <class CharT> const typename time_formats<CharT>::char_type time_formats<CharT>::<API key>[3] = {'%','f'}; template <class CharT> const typename time_formats<CharT>::char_type time_formats<CharT>::<API key>[3] = {'%','F'}; template <class CharT> const typename time_formats<CharT>::char_type time_formats<CharT>::<API key>[3] = {'%','s'}; template <class CharT> const typename time_formats<CharT>::char_type time_formats<CharT>::seconds_format[3] = {'%','S'}; template <class CharT> const typename time_formats<CharT>::char_type time_formats<CharT>::hours_format[3] = {'%','H'}; template <class CharT> const typename time_formats<CharT>::char_type time_formats<CharT>::<API key>[3] = {'%','O'}; template <class CharT> const typename time_formats<CharT>::char_type time_formats<CharT>::<API key>[3] = {'%','T'}; template <class CharT> const typename time_formats<CharT>::char_type time_formats<CharT>::<API key>[9] = {'%','H',':','%','M',':','%','S'}; template <class CharT> const typename time_formats<CharT>::char_type time_formats<CharT>::<API key>[3] = {'%','R'}; template <class CharT> const typename time_formats<CharT>::char_type time_formats<CharT>::<API key>[6] = {'%','H',':','%','M'}; template <class CharT> const typename time_formats<CharT>::char_type //time_formats<CharT>::standard_format[5] = {'%','c',' ','%','z'}; time_formats<CharT>::standard_format[9] = {'%','x',' ','%','X',' ','%','z'}; template <class CharT> const typename time_formats<CharT>::char_type time_formats<CharT>::zone_abbrev_format[3] = {'%','z'}; template <class CharT> const typename time_formats<CharT>::char_type time_formats<CharT>::zone_name_format[3] = {'%','Z'}; template <class CharT> const typename time_formats<CharT>::char_type time_formats<CharT>::zone_iso_format[3] = {'%','q'}; template <class CharT> const typename time_formats<CharT>::char_type time_formats<CharT>::<API key>[3] ={'%','Q'}; template <class CharT> const typename time_formats<CharT>::char_type time_formats<CharT>::<API key>[4] ={'%','Z','P'}; template <class CharT> const typename time_formats<CharT>::char_type time_formats<CharT>::duration_seperator[2] = {':'}; template <class CharT> const typename time_formats<CharT>::char_type time_formats<CharT>::negative_sign[2] = {'-'}; template <class CharT> const typename time_formats<CharT>::char_type time_formats<CharT>::positive_sign[2] = {'+'}; template <class CharT> const typename time_formats<CharT>::char_type time_formats<CharT>::<API key>[3] ={'%','-'}; template <class CharT> const typename time_formats<CharT>::char_type time_formats<CharT>::<API key>[3] ={'%','+'}; template <class CharT> const typename time_formats<CharT>::char_type time_formats<CharT>::<API key>[18] = {'%', 'Y', '%', 'm', '%', 'd', 'T', '%', 'H', '%', 'M', '%', 'S', '%', 'F', '%','q' }; template <class CharT> const typename time_formats<CharT>::char_type time_formats<CharT>::<API key>[22] = {'%', 'Y', '-', '%', 'm', '-', '%', 'd', ' ', '%', 'H', ':', '%', 'M', ':', '%', 'S', '%', 'F','%','Q'}; template <class CharT> const typename time_formats<CharT>::char_type time_formats<CharT>::default_time_format[23] = {'%','Y','-','%','b','-','%','d',' ', '%','H',':','%','M',':','%','S','%','F',' ','%','z'}; template <class CharT> const typename time_formats<CharT>::char_type time_formats<CharT>::<API key>[24] = {'%','Y','-','%','b','-','%','d',' ', '%','H',':','%','M',':','%','S','%','F',' ','%','Z','P'}; template <class CharT> const typename time_formats<CharT>::char_type time_formats<CharT>::<API key>[11] = {'%','O',':','%','M',':','%','S','%','F'}; /*! Facet used for format-based output of time types * This class provides for the use of format strings to output times. In addition * to the flags for formatting date elements, the following are the allowed format flags: * - %x %X => default format - enables addition of more flags to default (ie. "%x %X %z") * - %f => fractional seconds ".123456" * - %F => fractional seconds or none: like frac sec but empty if frac sec == 0 * - %s => seconds w/ fractional sec "02.123" (this is the same as "%S%f) * - %S => seconds "02" * - %z => abbreviated time zone "EDT" * - %Z => full time zone name "Eastern Daylight Time" */ template <class time_type, class CharT, class OutItrT = std::ostreambuf_iterator<CharT, std::char_traits<CharT> > > class time_facet : public boost::date_time::date_facet<typename time_type::date_type , CharT, OutItrT> { typedef time_formats< CharT > formats_type; public: typedef typename time_type::date_type date_type; typedef typename time_type::time_duration_type time_duration_type; typedef boost::date_time::period<time_type,time_duration_type> period_type; typedef boost::date_time::date_facet<typename time_type::date_type, CharT, OutItrT> base_type; typedef typename base_type::string_type string_type; typedef typename base_type::char_type char_type; typedef typename base_type::<API key> <API key>; typedef typename base_type::<API key> <API key>; typedef typename base_type::<API key> <API key>; static const char_type* <API key>; static const char_type* <API key>; static const char_type* <API key>; static const char_type* seconds_format; static const char_type* hours_format; static const char_type* <API key>; static const char_type* standard_format; // %x X static const char_type* zone_abbrev_format; static const char_type* zone_name_format; static const char_type* zone_iso_format; static const char_type* <API key>; static const char_type* <API key>; static const char_type* duration_seperator; static const char_type* <API key>; static const char_type* <API key>; static const char_type* negative_sign; static const char_type* positive_sign; static const char_type* <API key>; static const char_type* <API key>; //default ptime format is YYYY-Mon-DD HH:MM:SS[.fff...][ zzz] static const char_type* default_time_format; //default time_duration format is HH:MM:SS[.fff...] static const char_type* <API key>; static std::locale::id id; #if defined (__SUNPRO_CC) && defined (_RWSTD_VER) std::locale::id& __get_id (void) const { return id; } #endif //! sets default formats for ptime, local_date_time, and time_duration explicit time_facet(::size_t ref_arg = 0) : base_type(default_time_format, <API key>(), <API key>(), <API key>(), ref_arg), <API key>(string_type(<API key>) + <API key>) {} //! Construct the facet with an explicitly specified format explicit time_facet(const char_type* format_arg, <API key> <API key> = <API key>(), const <API key>& <API key> = <API key>(), <API key> dg_formatter = <API key>(), ::size_t ref_arg = 0) : base_type(format_arg, <API key>, <API key>, dg_formatter, ref_arg), <API key>(string_type(<API key>) + <API key>) {} //! Changes format for time_duration void <API key>(const char_type* const format) { <API key> = format; } virtual void set_iso_format() { this->m_format = <API key>; } virtual void <API key>() { this->m_format = <API key>; } OutItrT put(OutItrT next_arg, std::ios_base& ios_arg, char_type fill_arg, const time_type& time_arg) const { if (time_arg.is_special()) { return this->do_put_special(next_arg, ios_arg, fill_arg, time_arg.date().as_special()); } string_type local_format(this->m_format); // %T and %R have to be replaced here since they are not standard boost::algorithm::replace_all(local_format, boost::as_literal(formats_type::<API key>), boost::as_literal(formats_type::<API key>)); boost::algorithm::replace_all(local_format, boost::as_literal(formats_type::<API key>), boost::as_literal(formats_type::<API key>)); string_type frac_str; if (local_format.find(<API key>) != string_type::npos) { // replace %s with %S.nnn frac_str = <API key>(time_arg.time_of_day(), false); char_type sep = std::use_facet<std::numpunct<char_type> >(ios_arg.getloc()).decimal_point(); string_type replace_string(seconds_format); replace_string += sep; replace_string += frac_str; boost::algorithm::replace_all(local_format, <API key>, replace_string); } /* NOTE: replacing <API key> must be done BEFORE * zone_name_format: "%ZP" & "%Z", if Z is checked first it will * incorrectly replace a zone_name where a posix_string should go */ if (local_format.find(<API key>) != string_type::npos) { if(time_arg.zone_abbrev().empty()) { // if zone_abbrev() returns an empty string, we want to // erase <API key> from format boost::algorithm::erase_all(local_format, <API key>); } else{ boost::algorithm::replace_all(local_format, <API key>, time_arg.<API key>()); } } if (local_format.find(zone_name_format) != string_type::npos) { if(time_arg.zone_name().empty()) { /* TODO: this'll probably create problems if a user places * the zone_*_format flag in the format with a ptime. This * code removes the flag from the default formats */ // if zone_name() returns an empty string, we want to // erase zone_name_format & one preceeding space std::basic_ostringstream<char_type> ss; ss << ' ' << zone_name_format; boost::algorithm::erase_all(local_format, ss.str()); } else{ boost::algorithm::replace_all(local_format, zone_name_format, time_arg.zone_name()); } } if (local_format.find(zone_abbrev_format) != string_type::npos) { if(time_arg.zone_abbrev(false).empty()) { /* TODO: this'll probably create problems if a user places * the zone_*_format flag in the format with a ptime. This * code removes the flag from the default formats */ // if zone_abbrev() returns an empty string, we want to // erase zone_abbrev_format & one preceeding space std::basic_ostringstream<char_type> ss; ss << ' ' << zone_abbrev_format; boost::algorithm::erase_all(local_format, ss.str()); } else{ boost::algorithm::replace_all(local_format, zone_abbrev_format, time_arg.zone_abbrev(false)); } } if (local_format.find(<API key>) != string_type::npos) { if(time_arg.zone_name(true).empty()) { /* TODO: this'll probably create problems if a user places * the zone_*_format flag in the format with a ptime. This * code removes the flag from the default formats */ // if zone_name() returns an empty string, we want to // erase <API key> from format boost::algorithm::erase_all(local_format, <API key>); } else{ boost::algorithm::replace_all(local_format, <API key>, time_arg.zone_name(true)); } } if (local_format.find(zone_iso_format) != string_type::npos) { if(time_arg.zone_abbrev(true).empty()) { /* TODO: this'll probably create problems if a user places * the zone_*_format flag in the format with a ptime. This * code removes the flag from the default formats */ // if zone_abbrev() returns an empty string, we want to // erase zone_iso_format from format boost::algorithm::erase_all(local_format, zone_iso_format); } else{ boost::algorithm::replace_all(local_format, zone_iso_format, time_arg.zone_abbrev(true)); } } if (local_format.find(<API key>) != string_type::npos) { // replace %f with nnnnnnn if (frac_str.empty()) { frac_str = <API key>(time_arg.time_of_day(), false); } boost::algorithm::replace_all(local_format, <API key>, frac_str); } if (local_format.find(<API key>) != string_type::npos) { // replace %F with nnnnnnn or nothing if fs == 0 frac_str = <API key>(time_arg.time_of_day(), true); if (frac_str.size()) { char_type sep = std::use_facet<std::numpunct<char_type> >(ios_arg.getloc()).decimal_point(); string_type replace_string; replace_string += sep; replace_string += frac_str; boost::algorithm::replace_all(local_format, <API key>, replace_string); } else { boost::algorithm::erase_all(local_format, <API key>); } } return this->do_put_tm(next_arg, ios_arg, fill_arg, to_tm(time_arg), local_format); } //! put function for time_duration OutItrT put(OutItrT next_arg, std::ios_base& ios_arg, char_type fill_arg, const time_duration_type& time_dur_arg) const { if (time_dur_arg.is_special()) { return this->do_put_special(next_arg, ios_arg, fill_arg, time_dur_arg.get_rep().as_special()); } string_type format(<API key>); if (time_dur_arg.is_negative()) { // replace %- with minus sign. Should we use the numpunct facet? boost::algorithm::replace_all(format, <API key>, negative_sign); // remove all the %+ in the string with '-' boost::algorithm::replace_all(format, <API key>, negative_sign); } else { //duration is positive // remove all the %- combos from the string boost::algorithm::erase_all(format, <API key>); // remove all the %+ in the string with '+' boost::algorithm::replace_all(format, <API key>, positive_sign); } // %T and %R have to be replaced here since they are not standard boost::algorithm::replace_all(format, boost::as_literal(formats_type::<API key>), boost::as_literal(formats_type::<API key>)); boost::algorithm::replace_all(format, boost::as_literal(formats_type::<API key>), boost::as_literal(formats_type::<API key>)); /* * It is possible for a time duration to span more then 24 hours. * Standard time_put::put is obliged to behave the same as strftime * (See ISO 14882-2003 22.2.5.3.1 par. 1) and strftime's behavior is * unspecified for the case when tm_hour field is outside 0-23 range * (See ISO 9899-1999 7.23.3.5 par. 3). So we must output %H and %O * here ourself. */ string_type hours_str; if (format.find(<API key>) != string_type::npos) { hours_str = hours_as_string(time_dur_arg); boost::algorithm::replace_all(format, <API key>, hours_str); } // We still have to process restricted hours format specifier. In order to // support parseability of durations in ISO format (%H%M%S), we'll have to // restrict the stringified hours length to 2 characters. if (format.find(hours_format) != string_type::npos) { if (hours_str.empty()) hours_str = hours_as_string(time_dur_arg); BOOST_ASSERT(hours_str.length() <= 2); boost::algorithm::replace_all(format, hours_format, hours_str); } string_type frac_str; if (format.find(<API key>) != string_type::npos) { // replace %s with %S.nnn frac_str = <API key>(time_dur_arg, false); char_type sep = std::use_facet<std::numpunct<char_type> >(ios_arg.getloc()).decimal_point(); string_type replace_string(seconds_format); replace_string += sep; replace_string += frac_str; boost::algorithm::replace_all(format, <API key>, replace_string); } if (format.find(<API key>) != string_type::npos) { // replace %f with nnnnnnn if (!frac_str.size()) { frac_str = <API key>(time_dur_arg, false); } boost::algorithm::replace_all(format, <API key>, frac_str); } if (format.find(<API key>) != string_type::npos) { // replace %F with nnnnnnn or nothing if fs == 0 frac_str = <API key>(time_dur_arg, true); if (frac_str.size()) { char_type sep = std::use_facet<std::numpunct<char_type> >(ios_arg.getloc()).decimal_point(); string_type replace_string; replace_string += sep; replace_string += frac_str; boost::algorithm::replace_all(format, <API key>, replace_string); } else { boost::algorithm::erase_all(format, <API key>); } } return this->do_put_tm(next_arg, ios_arg, fill_arg, to_tm(time_dur_arg), format); } OutItrT put(OutItrT next, std::ios_base& ios_arg, char_type fill, const period_type& p) const { return this->m_period_formatter.put_period(next, ios_arg, fill,p,*this); } protected: static string_type <API key>(const time_duration_type& time_arg, bool null_when_zero) { typename time_duration_type::<API key> frac_sec = time_arg.fractional_seconds(); if (null_when_zero && (frac_sec == 0)) { return string_type(); } //make sure there is no sign return integral_as_string( date_time::absolute_value(frac_sec), time_duration_type::<API key>()); } static string_type hours_as_string(const time_duration_type& time_arg, int width = 2) { return integral_as_string(date_time::absolute_value(time_arg.hours()), width); } template< typename IntT > static string_type integral_as_string(IntT val, int width = 2) { std::basic_ostringstream<char_type> ss; ss.imbue(std::locale::classic()); // don't want any formatting ss << std::setw(width) << std::setfill(static_cast<char_type>('0')); #if (defined(BOOST_MSVC) && (_MSC_VER < 1300)) // JDG [7/6/02 VC++ compatibility] char_type buff[34]; ss << _i64toa(static_cast<boost::int64_t>(val), buff, 10); #else ss << val; #endif return ss.str(); } private: string_type <API key>; }; template <class time_type, class CharT, class OutItrT> std::locale::id time_facet<time_type, CharT, OutItrT>::id; template <class time_type, class CharT, class OutItrT> const typename time_facet<time_type, CharT, OutItrT>::char_type* time_facet<time_type, CharT, OutItrT>::<API key> = time_formats<CharT>::<API key>; template <class time_type, class CharT, class OutItrT> const typename time_facet<time_type, CharT, OutItrT>::char_type* time_facet<time_type, CharT, OutItrT>::<API key> = time_formats<CharT>::<API key>; template <class time_type, class CharT, class OutItrT> const typename time_facet<time_type, CharT, OutItrT>::char_type* time_facet<time_type, CharT, OutItrT>::<API key> = time_formats<CharT>::<API key>; template <class time_type, class CharT, class OutItrT> const typename time_facet<time_type, CharT, OutItrT>::char_type* time_facet<time_type, CharT, OutItrT>::zone_name_format = time_formats<CharT>::zone_name_format; template <class time_type, class CharT, class OutItrT> const typename time_facet<time_type, CharT, OutItrT>::char_type* time_facet<time_type, CharT, OutItrT>::zone_abbrev_format = time_formats<CharT>::zone_abbrev_format; template <class time_type, class CharT, class OutItrT> const typename time_facet<time_type, CharT, OutItrT>::char_type* time_facet<time_type, CharT, OutItrT>::<API key> =time_formats<CharT>::<API key>; template <class time_type, class CharT, class OutItrT> const typename time_facet<time_type, CharT, OutItrT>::char_type* time_facet<time_type, CharT, OutItrT>::<API key> =time_formats<CharT>::<API key>; template <class time_type, class CharT, class OutItrT> const typename time_facet<time_type, CharT, OutItrT>::char_type* time_facet<time_type, CharT, OutItrT>::zone_iso_format = time_formats<CharT>::zone_iso_format; template <class time_type, class CharT, class OutItrT> const typename time_facet<time_type, CharT, OutItrT>::char_type* time_facet<time_type, CharT, OutItrT>::seconds_format = time_formats<CharT>::seconds_format; template <class time_type, class CharT, class OutItrT> const typename time_facet<time_type, CharT, OutItrT>::char_type* time_facet<time_type, CharT, OutItrT>::hours_format = time_formats<CharT>::hours_format; template <class time_type, class CharT, class OutItrT> const typename time_facet<time_type, CharT, OutItrT>::char_type* time_facet<time_type, CharT, OutItrT>::<API key> = time_formats<CharT>::<API key>; template <class time_type, class CharT, class OutItrT> const typename time_facet<time_type, CharT, OutItrT>::char_type* time_facet<time_type, CharT, OutItrT>::standard_format = time_formats<CharT>::standard_format; template <class time_type, class CharT, class OutItrT> const typename time_facet<time_type, CharT, OutItrT>::char_type* time_facet<time_type, CharT, OutItrT>::duration_seperator = time_formats<CharT>::duration_seperator; template <class time_type, class CharT, class OutItrT> const typename time_facet<time_type, CharT, OutItrT>::char_type* time_facet<time_type, CharT, OutItrT>::negative_sign = time_formats<CharT>::negative_sign; template <class time_type, class CharT, class OutItrT> const typename time_facet<time_type, CharT, OutItrT>::char_type* time_facet<time_type, CharT, OutItrT>::positive_sign = time_formats<CharT>::positive_sign; template <class time_type, class CharT, class OutItrT> const typename time_facet<time_type, CharT, OutItrT>::char_type* time_facet<time_type, CharT, OutItrT>::<API key> = time_formats<CharT>::<API key>; template <class time_type, class CharT, class OutItrT> const typename time_facet<time_type, CharT, OutItrT>::char_type* time_facet<time_type, CharT, OutItrT>::<API key> = time_formats<CharT>::<API key>; template <class time_type, class CharT, class OutItrT> const typename time_facet<time_type,CharT, OutItrT>::char_type* time_facet<time_type,CharT, OutItrT>::<API key> = time_formats<CharT>::<API key>; template <class time_type, class CharT, class OutItrT> const typename time_facet<time_type, CharT, OutItrT>::char_type* time_facet<time_type, CharT, OutItrT>::<API key> = time_formats<CharT>::<API key>; template <class time_type, class CharT, class OutItrT> const typename time_facet<time_type, CharT, OutItrT>::char_type* time_facet<time_type, CharT, OutItrT>::default_time_format = time_formats<CharT>::default_time_format; template <class time_type, class CharT, class OutItrT> const typename time_facet<time_type, CharT, OutItrT>::char_type* time_facet<time_type, CharT, OutItrT>::<API key> = time_formats<CharT>::<API key>; //! Facet for format-based input. template <class time_type, class CharT, class InItrT = std::istreambuf_iterator<CharT, std::char_traits<CharT> > > class time_input_facet : public boost::date_time::date_input_facet<typename time_type::date_type , CharT, InItrT> { public: typedef typename time_type::date_type date_type; typedef typename time_type::time_duration_type time_duration_type; typedef typename time_duration_type::<API key> <API key>; typedef boost::date_time::period<time_type,time_duration_type> period_type; typedef boost::date_time::date_input_facet<typename time_type::date_type, CharT, InItrT> base_type; typedef typename base_type::duration_type date_duration_type; typedef typename base_type::year_type year_type; typedef typename base_type::month_type month_type; typedef typename base_type::day_type day_type; typedef typename base_type::string_type string_type; typedef typename string_type::const_iterator const_itr; typedef typename base_type::char_type char_type; typedef typename base_type::<API key> <API key>; typedef typename base_type::period_parser_type period_parser_type; typedef typename base_type::<API key> <API key>; typedef typename base_type::<API key> <API key>; typedef typename base_type::<API key>::match_results match_results; static const char_type* <API key>; static const char_type* <API key>; static const char_type* <API key>; static const char_type* seconds_format; static const char_type* standard_format; // x X static const char_type* zone_abbrev_format; static const char_type* zone_name_format; static const char_type* zone_iso_format; static const char_type* <API key>; static const char_type* duration_seperator; static const char_type* <API key>; static const char_type* <API key>; static const char_type* <API key>; static const char_type* <API key>; static std::locale::id id; //! Constructor that takes a format string for a ptime explicit time_input_facet(const string_type& format, ::size_t ref_arg = 0) : base_type(format, ref_arg), <API key>(<API key>) { } explicit time_input_facet(const string_type& format, const <API key>& date_parser, const <API key>& sv_parser, const period_parser_type& per_parser, const <API key>& date_gen_parser, ::size_t ref_arg = 0) : base_type(format, date_parser, sv_parser, per_parser, date_gen_parser, ref_arg), <API key>(<API key>) {} //! sets default formats for ptime, local_date_time, and time_duration explicit time_input_facet(::size_t ref_arg = 0) : base_type(<API key>, ref_arg), <API key>(<API key>) { } //! Set the format for time_duration void <API key>(const char_type* const format) { <API key> = format; } virtual void set_iso_format() { this->m_format = <API key>; } virtual void <API key>() { this->m_format = <API key>; } InItrT get(InItrT& sitr, InItrT& stream_end, std::ios_base& ios_arg, period_type& p) const { p = this->m_period_parser.get_period(sitr, stream_end, ios_arg, p, time_duration_type::unit(), *this); return sitr; } //default ptime format is YYYY-Mon-DD HH:MM:SS[.fff...][ zzz] //default time_duration format is %H:%M:%S%F HH:MM:SS[.fff...] InItrT get(InItrT& sitr, InItrT& stream_end, std::ios_base& ios_arg, time_duration_type& td) const { // skip leading whitespace while((sitr != stream_end) && std::isspace(*sitr)) { ++sitr; } bool use_current_char = false; // num_get will consume the +/-, we may need a copy if special_value char_type c = '\0'; if((sitr != stream_end) && (*sitr == '-' || *sitr == '+')) { c = *sitr; } typedef typename time_duration_type::hour_type hour_type; typedef typename time_duration_type::min_type min_type; typedef typename time_duration_type::sec_type sec_type; hour_type hour = 0; min_type min = 0; sec_type sec = 0; typename time_duration_type::<API key> frac(0); typedef std::num_get<CharT, InItrT> num_get; if(!std::has_facet<num_get>(ios_arg.getloc())) { num_get* ng = new num_get(); std::locale loc = std::locale(ios_arg.getloc(), ng); ios_arg.imbue(loc); } const_itr itr(<API key>.begin()); while (itr != <API key>.end() && (sitr != stream_end)) { if (*itr == '%') { if (++itr == <API key>.end()) break; if (*itr != '%') { switch(*itr) { case 'O': { // A period may span more than 24 hours. In that case the format // string should be composed with the unrestricted hours specifier. hour = var_string_to_int<hour_type, CharT>(sitr, stream_end, std::numeric_limits<hour_type>::digits10 + 1); if(hour == -1){ return check_special_value(sitr, stream_end, td, c); } break; } case 'H': { match_results mr; hour = fixed_string_to_int<hour_type, CharT>(sitr, stream_end, mr, 2); if(hour == -1){ return check_special_value(sitr, stream_end, td, c); } break; } case 'M': { match_results mr; min = fixed_string_to_int<min_type, CharT>(sitr, stream_end, mr, 2); if(min == -1){ return check_special_value(sitr, stream_end, td, c); } break; } case 's': case 'S': { match_results mr; sec = fixed_string_to_int<sec_type, CharT>(sitr, stream_end, mr, 2); if(sec == -1){ return check_special_value(sitr, stream_end, td, c); } if (*itr == 'S') break; // %s is the same as %S%f so we drop through into %f } case 'f': { // check for decimal, check special_values if missing if(*sitr == '.') { ++sitr; parse_frac_type(sitr, stream_end, frac); // sitr will point to next expected char after this parsing // is complete so no need to advance it use_current_char = true; } else { return check_special_value(sitr, stream_end, td, c); } break; } case 'F': { // check for decimal, skip if missing if(*sitr == '.') { ++sitr; parse_frac_type(sitr, stream_end, frac); // sitr will point to next expected char after this parsing // is complete so no need to advance it use_current_char = true; } else { // nothing was parsed so we don't want to advance sitr use_current_char = true; } break; } default: {} // ignore what we don't understand? }// switch } else { // itr == '%', second consecutive ++sitr; } ++itr; //advance past format specifier } else { //skip past chars in format and in buffer ++itr; // set use_current_char when sitr is already // pointing at the next character to process if (use_current_char) { use_current_char = false; } else { ++sitr; } } } td = time_duration_type(hour, min, sec, frac); return sitr; } //! Parses a time object from the input stream InItrT get(InItrT& sitr, InItrT& stream_end, std::ios_base& ios_arg, time_type& t) const { string_type tz_str; return get(sitr, stream_end, ios_arg, t, tz_str, false); } //! Expects a time_zone in the input stream InItrT get_local_time(InItrT& sitr, InItrT& stream_end, std::ios_base& ios_arg, time_type& t, string_type& tz_str) const { return get(sitr, stream_end, ios_arg, t, tz_str, true); } protected: InItrT get(InItrT& sitr, InItrT& stream_end, std::ios_base& ios_arg, time_type& t, string_type& tz_str, bool time_is_local) const { // skip leading whitespace while((sitr != stream_end) && std::isspace(*sitr)) { ++sitr; } bool use_current_char = false; bool <API key> = false; // used whith two character flags // num_get will consume the +/-, we may need a copy if special_value char_type c = '\0'; if((sitr != stream_end) && (*sitr == '-' || *sitr == '+')) { c = *sitr; } typedef typename time_duration_type::hour_type hour_type; typedef typename time_duration_type::min_type min_type; typedef typename time_duration_type::sec_type sec_type; // time elements hour_type hour = 0; min_type min = 0; sec_type sec = 0; typename time_duration_type::<API key> frac(0); // date elements short day_of_year(0); /* Initialized the following to their minimum values. These intermediate * objects are used so we get specific exceptions when part of the input * is unparsable. * Ex: "205-Jan-15" will throw a bad_year, "2005-Jsn-15"- bad_month, etc.*/ year_type t_year(1400); month_type t_month(1); day_type t_day(1); typedef std::num_get<CharT, InItrT> num_get; if(!std::has_facet<num_get>(ios_arg.getloc())) { num_get* ng = new num_get(); std::locale loc = std::locale(ios_arg.getloc(), ng); ios_arg.imbue(loc); } const_itr itr(this->m_format.begin()); while (itr != this->m_format.end() && (sitr != stream_end)) { if (*itr == '%') { if (++itr == this->m_format.end()) break; if (*itr != '%') { // the cases are grouped by date & time flags - not alphabetical order switch(*itr) { // date flags case 'Y': case 'y': { char_type cs[3] = { '%', *itr }; string_type s(cs); match_results mr; try { t_year = this->m_parser.parse_year(sitr, stream_end, s, mr); } catch(std::out_of_range&) { // base class for bad_year exception if(this->m_sv_parser.match(sitr, stream_end, mr)) { t = time_type(static_cast<special_values>(mr.current_match)); return sitr; } else { throw; // rethrow bad_year } } break; } case 'B': case 'b': case 'm': { char_type cs[3] = { '%', *itr }; string_type s(cs); match_results mr; try { t_month = this->m_parser.parse_month(sitr, stream_end, s, mr); } catch(std::out_of_range&) { // base class for bad_month exception if(this->m_sv_parser.match(sitr, stream_end, mr)) { t = time_type(static_cast<special_values>(mr.current_match)); return sitr; } else { throw; // rethrow bad_month } } // did m_parser already advance sitr to next char? if(mr.has_remaining()) { use_current_char = true; } break; } case 'a': case 'A': case 'w': { // weekday is not used in construction but we need to get it out of the stream char_type cs[3] = { '%', *itr }; string_type s(cs); match_results mr; typename date_type::day_of_week_type wd(0); try { wd = this->m_parser.parse_weekday(sitr, stream_end, s, mr); } catch(std::out_of_range&) { // base class for bad_weekday exception if(this->m_sv_parser.match(sitr, stream_end, mr)) { t = time_type(static_cast<special_values>(mr.current_match)); return sitr; } else { throw; // rethrow bad_weekday } } // did m_parser already advance sitr to next char? if(mr.has_remaining()) { use_current_char = true; } break; } case 'j': { // code that gets julian day (from format_date_parser) match_results mr; day_of_year = fixed_string_to_int<unsigned short, CharT>(sitr, stream_end, mr, 3); if(day_of_year == -1) { if(this->m_sv_parser.match(sitr, stream_end, mr)) { t = time_type(static_cast<special_values>(mr.current_match)); return sitr; } } // these next two lines are so we get an exception with bad input typedef typename time_type::date_type::day_of_year_type day_of_year_type; day_of_year_type t_day_of_year(day_of_year); break; } case 'd': { try { t_day = this->m_parser.parse_day_of_month(sitr, stream_end); } catch(std::out_of_range&) { // base class for exception bad_day_of_month match_results mr; if(this->m_sv_parser.match(sitr, stream_end, mr)) { t = time_type(static_cast<special_values>(mr.current_match)); return sitr; } else { throw; // rethrow bad_day_of_month } } break; } // time flags case 'H': { match_results mr; hour = fixed_string_to_int<hour_type, CharT>(sitr, stream_end, mr, 2); if(hour == -1){ return check_special_value(sitr, stream_end, t, c); } break; } case 'M': { match_results mr; min = fixed_string_to_int<min_type, CharT>(sitr, stream_end, mr, 2); if(min == -1){ return check_special_value(sitr, stream_end, t, c); } break; } case 's': case 'S': { match_results mr; sec = fixed_string_to_int<sec_type, CharT>(sitr, stream_end, mr, 2); if(sec == -1){ return check_special_value(sitr, stream_end, t, c); } if (*itr == 'S') break; // %s is the same as %S%f so we drop through into %f } case 'f': { // check for decimal, check SV if missing if(*sitr == '.') { ++sitr; parse_frac_type(sitr, stream_end, frac); // sitr will point to next expected char after this parsing // is complete so no need to advance it use_current_char = true; } else { return check_special_value(sitr, stream_end, t, c); } break; } case 'F': { // check for decimal, skip if missing if(*sitr == '.') { ++sitr; parse_frac_type(sitr, stream_end, frac); // sitr will point to next expected char after this parsing // is complete so no need to advance it use_current_char = true; } else { // nothing was parsed so we don't want to advance sitr use_current_char = true; } break; } // time_zone flags //case 'q': //case 'Q': //case 'z': case 'Z': { if(time_is_local) { // skip if 't' is a ptime ++itr; if(*itr == 'P') { // skip leading whitespace while((sitr != stream_end) && std::isspace(*sitr)) { ++sitr; } // parse zone while((sitr != stream_end) && (!std::isspace(*sitr))) { tz_str += *sitr; ++sitr; } } else { <API key> = true; } } else { // nothing was parsed so we don't want to advance sitr use_current_char = true; } break; } default: {} // ignore what we don't understand? }// switch } else { // itr == '%', second consecutive ++sitr; } if(<API key>) { <API key> = false; } else { ++itr; //advance past format specifier } } else { //skip past chars in format and in buffer ++itr; // set use_current_char when sitr is already // pointing at the next character to process if (use_current_char) { use_current_char = false; } else { ++sitr; } } } date_type d(not_a_date_time); if (day_of_year > 0) { d = date_type(static_cast<unsigned short>(t_year-1),12,31) + date_duration_type(day_of_year); } else { d = date_type(t_year, t_month, t_day); } time_duration_type td(hour, min, sec, frac); t = time_type(d, td); return sitr; } //! Helper function to check for special_value /*! First character may have been consumed during original parse * attempt. Parameter 'c' should be a copy of that character. * Throws ios_base::failure if parse fails. */ template<class temporal_type> inline InItrT check_special_value(InItrT& sitr,InItrT& stream_end, temporal_type& tt, char_type c='\0') const { match_results mr; if((c == '-' || c == '+') && (*sitr != c)) { // was the first character consumed? mr.cache += c; } this->m_sv_parser.match(sitr, stream_end, mr); if(mr.current_match == match_results::PARSE_ERROR) { std::string tmp = convert_string_type<char_type, char>(mr.cache); boost::throw_exception(std::ios_base::failure("Parse failed. No match found for '" + tmp + "'")); <API key>(return sitr); // should never reach } tt = temporal_type(static_cast<special_values>(mr.current_match)); return sitr; } //! Helper function for parsing a fractional second type from the stream void parse_frac_type(InItrT& sitr, InItrT& stream_end, <API key>& frac) const { string_type cache; while((sitr != stream_end) && std::isdigit(*sitr)) { cache += *sitr; ++sitr; } if(cache.size() > 0) { unsigned short precision = time_duration_type::<API key>(); // input may be only the first few decimal places if(cache.size() < precision) { frac = lexical_cast<<API key>>(cache); frac = decimal_adjust(frac, static_cast<unsigned short>(precision - cache.size())); } else { // if input has too many decimal places, drop excess digits frac = lexical_cast<<API key>>(cache.substr(0, precision)); } } } private: string_type <API key>; //! Helper function to adjust trailing zeros when parsing fractional digits template<class int_type> inline int_type decimal_adjust(int_type val, const unsigned short places) const { unsigned long factor = 1; for(int i = 0; i < places; ++i){ factor *= 10; // shift decimal to the right } return val * factor; } }; template <class time_type, class CharT, class InItrT> std::locale::id time_input_facet<time_type, CharT, InItrT>::id; template <class time_type, class CharT, class InItrT> const typename time_input_facet<time_type, CharT, InItrT>::char_type* time_input_facet<time_type, CharT, InItrT>::<API key> = time_formats<CharT>::<API key>; template <class time_type, class CharT, class InItrT> const typename time_input_facet<time_type, CharT, InItrT>::char_type* time_input_facet<time_type, CharT, InItrT>::<API key> = time_formats<CharT>::<API key>; template <class time_type, class CharT, class InItrT> const typename time_input_facet<time_type, CharT, InItrT>::char_type* time_input_facet<time_type, CharT, InItrT>::<API key> = time_formats<CharT>::<API key>; template <class time_type, class CharT, class InItrT> const typename time_input_facet<time_type, CharT, InItrT>::char_type* time_input_facet<time_type, CharT, InItrT>::seconds_format = time_formats<CharT>::seconds_format; template <class time_type, class CharT, class InItrT> const typename time_input_facet<time_type, CharT, InItrT>::char_type* time_input_facet<time_type, CharT, InItrT>::standard_format = time_formats<CharT>::standard_format; template <class time_type, class CharT, class InItrT> const typename time_input_facet<time_type, CharT, InItrT>::char_type* time_input_facet<time_type, CharT, InItrT>::zone_abbrev_format = time_formats<CharT>::zone_abbrev_format; template <class time_type, class CharT, class InItrT> const typename time_input_facet<time_type, CharT, InItrT>::char_type* time_input_facet<time_type, CharT, InItrT>::zone_name_format = time_formats<CharT>::zone_name_format; template <class time_type, class CharT, class InItrT> const typename time_input_facet<time_type, CharT, InItrT>::char_type* time_input_facet<time_type, CharT, InItrT>::zone_iso_format = time_formats<CharT>::zone_iso_format; template <class time_type, class CharT, class InItrT> const typename time_input_facet<time_type, CharT, InItrT>::char_type* time_input_facet<time_type, CharT, InItrT>::<API key> = time_formats<CharT>::<API key>; template <class time_type, class CharT, class InItrT> const typename time_input_facet<time_type, CharT, InItrT>::char_type* time_input_facet<time_type, CharT, InItrT>::duration_seperator = time_formats<CharT>::duration_seperator; template <class time_type, class CharT, class InItrT> const typename time_input_facet<time_type, CharT, InItrT>::char_type* time_input_facet<time_type, CharT, InItrT>::<API key> = time_formats<CharT>::<API key>; template <class time_type, class CharT, class InItrT> const typename time_input_facet<time_type, CharT, InItrT>::char_type* time_input_facet<time_type, CharT, InItrT>::<API key> = time_formats<CharT>::<API key>; template <class time_type, class CharT, class InItrT> const typename time_input_facet<time_type, CharT, InItrT>::char_type* time_input_facet<time_type, CharT, InItrT>::<API key> = time_formats<CharT>::<API key>; template <class time_type, class CharT, class InItrT> const typename time_input_facet<time_type, CharT, InItrT>::char_type* time_input_facet<time_type, CharT, InItrT>::<API key> = time_formats<CharT>::<API key>; } } // namespaces #endif
// <auto-generated/> using System; namespace Telegram.Api.TL { public partial class TLTextPlain : TLRichTextBase { public String Text { get; set; } public TLTextPlain() { } public TLTextPlain(TLBinaryReader from) { Read(from); } public override TLType TypeId { get { return TLType.TextPlain; } } public override void Read(TLBinaryReader from) { Text = from.ReadString(); } public override void Write(TLBinaryWriter to) { to.Write(0x744694E0); to.Write(Text); } } }
package com.bfh.logisim.settings; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.regex.Pattern; import java.util.zip.ZipEntry; import java.util.zip.ZipException; import java.util.zip.ZipFile; public class BoardList { public static String getBoardName(String BoardIdentifier) { String[] parts; if (BoardIdentifier.contains("url:")) parts = BoardIdentifier.split("/"); else parts = BoardIdentifier.split(Pattern.quote(File.separator)); return parts[parts.length - 1].replace(".xml", ""); } private static Collection<String> getBoards(Pattern p, String Match, String Element) { ArrayList<String> ret = new ArrayList<String>(); File file = new File(Element); if (file.isDirectory()) { ret.addAll(<API key>(p, Match, file)); } else { ret.addAll(getBoardsfromJar(p, Match, file)); } return ret; } private static Collection<String> <API key>(Pattern p, String Match, File Dir) { ArrayList<String> ret = new ArrayList<String>(); File[] fileList = Dir.listFiles(); for (File file : fileList) { if (file.isDirectory()) { ret.addAll(<API key>(p, Match, file)); } else { try { String fileName = file.getCanonicalPath(); boolean accept = p.matcher(fileName).matches() && fileName.contains(Match); if (accept) { ret.add("file:" + fileName); } } catch (IOException e) { throw new Error(e); } } } return ret; } private static Collection<String> getBoardsfromJar(Pattern p, String Match, File Dir) { // All path separators are defined with File.Separator, but when // browsing the .jar, java uses slash even in Windows Match = Match.replaceAll("\\\\", "/"); ArrayList<String> ret = new ArrayList<String>(); ZipFile zf; try { zf = new ZipFile(Dir); } catch (ZipException e) { throw new Error(e); } catch (IOException e) { throw new Error(e); } Enumeration<? extends ZipEntry> e = zf.entries(); while (e.hasMoreElements()) { ZipEntry ze = (ZipEntry) e.nextElement(); String fileName = ze.getName(); boolean accept = p.matcher(fileName).matches() && fileName.contains(Match); if (accept) { ret.add("url:" + fileName); } } try { zf.close(); } catch (IOException e1) { throw new Error(e1); } return ret; } private static String BoardResourcePath = "resources" + File.separator + "logisim" + File.separator + "boards"; private ArrayList<String> DefinedBoards = new ArrayList<String>(); public BoardList() { String classPath = System.getProperty("java.class.path", File.pathSeparator); String[] classPathElements = classPath.split(File.pathSeparator); Pattern p = Pattern.compile(".*.xml"); for (String element : classPathElements) { DefinedBoards.addAll(getBoards(p, BoardResourcePath, element)); } } public boolean AddExternalBoard(String Filename) { if (!DefinedBoards.contains(Filename)) { DefinedBoards.add(Filename); return true; } return false; } public boolean RemoveExternalBoard(String Filename) { if (DefinedBoards.contains(Filename)) { int index = DefinedBoards.indexOf(Filename); DefinedBoards.remove(index); return true; } return false; } public String GetBoardFilePath(String BoardName) { if (BoardName == null) return null; for (String board : DefinedBoards) { if (getBoardName(board).equals(BoardName)) { return board; } } return null; } @SuppressWarnings("serial") private class SortedArrayList<T> extends ArrayList<T> { @SuppressWarnings("unchecked") public void insertSorted(T value) { add(value); Comparable<T> cmp = (Comparable<T>) value; for (int i = size()-1; i > 0 && cmp.compareTo(get(i-1)) < 0; i Collections.swap(this, i, i-1); } } public ArrayList<String> GetBoardNames() { SortedArrayList<String> ret = new SortedArrayList<String>(); for (String board : DefinedBoards) { ret.insertSorted(getBoardName(board)); } return ret; } }
/* vim: set expandtab ts=4 sw=4: */ #include "admin/Admin.h" #include "benc/String.h" #include "benc/Dict.h" #include "exception/Except.h" #include "exception/Jmp.h" #include "util/log/Log.h" #include "util/Security.h" #include "util/Security_admin.h" struct Context { struct Log* logger; struct Admin* admin; struct Security* sec; Identity }; static void sendError(char* errorMessage, String* txid, struct Admin* admin) { Dict error = Dict_CONST(String_CONST("error"), String_OBJ(String_CONST(errorMessage)), NULL); Admin_sendMessage(&error, txid, admin); } static void setUser(Dict* args, void* vctx, String* txid, struct Allocator* requestAlloc) { struct Context* const ctx = Identity_check((struct Context*) vctx); struct Jmp jmp; Jmp_try(jmp) { int64_t* user = Dict_getIntC(args, "uid"); int64_t* group = Dict_getIntC(args, "gid"); int gid = group ? (int)*group : 0; int64_t* keepNetAdmin = Dict_getIntC(args, "keepNetAdmin"); Security_setUser(*user, gid, *keepNetAdmin, ctx->logger, &jmp.handler, requestAlloc); } Jmp_catch { sendError(jmp.message, txid, ctx->admin); return; } sendError("none", txid, ctx->admin); } static void checkPermissionsB(struct Except* eh, String* txid, struct Admin* admin, struct Allocator* requestAlloc) { struct <API key>* sp = <API key>(requestAlloc, eh); Dict* out = Dict_new(requestAlloc); Dict_putIntC(out, "noOpenFiles", sp->noOpenFiles, requestAlloc); Dict_putIntC(out, "seccompExists", sp->seccompExists, requestAlloc); Dict_putIntC(out, "seccompEnforcing", sp->seccompEnforcing, requestAlloc); Dict_putIntC(out, "userId", sp->uid, requestAlloc); Dict_putStringCC(out, "error", "none", requestAlloc); Admin_sendMessage(out, txid, admin); } static void checkPermissions(Dict* args, void* vctx, String* txid, struct Allocator* requestAlloc) { struct Context* const ctx = Identity_check((struct Context*) vctx); struct Jmp jmp; Jmp_try(jmp) { checkPermissionsB(&jmp.handler, txid, ctx->admin, requestAlloc); } Jmp_catch { sendError(jmp.message, txid, ctx->admin); return; } } #define NOARG_CALL(vctx, txid, func) \ do { \ struct Context* const ctx = Identity_check((struct Context*) vctx); \ struct Jmp jmp; \ Jmp_try(jmp) { \ func(&jmp.handler); \ } Jmp_catch { \ sendError(jmp.message, txid, ctx->admin); \ return; \ } \ sendError("none", txid, ctx->admin); \ } while (0) // CHECKFILES_IGNORE expecting { bracket static void nofiles(Dict* args, void* vctx, String* txid, struct Allocator* requestAlloc) { NOARG_CALL(vctx, txid, Security_nofiles); } static void noforks(Dict* args, void* vctx, String* txid, struct Allocator* requestAlloc) { NOARG_CALL(vctx, txid, Security_noforks); } static void chroot(Dict* args, void* vctx, String* txid, struct Allocator* requestAlloc) { struct Context* const ctx = Identity_check((struct Context*) vctx); struct Jmp jmp; Jmp_try(jmp) { String* root = Dict_getStringC(args, "root"); Security_chroot(root->bytes, &jmp.handler); } Jmp_catch { sendError(jmp.message, txid, ctx->admin); return; } sendError("none", txid, ctx->admin); } static void seccomp(Dict* args, void* vctx, String* txid, struct Allocator* requestAlloc) { struct Context* const ctx = Identity_check((struct Context*) vctx); struct Jmp jmp; struct Except* eh = &jmp.handler; Jmp_try(jmp) { struct <API key>* sp = <API key>(requestAlloc, eh); if (!sp->seccompEnforcing) { Security_seccomp(requestAlloc, ctx->logger, eh); } else { sendError("seccomp is already enabled", txid, ctx->admin); } } Jmp_catch { sendError(jmp.message, txid, ctx->admin); return; } sendError("none", txid, ctx->admin); } static void setupComplete(Dict* args, void* vctx, String* txid, struct Allocator* requestAlloc) { struct Context* const ctx = Identity_check((struct Context*) vctx); <API key>(ctx->sec); sendError("none", txid, ctx->admin); } static void getUser(Dict* args, void* vctx, String* txid, struct Allocator* requestAlloc) { struct Context* const ctx = Identity_check((struct Context*) vctx); String* user = Dict_getStringC(args, "user"); Dict* ret = Security_getUser((user) ? user->bytes : NULL, requestAlloc); Admin_sendMessage(ret, txid, ctx->admin); } void <API key>(struct Allocator* alloc, struct Log* logger, struct Security* sec, struct Admin* admin) { struct Context* ctx = Allocator_clone(alloc, (&(struct Context) { .logger = logger, .admin = admin })); Identity_set(ctx); ctx->sec = sec; <API key>("Security_nofiles", nofiles, ctx, true, NULL, admin); <API key>("Security_noforks", noforks, ctx, true, NULL, admin); <API key>("Security_chroot", chroot, ctx, true, ((struct Admin_FunctionArg[]) { { .name = "root", .required = 1, .type = "String" } }), admin); <API key>("Security_setUser", setUser, ctx, true, ((struct Admin_FunctionArg[]) { { .name = "uid", .required = 1, .type = "Int" }, { .name = "gid", .required = 0, .type = "Int" }, { .name = "keepNetAdmin", .required = 1, .type = "Int" }, }), admin); <API key>("Security_getUser", getUser, ctx, true, ((struct Admin_FunctionArg[]) { { .name = "user", .required = 0, .type = "String" } }), admin); <API key>("Security_seccomp", seccomp, ctx, true, NULL, admin); <API key>("<API key>", setupComplete, ctx, true, NULL, admin); <API key>("<API key>", checkPermissions, ctx, true, NULL, admin); }
// Generated on 04/17/2013 22:29:58 using System; using System.Collections.Generic; using System.Linq; using BiM.Protocol.Types; using BiM.Core.IO; using BiM.Core.Network; namespace BiM.Protocol.Messages { public class <API key> : <API key> { public const uint Id = 5784; public override uint MessageId { get { return Id; } } public int target; public int skillId; public <API key>() { } public <API key>(sbyte exchangeType, int target, int skillId) : base(exchangeType) { this.target = target; this.skillId = skillId; } public override void Serialize(IDataWriter writer) { base.Serialize(writer); writer.WriteInt(target); writer.WriteInt(skillId); } public override void Deserialize(IDataReader reader) { base.Deserialize(reader); target = reader.ReadInt(); if (target < 0) throw new Exception("Forbidden value on target = " + target + ", it doesn't respect the following condition : target < 0"); skillId = reader.ReadInt(); if (skillId < 0) throw new Exception("Forbidden value on skillId = " + skillId + ", it doesn't respect the following condition : skillId < 0"); } } }
/** * @private */ Ext.define('Ext.chart.Shape', { /* Begin Definitions */ singleton: true, /* End Definitions */ circle: function (surface, opts) { return surface.add(Ext.apply({ type: 'circle', x: opts.x, y: opts.y, stroke: null, radius: opts.radius }, opts)); }, line: function (surface, opts) { return surface.add(Ext.apply({ type: 'rect', x: opts.x - opts.radius, y: opts.y - opts.radius, height: 2 * opts.radius, width: 2 * opts.radius / 5 }, opts)); }, square: function (surface, opts) { return surface.add(Ext.applyIf({ type: 'rect', x: opts.x - opts.radius, y: opts.y - opts.radius, height: 2 * opts.radius, width: 2 * opts.radius, radius: null }, opts)); }, triangle: function (surface, opts) { opts.radius *= 1.75; return surface.add(Ext.apply({ type: 'path', stroke: null, path: "M".concat(opts.x, ",", opts.y, "m0-", opts.radius * 0.58, "l", opts.radius * 0.5, ",", opts.radius * 0.87, "-", opts.radius, ",0z") }, opts)); }, diamond: function (surface, opts) { var r = opts.radius; r *= 1.5; return surface.add(Ext.apply({ type: 'path', stroke: null, path: ["M", opts.x, opts.y - r, "l", r, r, -r, r, -r, -r, r, -r, "z"] }, opts)); }, cross: function (surface, opts) { var r = opts.radius; r = r / 1.7; return surface.add(Ext.apply({ type: 'path', stroke: null, path: "M".concat(opts.x - r, ",", opts.y, "l", [-r, -r, r, -r, r, r, r, -r, r, r, -r, r, r, r, -r, r, -r, -r, -r, r, -r, -r, "z"]) }, opts)); }, plus: function (surface, opts) { var r = opts.radius / 1.3; return surface.add(Ext.apply({ type: 'path', stroke: null, path: "M".concat(opts.x - r / 2, ",", opts.y - r / 2, "l", [0, -r, r, 0, 0, r, r, 0, 0, r, -r, 0, 0, r, -r, 0, 0, -r, -r, 0, 0, -r, "z"]) }, opts)); }, arrow: function (surface, opts) { var r = opts.radius; return surface.add(Ext.apply({ type: 'path', path: "M".concat(opts.x - r * 0.7, ",", opts.y - r * 0.4, "l", [r * 0.6, 0, 0, -r * 0.4, r, r * 0.8, -r, r * 0.8, 0, -r * 0.4, -r * 0.6, 0], "z") }, opts)); }, drop: function (surface, x, y, text, size, angle) { size = size || 30; angle = angle || 0; surface.add({ type: 'path', path: ['M', x, y, 'l', size, 0, 'A', size * 0.4, size * 0.4, 0, 1, 0, x + size * 0.7, y - size * 0.7, 'z'], fill: '#000', stroke: 'none', rotate: { degrees: 22.5 - angle, x: x, y: y } }); angle = (angle + 90) * Math.PI / 180; surface.add({ type: 'text', x: x + size * Math.sin(angle) - 10, // Shift here, Not sure why. y: y + size * Math.cos(angle) + 5, text: text, 'font-size': size * 12 / 40, stroke: 'none', fill: '#fff' }); } });
/** * type that is used to implement a 'flashing' behavior in a node by switching colors using a timer * * @author Sharfudeen Ashraf * @author John Blanco * @author Aadish Gupta */ import stepTimer from '../../../../axon/js/stepTimer.js'; import <API key> from '../../<API key>.js'; class FlashController { /** * @param {Path} flashingNode * @param {Color} normalColor * @param {Color} flashColor * @param {Object} [options] */ constructor( flashingNode, normalColor, flashColor, options ) { // variables used to implement the flashing behavior this.transitionCountdown = 0; // @private this.flashingNode = flashingNode; // @private this.flashColor = flashColor; // @private this.normalColor = normalColor; // @private this.flashOnAtStart = options.visibleAtStart; // @private this.flashOnAtEnd = options.visibleAtEnd; // @private this.numFlashes = options.numFlashes; // @private this.timerHandle = null; // @private let time = 0; // @private this.timerListener = () => { this.timerHandle = null; if ( this.flashingNode.fill === this.flashColor ) { // Flash is on, so turn flash off. this.flashingNode.fill = this.normalColor; time = options.offTime; } else { // Flash is off, so turn flash on. this.flashingNode.fill = this.flashColor; time = options.onTime; } this.transitionCountdown if ( this.transitionCountdown > 0 ) { // Set timer for next transition. this.timerHandle = stepTimer.setTimeout( this.timerListener, time ); } }; } /** * @returns {boolean} * @public */ isFlashing() { return this.timerHandle !== null; } /** * @public */ stop() { if ( this.timerHandle ) { stepTimer.clearTimeout( this.timerHandle ); } this.timerHandle = null; } /** * @public */ forceFlashOff() { if ( this.isFlashing() ) { this.stop(); } this.setFlashOn( false ); } /** * @public */ restart() { this.stop(); this.setFlashOn( this.flashOnAtStart ); this.transitionCountdown = this.numFlashes * 2; if ( this.flashOnAtStart !== this.flashOnAtEnd ) { this.transitionCountdown -= 1; } this.timerListener(); } /** * @param {boolean} flashOn * @private */ setFlashOn( flashOn ) { this.flashingNode.fill = flashOn ? this.flashColor : this.normalColor; } } <API key>.register( 'FlashController', FlashController ); export default FlashController;
<?php namespace PhpCsFixer\Fixer\Alias; use PhpCsFixer\AbstractFixer; use PhpCsFixer\FixerDefinition\CodeSample; use PhpCsFixer\FixerDefinition\FixerDefinition; use PhpCsFixer\Preg; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; /** * @author Filippo Tessarotto <zoeslam@gmail.com> */ final class <API key> extends AbstractFixer { /** * {@inheritdoc} */ public function isCandidate(Tokens $tokens) { return $tokens->isTokenKindFound('`'); } /** * {@inheritdoc} */ public function getDefinition() { return new FixerDefinition( 'Converts backtick operators to shell_exec calls.', [ new CodeSample( 'EOT' <?php $plain = `ls -lah`; $withVar = `ls -lah $var1 ${var2} {$var3} {$var4[0]} {$var5->call()}`; EOT ), ], 'Convertion is done only when it is non risky, so when special chars like single-quotes, double-quotes and backticks are not used inside the command.' ); } /** * {@inheritdoc} */ public function getPriority() { // Should run before <API key> return 2; } /** * {@inheritdoc} */ protected function applyFix(\SplFileInfo $file, Tokens $tokens) { $backtickStarted = false; $backtickTokens = []; for ($index = $tokens->count() - 1; $index > 0; --$index) { $token = $tokens[$index]; if (!$token->equals('`')) { if ($backtickStarted) { $backtickTokens[$index] = $token; } continue; } $backtickTokens[$index] = $token; if ($backtickStarted) { $this->fixBackticks($tokens, $backtickTokens); $backtickTokens = []; } $backtickStarted = !$backtickStarted; } } /** * Override backtick code with corresponding double-quoted string. * * @param Tokens $tokens * @param array $backtickTokens */ private function fixBackticks(Tokens $tokens, array $backtickTokens) { // Track indexes for final override ksort($backtickTokens); $<API key> = key($backtickTokens); end($backtickTokens); $<API key> = key($backtickTokens); // Strip enclosing backticks array_shift($backtickTokens); array_pop($backtickTokens); // Double-quoted strings are parsed differenly if they contain // variables or not, so we need to build the new token array accordingly $count = count($backtickTokens); $newTokens = [ new Token([T_STRING, 'shell_exec']), new Token('('), ]; if (1 !== $count) { $newTokens[] = new Token('"'); } foreach ($backtickTokens as $token) { if (!$token->isGivenKind(<API key>)) { $newTokens[] = $token; continue; } $content = $token->getContent(); // Escaping special chars depends on the context: too tricky if (Preg::match('/[`"\']/u', $content)) { return; } $kind = <API key>; if (1 === $count) { $content = '"'.$content.'"'; $kind = <API key>; } $newTokens[] = new Token([$kind, $content]); } if (1 !== $count) { $newTokens[] = new Token('"'); } $newTokens[] = new Token(')'); $tokens->overrideRange($<API key>, $<API key>, $newTokens); } }
#include<iostream> using namespace std; int main() { int n; cout <<"Enter a Range: "; cin >>n; for(int i=0; i<=n; i++) { for(int j=0; j<=n-i; j++) { cout <<"*"; } for(int k=1; k<=2*i; k++) { cout <<" "; } for(int l=0; l<=n-i; l++) { cout <<"*"; } cout <<endl; } for(int i=0; i<=n; i++) { for(int j=0; j<=i; j++) { cout <<"*"; } for(int k=2*(n-i); k>0; k { cout <<" "; } for(int l=0; l<=i; l++) { cout <<"*"; } cout <<endl; } return 0; }
// $Id: <API key>.java 41 2010-04-03 20:04:12Z marcusvnac $ // software and its documentation without fee, and without a written // and this paragraph appear in all copies. This software program and // California. The software program and documentation are supplied "AS // IS", without any accompanying services from The Regents. The Regents // does not warrant that the operation of the program will be // uninterrupted or error-free. The end-user understands that the program // was developed for research purposes and is advised not to rely // exclusively on the program for any reason. IN NO EVENT SHALL THE // UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, // SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, // ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF // THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF // SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE // PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF // CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, // UPDATES, ENHANCEMENTS, OR MODIFICATIONS. package org.argouml.uml.ui; import java.util.Iterator; import java.util.List; import javax.swing.Action; import org.argouml.application.helpers.<API key>; /** * An action to navigate to the previous in the list, * i.e. first we go up, then down again to the previous in the list. * * @author Michiel */ public abstract class <API key> extends <API key> { /** * The constructor. */ public <API key>() { super("button.go-up-previous-down", true); putValue(Action.SMALL_ICON, <API key>.lookupIconResource("NavigateUpPrevious")); } /* * @see org.argouml.uml.ui.<API key>#navigateTo(java.lang.Object) */ protected Object navigateTo(Object source) { Object up = getParent(source); List family = getFamily(up); assert family.contains(source); Iterator it = family.iterator(); Object previous = null; while (it.hasNext()) { Object child = it.next(); if (child == source) { return previous; } previous = child; } return null; } /** * Get the list of elements that we are navigating through. * * @param parent the parent element that owns all elements in the list * @return the list */ public abstract List getFamily(Object parent); /** * Get the parent of the list of elements that we are navigating through. * * @param child the childelement of which we seek the previous element * @return the parent element */ public abstract Object getParent(Object child); }
# -*- coding: utf-8 -*- """Get the pollen count for a UK postcode.""" import dave.module from bs4 import BeautifulSoup from requests import get from twisted.words.protocols.irc import <API key>, attributes as A import dave.config @dave.module.help("Syntax: pollen [first part of postcode]. Get the forecast in the specified location. Only works for UK postcodes.") @dave.module.command(["pollen"], "(([gG][iI][rR] {0,}0[aA]{2})|((([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y]?[0-9][0-9]?)|(([a-pr-uwyzA-PR-UWYZ][0-9][a-hjkstuwA-HJKSTUW])|([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y][0-9][<API key>])))))$") @dave.module.priority(dave.module.Priority.HIGHEST) @dave.module.ratelimit(1, 1) def pollen(bot, args, sender, source): postcode = args[0].lower() text = None if not dave.config.redis.exists("pollen:{}".format(postcode)): res = get("https: soup = BeautifulSoup(res.text, "html.parser") element = soup.find_all("div", class_="<API key>") if element: pollen = element[0].find("span", class_="<API key>") if pollen: text = {'L': 'low', 'M': 'medium', 'H': 'high'}[pollen.text] or pollen.text dave.config.redis.setex("pollen:{}".format(postcode), 1800, text) else: text = dave.config.redis.get("pollen:{}".format(postcode)) if text: bot.reply(source, sender, <API key>( A.normal["The pollen count is currently ", A.bold[str(text)], " in ", postcode.upper()] ))
#ifndef MAVLINK_VERSION_H #define MAVLINK_VERSION_H #define MAVLINK_BUILD_DATE "Fri Nov 16 17:51:26 2012" #define <API key> "0.9" #define <API key> 179 #endif // MAVLINK_VERSION_H
function Template(opts) { var self = this; Template.base.call(self, opts); self.flist = []; self.context = {}; } inherit(Template, Command); Template.scripts = ["extra/handlebars-1.0.0.beta.6.js"]; Template.prototype.usage = 'template -- pretty print files using template\n\n' + 'Usage:\n' + ' template -h | --help\n' + ' template [-c <cvar>] [-g] <template> [<file>...]\n' + ' template [-c <cvar>] [-g] -s <tstr> [<file>...]\n\n' + 'Options:\n' + ' <template> Template file path\n' + ' <file> File to display through template\n' + ' -s <tstr> Template string\n' + ' -c <cvar> Comma separated list of shell variables to use as template context\n' + ' -g Gather all files and deliver to template as a list\n' + ' -h --help Show this message.\n'; Template.prototype.next = check_next(loadscripts(do_docopt(fileargs(function() { var self = this; if (self.inited === undefined) { var cvars; self.inited = true; self.context['pid'] = self.shell.pid; if (self.docopts['-c']) { cvars = self.docopts['-c'].split(','); for (var i = 0; i < cvars.length; i++) { var cval = sys.getenv(self, cvars[i]); if (cval === undefined) { return self.exit("Context variable " + cvars[i] + " undefined"); } self.context[cvars[i]] = (cval.length === 1) ? cval[0] : cval; } } Handlebars.registerHelper('canvas', function(item) { return item.toDataURL(); }); if (self.docopts['-s']) { self.template = Handlebars.compile(self.docopts['-s']); return next(); } fread.call(self, self.docopts['<template>'], function(err, res) { if (err) { return self.exit(err); } to('text', res, {}, function(err, res) { if (err) { return self.exit(err); } self.template = Handlebars.compile(res); return next(); }); }); } else { return next(); } function next() { self.unext({}, cef(self, function(file) { if (file === null) { if (self.docopts['-g']) { self.done = true; self.context['files'] = self.flist; return output(); } return self.exit(); } if (self.docopts['-g']) { self.flist.push(file); return next(); } self.context['file'] = file; return output(); })); } function output() { return self.output({html: self.template(self.context)}); } })))); Command.register("template", Template);
#Overwriting Data from Data Import Tool Data Import Tool allows importing documents (like customers, Suppliers, Orders, Invoices etc.) from spreadsheet file into Revalue. The very same tool can also be used for overwrite values in the existing documents. <div class="well">Overwriting data from Data Import Tool works only for the saved transactions, and not for Submitted ones.</div> Let's assume there are no. of items for which we need to overwrite Item Group. Following are the steps to go about overwriting Item Groups for existing Items. #Step 1: Download Template Template Used for overwriting data will be same as one used for importing new items. Hence, you should first download template from. `Setup > Data > Import/Export Data' Since items to be over-written will be already available in the system, while downloading template, click on "Download with data" to get all the existing items in the template. <img alt="Download Template" class="screenshot" src="{{docs_base_url}}/assets/img/articles/overwrite-1.gif"> #Step 2: Prepare Data In the template, we can only keep rows of the items to be overwritten and delete the rest. Enter new value in the Item Group column for an item. Since Item Group is a master in itself, ensure Item Group entered in the spreadsheet file is already added in the Item Group master. <img alt="Update Values" class="screenshot" src="{{docs_base_url}}/assets/img/articles/overwrite-2.png"> Since we are overwriting only Item Group, only following columns will be mandatory. 1. Column A (since it has main values of template) 1. Name (Column B) 1. Item Group Columns of other field which won't have any impact can be removed, even if they are mandatory. This is applicable only for overwriting, and not when importing new records. #Step 3: Browse Template After updating Item Groups in spreadheet, come back to Data Import Tool in Revalue. Browse and select the File/template which has data to be overwritten. <img alt="Browse template" class="screenshot" src="{{docs_base_url}}/assets/img/articles/overwrite-3.gif"> #Step 4: Upload On clicking Import, Item Group will be over-written. <img alt="Upload" class="screenshot" src="{{docs_base_url}}/assets/img/articles/overwrite-4.png"> If validation of values fails, then it will indicate row no. of spreadsheet for which validation failed and needs correction. In that case, you should corrected value in that row of spreadsheet, and then import same file again. If validation fails even for one row, none of the records are imported/overwritten. <!-- markdown -->
package mhst.dreamteam.IcingaClient.Controller; import android.util.Log; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.<API key>; import java.net.URL; import java.net.<API key>; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import mhst.dreamteam.IcingaClient.GlobalConst; /** * Network controller<br /> * Uses to control network communication such as send request to server and get response data, etc. * * @author MinhNN */ public class NetController { /** * Uses to send request to a specific server via POST or GET method. * * @param sMethod "POST" - using POST method or "GET" - using GET method * @param sURL Target URL to send request * @param sParam (POST method only) data to send to server * @return a hashmap of response data<br /> * "Code" - response code<br /> * "Data" - data response from server (eg. json)<br /> * "Error" - any error detected while communicating with server */ public static Map<String, Object> sendRequest(String sMethod, String sURL, String sParam, Map<String, String> mProperty) { HttpURLConnection connection = null; Map<String, Object> result = new HashMap<String, Object>(); // Map data response from server try { // Create new URL URL HttpUrl = new URL(sURL); // Open connection for that URL connection = (HttpURLConnection) HttpUrl.openConnection(); // Set properties for this connection connection.setRequestProperty("Content-type", "application/<API key>; charset=UTF-8"); // if mProperty != null, set list of property in mProperty if (mProperty != null) { String[] keyList = mProperty.keySet().toArray(new String[mProperty.size()]); // List of property name for (String keyName : keyList) { connection.setRequestProperty(keyName, mProperty.get(keyName)); } } connection.setDoInput(true); // Enable send request body (POST Method if true; otherwise, GET Method) connection.setDoOutput(sMethod.equalsIgnoreCase("POST")); if (sMethod.equalsIgnoreCase("POST")) { // Send request DataOutputStream post = new DataOutputStream(connection.getOutputStream()); post.writeBytes(sParam); post.flush(); post.close(); } // Get response int sttCode = connection.getResponseCode(); // Get status code result.put("Code", sttCode); Log.i("NetController", "Response code = " + sttCode); // Get headers Map<String, Object> headers = new HashMap<String, Object>(); String sHeader; int i = 1; while ((sHeader = connection.getHeaderFieldKey(i)) != null) { if (headers.containsKey(sHeader)) { ArrayList<String> listValue = new ArrayList<String>(); listValue.add((String) headers.get(sHeader)); listValue.add(connection.getHeaderField(i)); headers.put(sHeader, listValue); } else { headers.put(sHeader, connection.getHeaderField(i)); } i++; } result.put("Headers", headers); // Get response data if (sttCode != 200) { // if status code != HTTP 200 OK, read response data from error stream BufferedReader errorReader = new BufferedReader(new InputStreamReader(connection.getErrorStream())); String sErrorBuffer; StringBuilder sError = new StringBuilder(); while ((sErrorBuffer = errorReader.readLine()) != null) { sError.append(sErrorBuffer); sError.append("\r\n"); } errorReader.close(); // Put data response message to map Log.e("NetController", sError.toString()); result.put("Data", sError.toString()); } else { // if status code is HTTP 200 OK, read data response from input stream BufferedReader responseReader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String sBuffer; StringBuilder sResponse = new StringBuilder(); while ((sBuffer = responseReader.readLine()) != null) { sResponse.append(sBuffer); sResponse.append("\r\n"); } responseReader.close(); // Put data response message to map Log.i("NetController", sResponse.toString()); result.put("Data", sResponse.toString()); } } catch (<API key> e) { e.printStackTrace(); result.put("Error", GlobalConst.ERROR_UNKNOWN_HOST); } catch (<API key> e) { e.printStackTrace(); result.put("Error", GlobalConst.ERROR_UNKNOWN_ERROR); } catch (IOException e) { e.printStackTrace(); result.put("Error", GlobalConst.<API key>); } finally { if (connection != null) connection.disconnect(); } return result; } }
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class <API key> extends Migration { /** * Run the migrations. * * @return void */ public function up() { if (!Schema::hasColumn('sessions', 'user_id')) { Schema::table('sessions', function (Blueprint $table) { $table->integer('user_id')->unsigned(); }); } } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('sessions', function (Blueprint $table) { $table->dropColumn('user_id'); }); } }
/*.footable { border-collapse: separate; border-spacing: 0; width: 100%; border: solid #ccc 1px; -moz-border-radius: 6px; -<API key>: 6px; border-radius: 6px; font-family: 'trebuchet MS' , 'Lucida sans' , Arial; font-size: 14px; color: #444; }*/ .footable.breakpoint > tbody > tr > td.expand { background: url('img/plus.png') no-repeat 5px center; padding-left: 40px; } .footable.breakpoint > tbody > tr.<API key> > td.expand { background: url('img/minus.png') no-repeat 5px center; } /* .footable.breakpoint > tbody > tr.footable-row-detail { background: #eee; } .footable > tbody > tr:hover { background: #fbf8e9; } .footable.breakpoint > tbody > tr:hover:not(.footable-row-detail) { cursor: pointer; } .footable > tbody > tr > td, .footable > thead > tr > th { border-left: 1px solid #ccc; border-top: 1px solid #ccc; padding: 10px; text-align: left; } .footable > thead > tr > th, .footable > thead > tr > td { background-color: #dce9f9; background-image: -webkit-gradient(linear, left top, left bottom, from(#ebf3fc), to(#dce9f9)); background-image: -<API key>(top, #ebf3fc, #dce9f9); background-image: -moz-linear-gradient(top, #ebf3fc, #dce9f9); background-image: -ms-linear-gradient(top, #ebf3fc, #dce9f9); background-image: -o-linear-gradient(top, #ebf3fc, #dce9f9); background-image: linear-gradient(to bottom, #ebf3fc, #dce9f9); -webkit-box-shadow: 0 1px 0 rgba(255,255,255,.8) inset; -moz-box-shadow: 0 1px 0 rgba(255,255,255,.8) inset; box-shadow: 0 1px 0 rgba(255,255,255,.8) inset; border-top: none; text-shadow: 0 1px 0 rgba(255,255,255,.5); } .footable > thead > tr:first-child > th.<API key>, .footable > thead > tr:first-child > td.<API key> { -moz-border-radius: 6px 0 0 0; -<API key>: 6px 0 0 0; border-radius: 6px 0 0 0; } .footable > thead > tr:first-child > th.<API key>, .footable > thead > tr:first-child > td.<API key> { -moz-border-radius: 0 6px 0 0; -<API key>: 0 6px 0 0; border-radius: 0 6px 0 0; } .footable > thead > tr:first-child > th.<API key>.<API key>, .footable > thead > tr:first-child > td.<API key>.<API key> { -moz-border-radius: 6px 6px 0 0; -<API key>: 6px 6px 0 0; border-radius: 6px 6px 0 0; } .footable > tbody > tr:last-child > td.<API key> { -moz-border-radius: 0 0 0 6px; -<API key>: 0 0 0 6px; border-radius: 0 0 0 6px; } .footable > tbody > tr:last-child > td.<API key> { -moz-border-radius: 0 0 6px 0; -<API key>: 0 0 6px 0; border-radius: 0 0 6px 0; } .footable > tbody > tr:last-child > td.<API key>.<API key> { -moz-border-radius: 0 0 6px 6px; -<API key>: 0 0 6px 6px; border-radius: 0 0 6px 6px; } .footable > thead > tr > th.<API key>, .footable > thead > tr > td.<API key>, .footable > tbody > tr > td.<API key> { border-left: none; } .footable > tbody img { vertical-align:middle; } .footable > tfoot > tr > th, .footable > tfoot > tr > td { background-color: #dce9f9; background-image: -webkit-gradient(linear, left top, left bottom, from(#ebf3fc), to(#dce9f9)); background-image: -<API key>(top, #ebf3fc, #dce9f9); background-image: -moz-linear-gradient(top, #ebf3fc, #dce9f9); background-image: -ms-linear-gradient(top, #ebf3fc, #dce9f9); background-image: -o-linear-gradient(top, #ebf3fc, #dce9f9); background-image: linear-gradient(to bottom, #ebf3fc, #dce9f9); -webkit-box-shadow: 0 1px 0 rgba(255,255,255,.8) inset; -moz-box-shadow: 0 1px 0 rgba(255,255,255,.8) inset; box-shadow: 0 1px 0 rgba(255,255,255,.8) inset; border-top: 1px solid #ccc; text-shadow: 0 1px 0 rgba(255,255,255,.5); padding: 10px; }*/
class CreateMonths < ActiveRecord::Migration def change create_table :months do |t| t.integer :year t.string :month t.timestamps end add_index(:months, :month, :unique => true) end end
<?php class <API key> extends <API key> { public function __construct() { parent::__construct(); $this->setId('imageGrid'); $this->setDefaultSort('image_id'); $this->setDefaultDir('ASC'); $this-><API key>(true); } protected function _prepareCollection() { $collection = Mage::getModel('blog/userimages')->getCollection(); $this->setCollection($collection); return parent::_prepareCollection(); } protected function _prepareColumns() { $this->addColumn('image_id', array( 'header' => Mage::helper('sns')->__('ID'), 'align' =>'right', 'width' => '50px', 'index' => 'image_id', )); $this->addColumn('title', array( 'header' => Mage::helper('sns')->__('Title'), 'align' =>'left', 'index' => 'title', )); $this->addColumn('product_id', array( 'header' => Mage::helper('sns')->__('product_id'), 'align' =>'left', 'index' => 'product_id', )); /* $this->addColumn('filename', array( 'header' => Mage::helper('sns')->__('filename'), 'align' =>'left', 'index' => 'filename', )); */ $this->addColumn('sort_order', array( 'header' => Mage::helper('sns')->__('sort_order'), 'align' =>'left', 'index' => 'sort_order', )); $this->addColumn('data1', array( 'header' => Mage::helper('sns')->__('data1'), 'align' =>'left', 'index' => 'data1', )); $this->addColumn('data2', array( 'header' => Mage::helper('sns')->__('data2'), 'align' =>'left', 'index' => 'data2', )); $this->addColumn('data3', array( 'header' => Mage::helper('sns')->__('data3'), 'align' =>'left', 'index' => 'data3', )); $this->addColumn('data4', array( 'header' => Mage::helper('sns')->__('data4'), 'align' =>'left', 'index' => 'data4', )); $this->addColumn('description', array( 'header' => Mage::helper('sns')->__('description'), 'align' =>'left', 'index' => 'description', )); $this->addColumn('data5', array( 'header' => Mage::helper('customer')->__(''), 'width' => '70', 'align' => 'left', 'renderer' => '<API key>', 'type'=>'image', 'index' => 'data5' )); /* $this->addColumn('content', array( 'header' => Mage::helper('sns')->__('Item Content'), 'width' => '150px', 'index' => 'content', )); */ $this->addColumn('status', array( 'header' => Mage::helper('sns')->__('Status'), 'align' => 'left', 'width' => '80px', 'index' => 'status', 'type' => 'options', 'options' => Mage::getSingleton('sns/status')->getOptionArray() )); $this->addColumn('action', array( 'header' => Mage::helper('sns')->__('Action'), 'width' => '100', 'type' => 'action', 'getter' => 'getImageId', 'actions' => array( array( 'caption' => Mage::helper('sns')->__('Edit'), 'url' => array('base'=> '*/*/edit'), 'field' => 'id' ) ), 'filter' => false, 'sortable' => false, 'index' => 'stores', 'is_system' => true, )); $this->addExportType('*/*/exportCsv', Mage::helper('sns')->__('CSV')); $this->addExportType('*/*/exportXml', Mage::helper('sns')->__('XML')); return parent::_prepareColumns(); } public function getRowUrl($row) { return $this->getUrl('*/*/edit', array('id' => $row->getImageId())); } }
package es.javocsoft.android.lib.toolbox.drive.callback; import android.content.Context; import com.google.android.gms.drive.DriveContents; /** * Base callback class to use when opening a file in Drive. * * @author JavocSoft 2015 * @version 1.0 * */ public abstract class <API key> extends Thread implements Runnable { protected DriveContents contents = null; protected int errorCode; protected String errorMessage; protected String errorDetails; protected Context context = null; public <API key>(Context context) { this.context = context; } @Override public void run() { doWork(); } public abstract void doWork(); public void setDriveContents(DriveContents contents) { this.contents = contents; } public void setErrorCode(int errorCode) { this.errorCode = errorCode; } public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; } public void setErrorDetails(String errorDetails) { this.errorDetails = errorDetails; } }
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # This file is part of qutebrowser. # qutebrowser is free software: you can redistribute it and/or modify # (at your option) any later version. # qutebrowser is distributed in the hope that it will be useful, # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the import pytest from PyQt5.QtCore import QUrl from qutebrowser.misc import httpclient, pastebin @pytest.fixture def pbclient(stubs): http_stub = stubs.HTTPPostStub() client = pastebin.PastebinClient(http_stub) return client def test_constructor(qapp): http_client = httpclient.HTTPClient() pastebin.PastebinClient(http_client) @pytest.mark.parametrize('data', [ { "name": "XYZ", "title": "hello world", "text": "xyz. 123 \n 172ANB", "reply": "abc", "apikey": "ihatespam", }, { "name": "the name", "title": "the title", "text": "some Text", "reply": "some parent", "apikey": "ihatespam", } ]) def <API key>(data, pbclient): http_stub = pbclient._client pbclient.paste(data["name"], data["title"], data["text"], data["reply"]) assert http_stub.data == data assert http_stub.url == QUrl('https://crashes.qutebrowser.org/api/create') @pytest.mark.parametrize('data', [ { "name": "XYZ", "title": "hello world", "text": "xyz. 123 \n 172ANB", "apikey": "ihatespam", }, { "name": "the name", "title": "the title", "text": "some Text", "apikey": "ihatespam", } ]) def <API key>(data, pbclient): http_stub = pbclient._client pbclient.paste(data["name"], data["title"], data["text"]) assert pbclient._client.data == data assert http_stub.url == QUrl('https://crashes.qutebrowser.org/api/create') def test_paste_private(pbclient): data = { "name": "the name", "title": "the title", "text": "some Text", "apikey": "ihatespam", "private": "1", } http_stub = pbclient._client pbclient.paste(data["name"], data["title"], data["text"], private=True) assert pbclient._client.data == data assert http_stub.url == QUrl('https://crashes.qutebrowser.org/api/create') @pytest.mark.parametrize('http', [ "http://paste.the-compiler.org/view/ges83nt3", "http://paste.the-compiler.org/view/3gjnwg4" ]) def <API key>(http, pbclient, qtbot): with qtbot.assertNotEmitted(pbclient.error): with qtbot.waitSignal(pbclient.success): pbclient._client.success.emit(http) @pytest.mark.parametrize('http', [ "http invalid", "http:/invalid.org" "http//invalid.com" ]) def <API key>(http, pbclient, qtbot): with qtbot.assertNotEmitted(pbclient.success): with qtbot.waitSignal(pbclient.error): pbclient._client.success.emit(http) def test_client_error(pbclient, qtbot): with qtbot.assertNotEmitted(pbclient.success): with qtbot.waitSignal(pbclient.error): pbclient._client.error.emit("msg")
namespace FOG { partial class FrmSetup { <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() { System.ComponentModel.<API key> resources = new System.ComponentModel.<API key>(typeof(FrmSetup)); this.pnlTop = new System.Windows.Forms.Panel(); this.pbTitle = new System.Windows.Forms.PictureBox(); this.pnlIP = new System.Windows.Forms.Panel(); this.pnlServices = new System.Windows.Forms.FlowLayoutPanel(); this.btnSave = new System.Windows.Forms.Button(); this.lblSubServices = new System.Windows.Forms.Label(); this.txtIP = new System.Windows.Forms.TextBox(); this.lblIPMessage = new System.Windows.Forms.Label(); this.pnlDone = new System.Windows.Forms.Panel(); this.btnDone = new System.Windows.Forms.Button(); this.lblDone = new System.Windows.Forms.Label(); this.pnlTop.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pbTitle)).BeginInit(); this.pnlIP.SuspendLayout(); this.pnlDone.SuspendLayout(); this.SuspendLayout(); // pnlTop this.pnlTop.BackColor = System.Drawing.Color.White; this.pnlTop.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.pnlTop.Controls.Add(this.pbTitle); this.pnlTop.Dock = System.Windows.Forms.DockStyle.Top; this.pnlTop.Location = new System.Drawing.Point(0, 0); this.pnlTop.Name = "pnlTop"; this.pnlTop.Size = new System.Drawing.Size(674, 87); this.pnlTop.TabIndex = 0; // pbTitle this.pbTitle.Image = ((System.Drawing.Image)(resources.GetObject("pbTitle.Image"))); this.pbTitle.Location = new System.Drawing.Point(367, 3); this.pbTitle.Name = "pbTitle"; this.pbTitle.Size = new System.Drawing.Size(304, 81); this.pbTitle.TabIndex = 0; this.pbTitle.TabStop = false; // pnlIP this.pnlIP.Controls.Add(this.pnlServices); this.pnlIP.Controls.Add(this.btnSave); this.pnlIP.Controls.Add(this.lblSubServices); this.pnlIP.Controls.Add(this.txtIP); this.pnlIP.Controls.Add(this.lblIPMessage); this.pnlIP.Location = new System.Drawing.Point(0, 87); this.pnlIP.Name = "pnlIP"; this.pnlIP.Size = new System.Drawing.Size(628, 381); this.pnlIP.TabIndex = 1; // pnlServices this.pnlServices.AutoScroll = true; this.pnlServices.BackColor = System.Drawing.Color.Transparent; this.pnlServices.Location = new System.Drawing.Point(68, 107); this.pnlServices.Name = "pnlServices"; this.pnlServices.Size = new System.Drawing.Size(592, 220); this.pnlServices.TabIndex = 5; // btnSave this.btnSave.Location = new System.Drawing.Point(552, 333); this.btnSave.Name = "btnSave"; this.btnSave.Size = new System.Drawing.Size(109, 37); this.btnSave.TabIndex = 4; this.btnSave.Text = "Save Changes"; this.btnSave.<API key> = true; this.btnSave.Click += new System.EventHandler(this.btnSave_Click); // lblSubServices this.lblSubServices.Location = new System.Drawing.Point(15, 79); this.lblSubServices.Name = "lblSubServices"; this.lblSubServices.Size = new System.Drawing.Size(389, 25); this.lblSubServices.TabIndex = 2; this.lblSubServices.Text = "What sub services would you like to run on this client?"; // txtIP this.txtIP.Location = new System.Drawing.Point(72, 43); this.txtIP.Name = "txtIP"; this.txtIP.Size = new System.Drawing.Size(167, 22); this.txtIP.TabIndex = 1; // lblIPMessage this.lblIPMessage.Location = new System.Drawing.Point(15, 15); this.lblIPMessage.Name = "lblIPMessage"; this.lblIPMessage.Size = new System.Drawing.Size(647, 25); this.lblIPMessage.TabIndex = 0; this.lblIPMessage.Text = "What is the IP address or host name of the FOG Web Server? (Blank for default \"fo" + "gserver\")"; // pnlDone this.pnlDone.Controls.Add(this.btnDone); this.pnlDone.Controls.Add(this.lblDone); this.pnlDone.Location = new System.Drawing.Point(18, 87); this.pnlDone.Name = "pnlDone"; this.pnlDone.Size = new System.Drawing.Size(654, 381); this.pnlDone.TabIndex = 2; this.pnlDone.Visible = false; // btnDone this.btnDone.Location = new System.Drawing.Point(535, 333); this.btnDone.Name = "btnDone"; this.btnDone.Size = new System.Drawing.Size(109, 37); this.btnDone.TabIndex = 5; this.btnDone.Text = "Done"; this.btnDone.<API key> = true; this.btnDone.Click += new System.EventHandler(this.btnDone_Click); // lblDone this.lblDone.BackColor = System.Drawing.Color.Transparent; this.lblDone.Location = new System.Drawing.Point(21, 22); this.lblDone.Name = "lblDone"; this.lblDone.Size = new System.Drawing.Size(610, 82); this.lblDone.TabIndex = 0; this.lblDone.Text = "The FOG Service has been configured, in order for the service modules to load cor" + "rectly, you MUST restart this computer. "; // FrmSetup this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 16F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(674, 468); this.Controls.Add(this.pnlDone); this.Controls.Add(this.pnlIP); this.Controls.Add(this.pnlTop); this.DoubleBuffered = true; this.Font = new System.Drawing.Font("Arial", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); this.MaximizeBox = false; this.Name = "FrmSetup"; this.ShowIcon = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "FOG Service :: Configuration Tool"; this.TopMost = true; this.Load += new System.EventHandler(this.FrmSetup_Load); this.pnlTop.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.pbTitle)).EndInit(); this.pnlIP.ResumeLayout(false); this.pnlIP.PerformLayout(); this.pnlDone.ResumeLayout(false); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Panel pnlTop; private System.Windows.Forms.PictureBox pbTitle; private System.Windows.Forms.Panel pnlIP; private System.Windows.Forms.TextBox txtIP; private System.Windows.Forms.Label lblIPMessage; private System.Windows.Forms.Label lblSubServices; private System.Windows.Forms.Button btnSave; private System.Windows.Forms.FlowLayoutPanel pnlServices; private System.Windows.Forms.Panel pnlDone; private System.Windows.Forms.Label lblDone; private System.Windows.Forms.Button btnDone; } }
/*global defineSuite*/ defineSuite([ 'Core/defined' ], function( defined) { "use strict"; /*global jasmine,describe,xdescribe,it,xit,expect,beforeEach,afterEach,beforeAll,afterAll,spyOn*/ var obj = 42; var obj2; it('works for defined object', function() { expect(defined(obj)).toEqual(true); }); it('works for undefined object', function() { expect(defined(obj2)).toEqual(false); }); });
# Memcached Cloud Node.js Sample A Node.js sample, running on Express framework, demonstrating how [Memcached](http://memcached.org/) can be used at Heroku.<br /> SET, GET and DELETE a key, and get your bucket's STATS. The app is currently running at: [<API key>.herokuapp.com](http: ## Deploy to Heroku Instantly deploy it to Heroku: [![Deploy](https:
#ifndef DIALOG_H #define DIALOG_H #include <QDialog> #include <QFileDialog> namespace Ui { class Dialog; } class Dialog : public QDialog { Q_OBJECT public: explicit Dialog(QWidget *parent = 0); ~Dialog(); void setPassPath(QString); void setGitPath(QString); void setGpgPath(QString); void setStorePath(QString); void usePass(bool); void useClipboard(bool); void useAutoclear(bool); void setAutoclear(int); void hidePassword(bool); void hideContent(bool); QString getPassPath(); QString getGitPath(); QString getGpgPath(); QString getStorePath(); bool usePass(); bool useClipboard(); bool useAutoclear(); int getAutoclear(); bool hidePassword(); bool hideContent(); private slots: void <API key>(); void <API key>(); void <API key>(); void <API key>(); void <API key>(); void <API key>(); void <API key>(); void <API key>(); private: QScopedPointer<Ui::Dialog> ui; void setGroupBoxState(); QString selectExecutable(); QString selectFolder(); }; #endif // DIALOG_H
<?php namespace Magento\User\Controller\Adminhtml\Locks; /** * Locked users grid */ class Grid extends \Magento\User\Controller\Adminhtml\Locks { /** * Render AJAX-grid only * * @return void */ public function execute() { $this->_view->loadLayout(false); $this->_view->renderLayout(); } }
# -*- coding: utf-8 -*- from object_test import session import random import string import model test_page = model.Page() N = 5 test_page.title = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(N)) test_page.content = u'Test content' print(test_page.title) session.add(test_page) print("1 print(test_page.id) """ At this point the test_page object is known to SQLAlchemy, but not to the database. To send it to the database, a flush operation can be forced: """ session.flush() print("2 print (test_page.id) """ Commits - Commits the changes in db """ session.commit() """ Delete - To delete the test_page object from the database you would use: """ session.delete(test_page) session.flush() print("3 print(test_page.id) session.rollback() print("4 print(test_page.id) """ Query - Queries are performed with query objects that are created from the session. The simplest way to create and use a query object is like this: """ page_q = session.query(model.Page) for page in page_q: print(page.title) print("---- page_q.all()") print(page_q.all()) page = page_q.first() print(page.title) print(page_q[2:5]) print(page_q.get(1).title) #comment1 = model.Comment() #comment1.name= u'James' #comment1.email = u'james@example.com' #comment1.content = u'This page needs a bit more detail ;-)' #comment2 = model.Comment() #comment2.name = u'Mike' #comment2.email = u'mike@example.com' #page.comments.append(comment1) #page.comments.append(comment2) #session.commit()
<!DOCTYPE html> <html> <head> <script> var regExp = /......-......./; var string = '910209-2001211'; var output = string.replace(regExp, '+$&+'); alert(output); </script> </head> <body> </body> </html>
<?php class kolab_format_file extends kolab_format { public $CTYPE = 'application/vnd.kolab+xml'; protected $objclass = 'File'; protected $read_func = 'kolabformat::readKolabFile'; protected $write_func = 'kolabformat::writeKolabFile'; protected $sensitivity_map = array( 'public' => kolabformat::ClassPublic, 'private' => kolabformat::ClassPrivate, 'confidential' => kolabformat::ClassConfidential, ); /** * Set properties to the kolabformat object * * @param array Object data as hash array */ public function set(&$object) { // set common object properties parent::set($object); $this->obj->setClassification($this->sensitivity_map[$object['sensitivity']]); $this->obj->setCategories(self::array2vector($object['categories'])); if (isset($object['notes'])) { $this->obj->setNote($object['notes']); } // Add file attachment if (!empty($object['_attachments'])) { $cid = key($object['_attachments']); $attach_attr = $object['_attachments'][$cid]; $attach = new Attachment; $attach->setLabel((string)$attach_attr['name']); $attach->setUri('cid:' . $cid, $attach_attr['mimetype']); $this->obj->setFile($attach); // make sure size is set, so object saved in cache contains this info if (!isset($attach_attr['size'])) { $size = 0; if (!empty($attach_attr['content'])) { if (is_resource($attach_attr['content'])) { $stat = fstat($attach_attr['content']); $size = $stat ? $stat['size'] : 0; } else { $size = strlen($attach_attr['content']); } } else if (isset($attach_attr['path'])) { $size = @filesize($attach_attr['path']); } $object['_attachments'][$cid]['size'] = $size; } } // cache this data $this->data = $object; unset($this->data['_formatobj']); } /** * Check if object's data validity */ public function is_valid() { return !$this->formaterror && ($this->data || (is_object($this->obj) && $this->obj->isValid())); } /** * Convert the Configuration object into a hash array data structure * * @param array Additional data for merge * * @return array Config object data as hash array */ public function to_array($data = array()) { // return cached result if (!empty($this->data)) { return $this->data; } // read common object props into local data object $object = parent::to_array($data); $sensitivity_map = array_flip($this->sensitivity_map); // read object properties $object += array( 'sensitivity' => $sensitivity_map[$this->obj->classification()], 'categories' => self::vector2array($this->obj->categories()), 'notes' => $this->obj->note(), ); return $this->data = $object; } /** * Callback for kolab_storage_cache to get object specific tags to cache * * @return array List of tags to save in cache */ public function get_tags() { $tags = array(); foreach ((array)$this->data['categories'] as $cat) { $tags[] = rcube_utils::normalize_string($cat); } // Add file mimetype to tags if (!empty($this->data['_attachments'])) { reset($this->data['_attachments']); $key = key($this->data['_attachments']); $attachment = $this->data['_attachments'][$key]; if ($attachment['mimetype']) { $tags[] = $attachment['mimetype']; } } return $tags; } }
C$TEST LPSB C TO RUN AS A MAIN PROGRAM REMOVE NEXT LINE SUBROUTINE LPSB C*********************************************************************** C C EXAMPLE OF USE OF THE PORT PROGRAM BPCE C C*********************************************************************** INTEGER N, MU, IG, K, I, IWRITE, I1MACH, J REAL G(2,100), B(200) REAL X, COND, AINVNO, AINORM, ABS N=100 X=1.0 MU=2 IG=2 DO 50 K=1,3 C CONSTRUCT MATRIX DO 10 I=1,N G(1,I)=2.0 G(2,I)=-1.0 10 CONTINUE G(1,1)=1.0+X G(1,N)=1.0+X C GET ESTIMATE OF CONDITION NUMBER FROM BPCE CALL BPCE(N,MU,G,IG,COND) IWRITE=I1MACH(2) WRITE(IWRITE,11)X 11 FORMAT(/10H WHEN X IS,E14.6) WRITE(IWRITE,12)COND 12 FORMAT(25H CONDITION ESTIMATE IS ,E15.8) C SINCE CONDITION NUMBER IS NORM(A)*NORM(INVERSE(A)), C FIND THE NORM OF EACH COLUMN OF INVERSE(A). GENERATE C THE COLUMNS ONE AT A TIME AND REUSE SPACE AINVNO=0.0 DO 40 I=1,N C GENERATE ITH COLUMN OF IDENTITY MATRIX AS RIGHT HAND SIDE DO 20 J=1,N B(J)=0.0 20 CONTINUE B(I)=1.0 C SOLVE AX=B TO GET ITH COLUMN OF A(INVERSE) CALL BPFS(N,MU,G,IG,B,N,1) CALL BPBS(N,MU,G,IG,B,N,1) C FIND NORM OF COLUMN AINORM=0.0 DO 30 J=1,N AINORM=AINORM+ABS(B(J)) 30 CONTINUE IF(AINVNO.LT.AINORM)AINVNO=AINORM 40 CONTINUE COND=4.0*AINVNO WRITE(IWRITE,41)COND 41 FORMAT(25H TRUE CONDITION NUMBER IS,E15.8) X=X/100.0 50 CONTINUE STOP END
#include <QtTest/QtTest> #include <QDebug> #include <qcamera.h> #include <qcamerainfo.h> #include "mockcameraservice.h" #include "<API key>.h" QT_USE_NAMESPACE class tst_QCameraInfo: public QObject { Q_OBJECT public slots: void initTestCase(); void init(); void cleanup(); private slots: void constructor(); void defaultCamera(); void availableCameras(); void equality_operators(); private: <API key> *<API key>; MockCameraService *mockCameraService; <API key> *provider; }; void tst_QCameraInfo::initTestCase() { } void tst_QCameraInfo::init() { provider = new <API key>; <API key> = new <API key>; mockCameraService = new MockCameraService; provider->service = mockCameraService; <API key>::<API key>(provider); } void tst_QCameraInfo::cleanup() { delete provider; delete mockCameraService; delete <API key>; } void tst_QCameraInfo::constructor() { // Service doesn't implement <API key> // QCameraInfo should not be valid in this case provider->service = <API key>; { QCamera camera; QCameraInfo info(camera); QVERIFY(info.isNull()); QVERIFY(info.deviceName().isEmpty()); QVERIFY(info.description().isEmpty()); QCOMPARE(info.position(), QCamera::UnspecifiedPosition); QCOMPARE(info.orientation(), 0); } // Service implements <API key> provider->service = mockCameraService; { // default camera QCamera camera; QCameraInfo info(camera); QVERIFY(!info.isNull()); QCOMPARE(info.deviceName(), QStringLiteral("othercamera")); QCOMPARE(info.description(), QStringLiteral("othercamera desc")); QCOMPARE(info.position(), QCamera::UnspecifiedPosition); QCOMPARE(info.orientation(), 0); } QCamera camera("backcamera"); QCameraInfo info(camera); QVERIFY(!info.isNull()); QCOMPARE(info.deviceName(), QStringLiteral("backcamera")); QCOMPARE(info.description(), QStringLiteral("backcamera desc")); QCOMPARE(info.position(), QCamera::BackFace); QCOMPARE(info.orientation(), 90); QCameraInfo info2(info); QVERIFY(!info2.isNull()); QCOMPARE(info2.deviceName(), QStringLiteral("backcamera")); QCOMPARE(info2.description(), QStringLiteral("backcamera desc")); QCOMPARE(info2.position(), QCamera::BackFace); QCOMPARE(info2.orientation(), 90); } void tst_QCameraInfo::defaultCamera() { provider->service = mockCameraService; QCameraInfo info = QCameraInfo::defaultCamera(); QVERIFY(!info.isNull()); QCOMPARE(info.deviceName(), QStringLiteral("othercamera")); QCOMPARE(info.description(), QStringLiteral("othercamera desc")); QCOMPARE(info.position(), QCamera::UnspecifiedPosition); QCOMPARE(info.orientation(), 0); QCamera camera(info); QCOMPARE(QCameraInfo(camera), info); } void tst_QCameraInfo::availableCameras() { provider->service = mockCameraService; QList<QCameraInfo> cameras = QCameraInfo::availableCameras(); QCOMPARE(cameras.count(), 2); QCameraInfo info = cameras.at(0); QVERIFY(!info.isNull()); QCOMPARE(info.deviceName(), QStringLiteral("backcamera")); QCOMPARE(info.description(), QStringLiteral("backcamera desc")); QCOMPARE(info.position(), QCamera::BackFace); QCOMPARE(info.orientation(), 90); info = cameras.at(1); QVERIFY(!info.isNull()); QCOMPARE(info.deviceName(), QStringLiteral("othercamera")); QCOMPARE(info.description(), QStringLiteral("othercamera desc")); QCOMPARE(info.position(), QCamera::UnspecifiedPosition); QCOMPARE(info.orientation(), 0); cameras = QCameraInfo::availableCameras(QCamera::BackFace); QCOMPARE(cameras.count(), 1); info = cameras.at(0); QVERIFY(!info.isNull()); QCOMPARE(info.deviceName(), QStringLiteral("backcamera")); QCOMPARE(info.description(), QStringLiteral("backcamera desc")); QCOMPARE(info.position(), QCamera::BackFace); QCOMPARE(info.orientation(), 90); cameras = QCameraInfo::availableCameras(QCamera::FrontFace); QCOMPARE(cameras.count(), 0); } void tst_QCameraInfo::equality_operators() { provider->service = mockCameraService; QCameraInfo defaultCamera = QCameraInfo::defaultCamera(); QList<QCameraInfo> cameras = QCameraInfo::availableCameras(); QVERIFY(defaultCamera == cameras.at(1)); QVERIFY(defaultCamera != cameras.at(0)); QVERIFY(cameras.at(0) != cameras.at(1)); { QCamera camera(defaultCamera); QVERIFY(QCameraInfo(camera) == defaultCamera); QVERIFY(QCameraInfo(camera) == cameras.at(1)); } { QCamera camera(cameras.at(0)); QVERIFY(QCameraInfo(camera) == cameras.at(0)); } } QTEST_MAIN(tst_QCameraInfo) #include "tst_qcamerainfo.moc"