code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
/* * Created: 31.03.2012 * * Copyright (C) 2012 Victor Antonovich (v.antonovich@gmail.com) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package su.comp.bk.arch; import android.content.res.Resources; import android.os.Bundle; import org.apache.commons.lang.ArrayUtils; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.ShortBuffer; import java.util.ArrayList; import java.util.List; import java.util.zip.Deflater; import java.util.zip.DeflaterOutputStream; import java.util.zip.InflaterInputStream; import su.comp.bk.R; import su.comp.bk.arch.cpu.Cpu; import su.comp.bk.arch.io.Device; import su.comp.bk.arch.io.KeyboardController; import su.comp.bk.arch.io.PeripheralPort; import su.comp.bk.arch.io.Sel1RegisterSystemBits; import su.comp.bk.arch.io.SystemTimer; import su.comp.bk.arch.io.Timer; import su.comp.bk.arch.io.VideoController; import su.comp.bk.arch.io.VideoControllerManager; import su.comp.bk.arch.io.audio.AudioOutput; import su.comp.bk.arch.io.audio.Ay8910; import su.comp.bk.arch.io.audio.Covox; import su.comp.bk.arch.io.audio.Speaker; import su.comp.bk.arch.io.disk.FloppyController; import su.comp.bk.arch.io.disk.IdeController; import su.comp.bk.arch.io.disk.SmkIdeController; import su.comp.bk.arch.io.memory.Bk11MemoryManager; import su.comp.bk.arch.io.memory.SmkMemoryManager; import su.comp.bk.arch.memory.BankedMemory; import su.comp.bk.arch.memory.Memory; import su.comp.bk.arch.memory.RandomAccessMemory; import su.comp.bk.arch.memory.RandomAccessMemory.Type; import su.comp.bk.arch.memory.ReadOnlyMemory; import su.comp.bk.arch.memory.SegmentedMemory; import su.comp.bk.arch.memory.SelectableMemory; import su.comp.bk.util.FileUtils; import timber.log.Timber; /** * BK001x computer implementation. */ public class Computer implements Runnable { // State save/restore: Computer system uptime (in nanoseconds) private static final String STATE_SYSTEM_UPTIME = Computer.class.getName() + "#sys_uptime"; // State save/restore: Computer RAM data private static final String STATE_RAM_DATA = Computer.class.getName() + "#ram_data"; /** Bus error constant */ public final static int BUS_ERROR = -1; // Computer configuration private Configuration configuration; // Memory table mapped by 4KB blocks private final List<?>[] memoryTable = new List[16]; // List of created RandomAccessMemory instances private final List<RandomAccessMemory> randomAccessMemoryList = new ArrayList<>(); // CPU implementation reference private final Cpu cpu; // Video controller reference private VideoController videoController; // Keyboard controller reference private KeyboardController keyboardController; // Peripheral port reference private PeripheralPort peripheralPort; // Audio outputs list private List<AudioOutput> audioOutputs = new ArrayList<>(); // Floppy controller reference (<code>null</code> if no floppy controller attached) private FloppyController floppyController; /** BK0011 first banked memory block address */ public static final int BK0011_BANKED_MEMORY_0_ADDRESS = 040000; /** BK0011 second banked memory block address */ public static final int BK0011_BANKED_MEMORY_1_ADDRESS = 0100000; /** I/O registers space min start address */ public final static int IO_REGISTERS_MIN_ADDRESS = 0177000; // I/O devices list private final List<Device> deviceList = new ArrayList<>(); // I/O registers space addresses mapped to devices private final List<?>[] deviceTable = new List[2048]; private boolean isRunning = false; private boolean isPaused = true; private Thread clockThread; /** Amount of nanoseconds in one microsecond */ public static final long NANOSECS_IN_USEC = 1000L; /** Amount of nanoseconds in one millisecond */ public static final long NANOSECS_IN_MSEC = 1000000L; /** BK0010 clock frequency (in kHz) */ public final static int CLOCK_FREQUENCY_BK0010 = 3000; /** BK0011 clock frequency (in kHz) */ public final static int CLOCK_FREQUENCY_BK0011 = 4000; // Computer clock frequency (in kHz) private int clockFrequency; /** Uptime sync threshold (in nanoseconds) */ private static final long UPTIME_SYNC_THRESHOLD = (10L * NANOSECS_IN_MSEC); // Last computer system uptime update timestamp (unix timestamp, in nanoseconds) private long systemUptimeUpdateTimestamp; // Computer system uptime since start (in nanoseconds) private long systemUptime; /** Uptime sync check interval (in nanoseconds) */ private static final long UPTIME_SYNC_CHECK_INTERVAL = (1L * NANOSECS_IN_MSEC); // Computer system uptime sync check interval (in CPU ticks) private long systemUptimeSyncCheckIntervalTicks; // Last computer system uptime sync check timestamp (in CPU ticks) private long systemUptimeSyncCheckTimestampTicks; private final List<UptimeListener> uptimeListeners = new ArrayList<>(); // IDE controller reference (<code>null</code> if no IDE controller present) private IdeController ideController; /** * Computer uptime updates listener. */ public interface UptimeListener { void uptimeUpdated(long uptime); } public enum Configuration { /** BK0010 - monitor only */ BK_0010_MONITOR, /** BK0010 - monitor and Basic */ BK_0010_BASIC, /** BK0010 - monitor, Focal and tests */ BK_0010_MSTD, /** BK0010 with connected floppy drive controller (КНГМД) */ BK_0010_KNGMD(true), /** BK0011M - MSTD block attached */ BK_0011M_MSTD(false, true), /** BK0011M with connected floppy drive controller (КНГМД) */ BK_0011M_KNGMD(true, true), /** BK0011M with connected SMK512 controller */ BK_0011M_SMK512(true, true); private final boolean isFloppyControllerPresent; private final boolean isMemoryManagerPresent; Configuration() { this(false, false); } Configuration(boolean isFloppyControllerPresent) { this(isFloppyControllerPresent, false); } Configuration(boolean isFloppyControllerPresent, boolean isMemoryManagerPresent) { this.isFloppyControllerPresent = isFloppyControllerPresent; this.isMemoryManagerPresent = isMemoryManagerPresent; } /** * Check is {@link FloppyController} present in this configuration. * @return <code>true</code> if floppy controller present, <code>false</code> otherwise */ public boolean isFloppyControllerPresent() { return isFloppyControllerPresent; } /** * Check is BK-0011 {@link Bk11MemoryManager} present in configuration. * @return <code>true</code> if memory manager present, <code>false</code> otherwise */ public boolean isMemoryManagerPresent() { return isMemoryManagerPresent; } } public static class MemoryRange { private final int startAddress; private final Memory memory; private final int endAddress; public MemoryRange(int startAddress, Memory memory) { this.startAddress = startAddress; this.memory = memory; this.endAddress = startAddress + (memory.getSize() << 1) - 1; } public int getStartAddress() { return startAddress; } public Memory getMemory() { return memory; } public boolean isRelatedAddress(int address) { return (address >= startAddress) && (address <= endAddress); } } public Computer() { this.cpu = new Cpu(this); } /** * Configure this computer. * @param resources Android resources object reference * @param config computer configuration as {@link Configuration} value * @throws Exception in case of error while configuring */ public void configure(Resources resources, Configuration config) throws Exception { setConfiguration(config); // Apply shared configuration addDevice(new Sel1RegisterSystemBits(!config.isMemoryManagerPresent() ? 0100000 : 0140000)); keyboardController = new KeyboardController(this); addDevice(keyboardController); peripheralPort = new PeripheralPort(); addDevice(peripheralPort); addDevice(new Timer()); // Apply computer specific configuration if (!config.isMemoryManagerPresent()) { // BK-0010 configurations setClockFrequency(CLOCK_FREQUENCY_BK0010); // Set RAM configuration RandomAccessMemory workMemory = createRandomAccessMemory("WorkMemory", 020000, Type.K565RU6); addMemory(0, workMemory); RandomAccessMemory videoMemory = createRandomAccessMemory("VideoMemory", 020000, Type.K565RU6); addMemory(040000, videoMemory); // Add video controller videoController = new VideoController(videoMemory); addDevice(videoController); // Set ROM configuration addReadOnlyMemory(resources, 0100000, R.raw.monit10, "Monitor10"); switch (config) { case BK_0010_BASIC: addReadOnlyMemory(resources, 0120000, R.raw.basic10_1, "Basic10:1"); addReadOnlyMemory(resources, 0140000, R.raw.basic10_2, "Basic10:2"); addReadOnlyMemory(resources, 0160000, R.raw.basic10_3, "Basic10:3"); break; case BK_0010_MSTD: addReadOnlyMemory(resources, 0120000, R.raw.focal, "Focal"); addReadOnlyMemory(resources, 0160000, R.raw.tests, "MSTD10"); break; case BK_0010_KNGMD: addMemory(0120000, createRandomAccessMemory("ExtMemory", 020000, Type.K537RU10)); addReadOnlyMemory(resources, 0160000, R.raw.disk_327, "FloppyBios"); floppyController = new FloppyController(this); addDevice(floppyController); break; default: break; } } else { // BK-0011 configurations setClockFrequency(CLOCK_FREQUENCY_BK0011); // Set RAM configuration BankedMemory firstBankedMemory = new BankedMemory("BankedMemory0", 020000, Bk11MemoryManager.NUM_RAM_BANKS); BankedMemory secondBankedMemory = new BankedMemory("BankedMemory1", 020000, Bk11MemoryManager.NUM_RAM_BANKS + Bk11MemoryManager.NUM_ROM_BANKS); for (int memoryBankIndex = 0; memoryBankIndex < Bk11MemoryManager.NUM_RAM_BANKS; memoryBankIndex++) { Memory memoryBank = createRandomAccessMemory("MemoryBank" + memoryBankIndex, 020000, Type.K565RU5); firstBankedMemory.setBank(memoryBankIndex, memoryBank); secondBankedMemory.setBank(memoryBankIndex, memoryBank); } addMemory(0, firstBankedMemory.getBank(6)); // Fixed RAM page at address 0 addMemory(BK0011_BANKED_MEMORY_0_ADDRESS, firstBankedMemory); // First banked memory window at address 040000 SelectableMemory selectableSecondBankedMemory = new SelectableMemory( secondBankedMemory.getId(), secondBankedMemory, true); addMemory(BK0011_BANKED_MEMORY_1_ADDRESS, selectableSecondBankedMemory); // Second banked memory window at address 0100000 // Set ROM configuration secondBankedMemory.setBank(Bk11MemoryManager.NUM_RAM_BANKS, new ReadOnlyMemory( "Basic11M:0", loadReadOnlyMemoryData(resources, R.raw.basic11m_0))); secondBankedMemory.setBank(Bk11MemoryManager.NUM_RAM_BANKS + 1, new ReadOnlyMemory("Basic11M:1/ExtBOS11M", loadReadOnlyMemoryData(resources, R.raw.basic11m_1, R.raw.ext11m))); ReadOnlyMemory bosRom = new ReadOnlyMemory("BOS11M", loadReadOnlyMemoryData(resources, R.raw.bos11m)); SelectableMemory selectableBosRom = new SelectableMemory(bosRom.getId(), bosRom, true); addMemory( 0140000, selectableBosRom); switch (config) { case BK_0011M_MSTD: addReadOnlyMemory(resources, 0160000, R.raw.mstd11m, "MSTD11M"); break; case BK_0011M_KNGMD: addReadOnlyMemory(resources, 0160000, R.raw.disk_327, "FloppyBios"); floppyController = new FloppyController(this); addDevice(floppyController); break; case BK_0011M_SMK512: ReadOnlyMemory smkBiosRom = new ReadOnlyMemory("SmkBiosRom", loadReadOnlyMemoryData(resources, R.raw.disk_smk512_v205)); SelectableMemory selectableSmkBiosRom0 = new SelectableMemory( smkBiosRom.getId() + ":0", smkBiosRom, false); SelectableMemory selectableSmkBiosRom1 = new SelectableMemory( smkBiosRom.getId() + ":1", smkBiosRom, false); addMemory(SmkMemoryManager.BIOS_ROM_0_START_ADDRESS, selectableSmkBiosRom0); addMemory(SmkMemoryManager.BIOS_ROM_1_START_ADDRESS, selectableSmkBiosRom1); RandomAccessMemory smkRam = createRandomAccessMemory("SmkRam", SmkMemoryManager.MEMORY_TOTAL_SIZE, Type.K565RU5); List<SegmentedMemory> smkRamSegments = new ArrayList<>( SmkMemoryManager.NUM_MEMORY_SEGMENTS); for (int i = 0; i < SmkMemoryManager.NUM_MEMORY_SEGMENTS; i++) { SegmentedMemory smkRamSegment = new SegmentedMemory("SmkRamSegment" + i, smkRam, SmkMemoryManager.MEMORY_SEGMENT_SIZE); smkRamSegments.add(smkRamSegment); addMemory(SmkMemoryManager.MEMORY_START_ADDRESS + i * SmkMemoryManager.MEMORY_SEGMENT_SIZE * 2, smkRamSegment); } SmkMemoryManager smkMemoryManager = new SmkMemoryManager(smkRamSegments, selectableSmkBiosRom0, selectableSmkBiosRom1); smkMemoryManager.setSelectableBk11BosRom(selectableBosRom); smkMemoryManager.setSelectableBk11SecondBankedMemory(selectableSecondBankedMemory); addDevice(smkMemoryManager); floppyController = new FloppyController(this); addDevice(floppyController); SmkIdeController smkIdeController = new SmkIdeController(this); ideController = smkIdeController; addDevice(smkIdeController); break; default: break; } // Configure BK0011M memory manager addDevice(new Bk11MemoryManager(firstBankedMemory, secondBankedMemory)); // Add video controller with palette/screen manager BankedMemory videoMemory = new BankedMemory("VideoPagesMemory", 020000, 2); videoMemory.setBank(0, firstBankedMemory.getBank(1)); videoMemory.setBank(1, firstBankedMemory.getBank(7)); videoController = new VideoController(videoMemory); addDevice(videoController); addDevice(new VideoControllerManager(videoController, videoMemory)); // Add system timer SystemTimer systemTimer = new SystemTimer(this); addDevice(systemTimer); videoController.addFrameSyncListener(systemTimer); } // Notify video controller about computer time updates addUptimeListener(videoController); // Add audio outputs addAudioOutput(new Speaker(this, config.isMemoryManagerPresent())); addAudioOutput(new Covox(this)); addAudioOutput(new Ay8910(this)); } /** * Set computer configuration. * @param config computer configuration as {@link Configuration} value */ public void setConfiguration(Configuration config) { this.configuration = config; } /** * Get computer configuration. * @return computer configuration as {@link Configuration} value */ public Configuration getConfiguration() { return this.configuration; } /** * Create new {@link RandomAccessMemory} and add it to the RAM list for further saving/restoring. * @param memoryId RAM identifier * @param memorySize RAM size (in words) * @param memoryType RAM type * @return created {@link RandomAccessMemory} reference */ private RandomAccessMemory createRandomAccessMemory(String memoryId, int memorySize, Type memoryType) { RandomAccessMemory memory = new RandomAccessMemory(memoryId, memorySize, memoryType); addToRandomAccessMemoryList(memory); return memory; } private void addToRandomAccessMemoryList(RandomAccessMemory memory) { randomAccessMemoryList.add(memory); } private List<RandomAccessMemory> getRandomAccessMemoryList() { return randomAccessMemoryList; } /** * Save computer state. * @param outState {@link Bundle} to save state */ public void saveState(Bundle outState) { // Save computer configuration outState.putString(Configuration.class.getName(), getConfiguration().name()); // Save computer system uptime outState.putLong(STATE_SYSTEM_UPTIME, getSystemUptime()); // Save RAM data saveRandomAccessMemoryData(outState); // Save CPU state getCpu().saveState(outState); // Save device states for (Device device : deviceList) { device.saveState(outState); } } private void saveRandomAccessMemoryData(Bundle outState) { List<RandomAccessMemory> randomAccessMemoryList = getRandomAccessMemoryList(); // Calculate total RAM data size (in bytes) int totalDataSize = 0; for (RandomAccessMemory memory: randomAccessMemoryList) { totalDataSize += memory.getSize() * 2; } // Pack all RAM data into a single buffer ByteBuffer dataBuf = ByteBuffer.allocate(totalDataSize); ShortBuffer shortDataBuf = dataBuf.asShortBuffer(); for (RandomAccessMemory memory: randomAccessMemoryList) { shortDataBuf.put(memory.getData(), 0, memory.getSize()); } dataBuf.flip(); // Compress RAM data ByteArrayOutputStream baos = new ByteArrayOutputStream(); Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION); try (DeflaterOutputStream dos = new DeflaterOutputStream(baos, deflater)) { dos.write(dataBuf.array()); } catch (IOException e) { throw new IllegalStateException("Can't compress RAM data", e); } byte[] compressedData = baos.toByteArray(); outState.putByteArray(STATE_RAM_DATA, compressedData); Timber.d("Saved RAM data: original %dKB, compressed %dKB", totalDataSize / 1024, compressedData.length / 1024); } /** * Restore computer state. * @param inState {@link Bundle} to restore state * @throws Exception in case of error while state restoring */ public void restoreState(Bundle inState) throws Exception { // Restore computer system uptime setSystemUptime(inState.getLong(STATE_SYSTEM_UPTIME)); // Initialize CPU and devices cpu.initDevices(true); // Restore RAM data restoreRandomAccessMemoryData(inState); // Restore CPU state getCpu().restoreState(inState); // Restore device states for (Device device : deviceList) { device.restoreState(inState); } } private void restoreRandomAccessMemoryData(Bundle inState) { byte[] compressedData = inState.getByteArray(STATE_RAM_DATA); if (compressedData == null || compressedData.length == 0) { throw new IllegalArgumentException("No RAM data to restore"); } List<RandomAccessMemory> randomAccessMemoryList = getRandomAccessMemoryList(); // Calculate RAM memory data size (in bytes) int totalDataSize = 0; for (RandomAccessMemory memory: randomAccessMemoryList) { totalDataSize += memory.getSize() * 2; } // Decompress RAM data ByteArrayOutputStream baos = new ByteArrayOutputStream(totalDataSize); ByteArrayInputStream bais = new ByteArrayInputStream(compressedData); try (InflaterInputStream iis = new InflaterInputStream(bais)) { FileUtils.writeFully(iis, baos); } catch (IOException e) { throw new IllegalArgumentException("Can't decompress RAM data", e); } // Check decompressed data byte[] data = baos.toByteArray(); if (data.length != totalDataSize) { throw new IllegalArgumentException(String.format("Invalid decompressed RAM " + "data length: expected %d, got %d", totalDataSize, data.length)); } // Restore RAM data ByteBuffer dataBuf = ByteBuffer.wrap(data); ShortBuffer shortDataBuf = dataBuf.asShortBuffer(); for (RandomAccessMemory memory: randomAccessMemoryList) { short[] memoryData = new short[memory.getSize()]; shortDataBuf.get(memoryData); memory.putData(memoryData); } } public static Configuration getStoredConfiguration(Bundle inState) { return (inState != null) ? Configuration.valueOf(inState.getString( Configuration.class.getName())) : null; } /** * Get clock frequency (in kHz) * @return clock frequency */ public int getClockFrequency() { return clockFrequency; } /** * Set clock frequency (in kHz) * @param clockFrequency clock frequency to set */ public void setClockFrequency(int clockFrequency) { this.clockFrequency = clockFrequency; systemUptimeSyncCheckIntervalTicks = nanosToCpuTime(UPTIME_SYNC_CHECK_INTERVAL); } private void addReadOnlyMemory(Resources resources, int address, int romDataResId, String romId) throws IOException { byte[] romData = loadReadOnlyMemoryData(resources, romDataResId); addMemory(address, new ReadOnlyMemory(romId, romData)); } /** * Load ROM data from raw resources. * @param resources {@link Resources} reference * @param romDataResIds ROM raw resource IDs * @return loaded ROM data * @throws IOException in case of ROM data loading error */ private byte[] loadReadOnlyMemoryData(Resources resources, int... romDataResIds) throws IOException { byte[] romData = null; for (int romDataResId : romDataResIds) { romData = ArrayUtils.addAll(romData, loadRawResourceData(resources, romDataResId)); } return romData; } /** * Load data of raw resource. * @param resources {@link Resources} reference * @param resourceId raw resource ID * @return read raw resource data * @throws IOException in case of loading error */ private byte[] loadRawResourceData(Resources resources, int resourceId) throws IOException { InputStream resourceDataStream = resources.openRawResource(resourceId); byte[] resourceData = new byte[resourceDataStream.available()]; resourceDataStream.read(resourceData); return resourceData; } /** * Get {@link Cpu} reference. * @return this <code>Computer</code> CPU object reference */ public Cpu getCpu() { return cpu; } /** * Get {@link VideoController} reference. * @return video controller reference */ public VideoController getVideoController() { return videoController; } /** * Get {@link KeyboardController} reference. * @return keyboard controller reference */ public KeyboardController getKeyboardController() { return keyboardController; } /** * Get {@link PeripheralPort} reference. * @return peripheral port reference */ public PeripheralPort getPeripheralPort() { return peripheralPort; } /** * Get {@link FloppyController} reference. * @return floppy controller reference or <code>null</code> if floppy controller is not present */ public FloppyController getFloppyController() { return floppyController; } /** * Get {@link IdeController} reference. * @return IDE controller reference or <code>null</code> if IDE controller is not present */ public IdeController getIdeController() { return ideController; } /** * Get list of available {@link AudioOutput}s. * @return audio outputs list */ public List<AudioOutput> getAudioOutputs() { return audioOutputs; } /** * Add {@link AudioOutput} device. * @param audioOutput audio output device to add */ public void addAudioOutput(AudioOutput audioOutput) { audioOutputs.add(audioOutput); addDevice(audioOutput); } /** * Set computer system uptime (in nanoseconds). * @param systemUptime computer system uptime to set (in nanoseconds) */ public void setSystemUptime(long systemUptime) { this.systemUptime = systemUptime; } /** * Get computer system uptime (in nanoseconds). * @return computer system uptime (in nanoseconds) */ public long getSystemUptime() { return systemUptime; } /** * Get computer time (in nanoseconds). * @return current computer uptime */ public long getUptime() { return cpuTimeToNanos(cpu.getTime()); } /** * Get computer time (in CPU ticks). * @return current computer uptime */ public long getUptimeTicks() { return cpu.getTime(); } /** * Add computer uptime updates listener. * @param uptimeListener {@link UptimeListener} object reference to add */ public void addUptimeListener(UptimeListener uptimeListener) { uptimeListeners.add(uptimeListener); } private void notifyUptimeListeners() { long uptime = getUptime(); for (int i = 0; i < uptimeListeners.size(); i++) { UptimeListener uptimeListener = uptimeListeners.get(i); uptimeListener.uptimeUpdated(uptime); } } /** * Add memory (RAM/ROM) to address space. * @param address address to add memory * @param memory {@link Memory} to add */ public void addMemory(int address, Memory memory) { int memoryStartBlock = address >> 12; int memoryBlocksCount = memory.getSize() >> 11; // ((size << 1) >> 12) if ((memory.getSize() & 03777) != 0) { memoryBlocksCount++; } MemoryRange memoryRange = new MemoryRange(address, memory); for (int i = 0; i < memoryBlocksCount; i++) { int memoryBlockIdx = memoryStartBlock + i; @SuppressWarnings("unchecked") List<MemoryRange> memoryRanges = (List<MemoryRange>) memoryTable[memoryBlockIdx]; if (memoryRanges == null) { memoryRanges = new ArrayList<>(1); memoryTable[memoryBlockIdx] = memoryRanges; } memoryRanges.add(0, memoryRange); } } /** * Add I/O device to address space. * @param device {@link Device} to add */ public void addDevice(Device device) { deviceList.add(device); int[] deviceAddresses = device.getAddresses(); for (int deviceAddress : deviceAddresses) { int deviceTableIndex = (deviceAddress - IO_REGISTERS_MIN_ADDRESS) >> 1; @SuppressWarnings("unchecked") List<Device> addressDevices = (List<Device>) deviceTable[deviceTableIndex]; if (addressDevices == null) { addressDevices = new ArrayList<>(1); deviceTable[deviceTableIndex] = addressDevices; } addressDevices.add(device); } } /** * Check is given address is mapped to ROM area. * @param address address to check * @return <code>true</code> if given address is mapped to ROM area, * <code>false</code> otherwise */ public boolean isReadOnlyMemoryAddress(int address) { if (address >= 0) { List<MemoryRange> memoryRanges = getMemoryRanges(address); if (memoryRanges == null || memoryRanges.isEmpty()) { return false; } for (MemoryRange memoryRange : memoryRanges) { if (memoryRange != null && memoryRange.isRelatedAddress(address) && memoryRange.getMemory() instanceof ReadOnlyMemory) { return true; } } } return false; } @SuppressWarnings("unchecked") public List<MemoryRange> getMemoryRanges(int address) { return (List<MemoryRange>) memoryTable[address >> 12]; } @SuppressWarnings("unchecked") private List<Device> getDevices(int address) { return (List<Device>) deviceTable[(address - IO_REGISTERS_MIN_ADDRESS) >> 1]; } /** * Initialize bus devices state (on power-on cycle or RESET opcode). * @param isHardwareReset true if bus initialization is initiated by hardware reset, * false if it is initiated by RESET command */ public void initDevices(boolean isHardwareReset) { for (Device device: deviceList) { device.init(getCpu().getTime(), isHardwareReset); } } /** * Reset computer state. */ public void reset() { pause(); synchronized (this) { Timber.d("resetting computer"); getCpu().reset(); } resume(); } /** * Read byte or word from memory or I/O device mapped to given address. * @param isByteMode <code>true</code> to read byte, <code>false</code> to read word * @param address address or memory location to read * @return read memory or I/O device data or <code>BUS_ERROR</code> in case if given memory * location is not mapped */ public int readMemory(boolean isByteMode, int address) { int readValue = BUS_ERROR; int wordAddress = address & 0177776; // Check for memories at given address List<MemoryRange> memoryRanges = getMemoryRanges(address); if (memoryRanges != null) { for (int i = 0, memoryRangesSize = memoryRanges.size(); i < memoryRangesSize; i++) { MemoryRange memoryRange = memoryRanges.get(i); if (memoryRange.isRelatedAddress(address)) { int memoryReadValue = memoryRange.getMemory().read( wordAddress - memoryRange.getStartAddress()); if (memoryReadValue != BUS_ERROR) { readValue = memoryReadValue; break; } } } } // Check for I/O registers if (address >= IO_REGISTERS_MIN_ADDRESS) { List<Device> subdevices = getDevices(address); if (subdevices != null) { long cpuClock = getCpu().getTime(); for (int i = 0, subdevicesSize = subdevices.size(); i < subdevicesSize; i++) { Device subdevice = subdevices.get(i); // Read and combine subdevice state values in word mode int subdeviceReadValue = subdevice.read(cpuClock, wordAddress); if (subdeviceReadValue != BUS_ERROR) { readValue = (readValue == BUS_ERROR) ? subdeviceReadValue : readValue | subdeviceReadValue; } } } } if (readValue != BUS_ERROR) { if (isByteMode && (address & 1) != 0) { // Extract high byte if byte mode read from odd address readValue >>= 8; } readValue &= (isByteMode ? 0377 : 0177777); } return readValue; } /** * Write byte or word to memory or I/O device mapped to given address. * @param isByteMode <code>true</code> to write byte, <code>false</code> to write word * @param address address or memory location to write * @param value value (byte/word) to write to given address * @return <code>true</code> if data successfully written or <code>false</code> * in case if given memory location is not mapped */ public boolean writeMemory(boolean isByteMode, int address, int value) { boolean isWritten = false; if (isByteMode && (address & 1) != 0) { value <<= 8; } // Check for memories at given address List<MemoryRange> memoryRanges = getMemoryRanges(address); if (memoryRanges != null) { for (int i = 0, memoryRangesSize = memoryRanges.size(); i < memoryRangesSize; i++) { MemoryRange memoryRange = memoryRanges.get(i); if (memoryRange.isRelatedAddress(address)) { if (memoryRange.getMemory().write(isByteMode, address - memoryRange.getStartAddress(), value)) { isWritten = true; } } } } // Check for I/O registers if (address >= IO_REGISTERS_MIN_ADDRESS) { List<Device> devices = getDevices(address); if (devices != null) { long cpuClock = getCpu().getTime(); for (int i = 0, devicesSize = devices.size(); i < devicesSize; i++) { Device device = devices.get(i); if (device.write(cpuClock, isByteMode, address, value)) { isWritten = true; } } } } return isWritten; } /** * Start computer. */ public synchronized void start() { if (!isRunning) { Timber.d("starting computer"); clockThread = new Thread(this, "ComputerClockThread"); isRunning = true; clockThread.start(); // Waiting for emulation thread start try { this.wait(); } catch (InterruptedException e) { // Do nothing } for (AudioOutput audioOutput : audioOutputs) { audioOutput.start(); } } else { throw new IllegalStateException("Computer is already running!"); } } /** * Stop computer. */ public void stop() { if (isRunning) { Timber.d("stopping computer"); isRunning = false; for (AudioOutput audioOutput : audioOutputs) { audioOutput.stop(); } synchronized (this) { this.notifyAll(); } while (clockThread.isAlive()) { try { clockThread.join(); } catch (InterruptedException e) { // Do nothing } } } else { throw new IllegalStateException("Computer is already stopped!"); } } public boolean isPaused() { return isPaused; } /** * Pause computer. */ public void pause() { if (!isPaused) { Timber.d("pausing computer"); isPaused = true; for (AudioOutput audioOutput : audioOutputs) { audioOutput.pause(); } } } /** * Resume computer. */ public void resume() { if (isPaused) { Timber.d("resuming computer"); systemUptimeUpdateTimestamp = System.nanoTime(); systemUptimeSyncCheckTimestampTicks = getUptimeTicks(); isPaused = false; synchronized (this) { this.notifyAll(); } for (AudioOutput audioOutput : audioOutputs) { audioOutput.resume(); } } } /** * Release computer resources. */ public void release() { Timber.d("releasing computer"); for (AudioOutput audioOutput : audioOutputs) { audioOutput.release(); } if (floppyController != null) { floppyController.unmountDiskImages(); } if (ideController != null) { ideController.detachDrives(); } } /** * Get effective emulation clock frequency. * @return effective emulation clock frequency (in kHz) */ public float getEffectiveClockFrequency() { return (float) getCpu().getTime() * NANOSECS_IN_MSEC / getSystemUptime(); } /** * Get CPU time (converted from clock ticks to nanoseconds). * @param cpuTime CPU time (in clock ticks) to convert * @return CPU time in nanoseconds */ public long cpuTimeToNanos(long cpuTime) { return cpuTime * NANOSECS_IN_MSEC / clockFrequency; } /** * Get number of CPU clock ticks for given time in nanoseconds. * @param nanosecs time (in nanoseconds) to convert to CPU ticks * @return CPU ticks for given time */ public long nanosToCpuTime(long nanosecs) { return nanosecs * clockFrequency / NANOSECS_IN_MSEC; } /** * Check computer uptime is in sync with system time. */ private void checkUptimeSync() { long uptimeTicks = getUptimeTicks(); if (uptimeTicks - systemUptimeSyncCheckTimestampTicks < systemUptimeSyncCheckIntervalTicks) { return; } long systemTime = System.nanoTime(); systemUptime += systemTime - systemUptimeUpdateTimestamp; systemUptimeUpdateTimestamp = systemTime; systemUptimeSyncCheckTimestampTicks = uptimeTicks; long uptimesDifference = getUptime() - systemUptime; if (uptimesDifference >= UPTIME_SYNC_THRESHOLD) { long uptimesDifferenceMillis = uptimesDifference / NANOSECS_IN_MSEC; int uptimesDifferenceNanos = (int) (uptimesDifference % NANOSECS_IN_MSEC); try { this.wait(uptimesDifferenceMillis, uptimesDifferenceNanos); } catch (InterruptedException e) { // Do nothing } } } @Override public void run() { synchronized (this) { Timber.d("computer started"); this.notifyAll(); while (isRunning) { if (isPaused) { Timber.d("computer paused"); while (isRunning && isPaused) { try { this.wait(100); } catch (InterruptedException e) { // Do nothing } } Timber.d("computer resumed"); } else { cpu.executeNextOperation(); notifyUptimeListeners(); checkUptimeSync(); } } } Timber.d("computer stopped"); } }
3cky/bkemu-android
app/src/main/java/su/comp/bk/arch/Computer.java
Java
gpl-3.0
40,937
// // 1029Ca.cpp // Problems // // Created by NicolasCardozo on 4/24/21. // Copyright © 2021 NicolasCardozo. All rights reserved. // #include <stdio.h> #include <bits/stdc++.h> using namespace std; int main(){ int n; multiset<int> l, r; pair<int, int> intervals[300010]; cin >> n; for (int i = 0; i < n; ++i) { cin >> intervals[i].first >> intervals[i].second; l.insert(intervals[i].first); r.insert(intervals[i].second); } int best = 0; for (int i = 0; i < n; ++i) { l.erase(l.find(intervals[i].first)); r.erase(r.find(intervals[i].second)); best = max(best, *r.begin() - *l.rbegin()); l.insert(intervals[i].first); r.insert(intervals[i].second); } cout << best << endl; return 0; }
mua-uniandes/weekly-problems
codeforces/1029/1029Ca.cpp
C++
gpl-3.0
800
package net.ddns.templex.commands; import io.github.trulyfree.va.command.commands.TabbableCommand; import io.github.trulyfree.va.daemon.Daemon; import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.ProxyServer; import net.md_5.bungee.api.chat.BaseComponent; import net.md_5.bungee.api.chat.ComponentBuilder; import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.event.TabCompleteEvent; import java.util.Collections; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class TPAHereCommand extends TabbableCommand { private final BaseComponent[] NO_ACTIVE_REQUESTS = new ComponentBuilder("You didn't have any active requests!").color(ChatColor.RED).create(); private final BaseComponent[] ALREADY_ACTIVE_REQUEST = new ComponentBuilder("You already have an active request!").color(ChatColor.RED).create(); private final BaseComponent[] TIMEOUT = new ComponentBuilder("Request timed out.").color(ChatColor.RED).create(); /** * The set of currently active requests. This map is threadsafe. */ private final Map<ProxiedPlayer, ProxiedPlayer> requests; /** * The scheduler which manages request timeouts. Requests will timeout after 10 seconds. */ private final ScheduledExecutorService requestManager; public TPAHereCommand() { super("tpahere", "nonop"); this.requests = new ConcurrentHashMap<>(); requestManager = Executors.newSingleThreadScheduledExecutor(); } @Override public void execute(final CommandSender commandSender, String[] strings) { if (!(commandSender instanceof ProxiedPlayer)) { return; } ProxyServer proxy = ProxyServer.getInstance(); final ProxiedPlayer executor = (ProxiedPlayer) commandSender; if (strings.length == 0) { ProxiedPlayer target = null; for (Map.Entry<ProxiedPlayer, ProxiedPlayer> entry : requests.entrySet()) { if (entry.getValue().equals(executor)) { target = entry.getKey(); break; } } if (target == null) { commandSender.sendMessage(NO_ACTIVE_REQUESTS); } else { requests.remove(target); Daemon instance = Daemon.getInstanceNow(); if (instance == null) { CommandUtil.daemonNotFound(commandSender); return; } instance.submitCommands(Collections.singletonList(String.format("/tp %s %s", executor.getName(), target.getName()))); } return; } if (requests.containsKey(executor)) { commandSender.sendMessage(ALREADY_ACTIVE_REQUEST); } else { final ProxiedPlayer requested = proxy.getPlayer(strings[0]); if (requested == null) { commandSender.sendMessage(new ComponentBuilder(String.format("Didn't recognize the name %s.", strings[0])).color(ChatColor.RED).create()); } else { commandSender.sendMessage(new ComponentBuilder(String.format("Request sent to %s", strings[0])).color(ChatColor.GREEN).create()); requested.sendMessage(new ComponentBuilder(String.format("%s requested that you TP to them! Type /tpahere to accept.", commandSender.getName())).color(ChatColor.GOLD).create()); requests.put(executor, requested); requestManager.schedule(new Runnable() { @Override public void run() { if (requests.remove(executor) != null) { commandSender.sendMessage(TIMEOUT); requested.sendMessage(new ComponentBuilder(String.format("Request from %s timed out.", commandSender.getName())).color(ChatColor.RED).create()); } } }, 10, TimeUnit.SECONDS); } } } @Override public void handleTabCompleteEvent(TabCompleteEvent event) { CommandUtil.pushAutocompletePlayers(event); } }
TemplexMC/TemplexAdditions
src/main/java/net/ddns/templex/commands/TPAHereCommand.java
Java
gpl-3.0
4,347
package com.ebrightmoon.doraemonkit.ui.dialog; /** * Created by wanglikun on 2019/4/12 */ public interface DialogListener { boolean onPositive(); boolean onNegative(); void onCancel(); }
jinsedeyuzhou/NewsClient
doraemonkit/src/main/java/com/ebrightmoon/doraemonkit/ui/dialog/DialogListener.java
Java
gpl-3.0
203
# -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2017-11-30 03:32 from __future__ import unicode_literals import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('administrador', '0011_auto_20171129_2215'), ] operations = [ migrations.AlterField( model_name='respuesta', name='fecha', field=models.DateTimeField(blank=True, default=datetime.datetime(2017, 11, 29, 22, 32, 35, 304385), null=True), ), ]
adbetin/organico-cooperativas
administrador/migrations/0012_auto_20171129_2232.py
Python
gpl-3.0
548
/** * @file Surface Component * @author Alexander Rose <alexander.rose@weirdbyte.de> * @private */ import { ComponentRegistry } from "../globals.js"; import { defaults } from "../utils.js"; import Component from "./component.js"; /** * Component wrapping a Surface object * @class * @extends Component * @param {Stage} stage - stage object the component belongs to * @param {Surface} surface - surface object to wrap * @param {ComponentParameters} params - component parameters */ function SurfaceComponent( stage, surface, params ){ var p = params || {}; p.name = defaults( p.name, surface.name ); Component.call( this, stage, p ); this.surface = surface; } SurfaceComponent.prototype = Object.assign( Object.create( Component.prototype ), { constructor: SurfaceComponent, /** * Component type * @alias SurfaceComponent#type * @constant * @type {String} * @default */ type: "surface", /** * Add a new surface representation to the component * @alias SurfaceComponent#addRepresentation * @param {String} type - the name of the representation, one of: * surface, dot. * @param {SurfaceRepresentationParameters} params - representation parameters * @return {RepresentationComponent} the created representation wrapped into * a representation component object */ addRepresentation: function( type, params ){ return Component.prototype.addRepresentation.call( this, type, this.surface, params ); }, dispose: function(){ this.surface.dispose(); Component.prototype.dispose.call( this ); }, centerView: function( zoom ){ var center = this.surface.center; if( zoom ){ zoom = this.surface.boundingBox.size().length(); } this.viewer.centerView( zoom, center ); }, } ); ComponentRegistry.add( "surface", SurfaceComponent ); export default SurfaceComponent;
deepchem/deepchem-gui
gui/static/ngl/src/component/surface-component.js
JavaScript
gpl-3.0
2,061
# daisy-extract # Copyright (C) 2016 James Scholes # This program is free software, licensed under the terms of the GNU General Public License (version 3 or later). # See the file LICENSE for more details. from collections import namedtuple import argparse import glob import logging import os import platform import shutil import sys from bs4 import BeautifulSoup from natsort import natsorted __version__ = '0.1' is_windows = 'windows' in platform.system().lower() logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) log_stream = logging.StreamHandler(sys.stdout) log_stream.setFormatter(logging.Formatter('%(levelname)s: %(message)s')) logger.addHandler(log_stream) HTML_PARSER = 'html.parser' NCC_FILENAME = 'NCC.HTML' MASTER_SMIL_FILENAME = 'MASTER.SMIL' SMIL_GLOB = '*.[sS][mM][iI][lL]' BookMetadata = namedtuple('BookMetadata', ('authors', 'title')) class InvalidDAISYBookError(Exception): pass class ExtractMetadataError(Exception): pass def main(): logger.info('daisy-extract version {0}'.format(__version__)) cli_args = parse_command_line() if cli_args.debug: logger.setLevel(logging.DEBUG) encoding = getattr(cli_args, 'encoding', 'utf-8') input_directory = os.path.abspath(cli_args.input_directory) output_directory = os.path.abspath(cli_args.output_directory) if not os.path.exists(input_directory) or not os.path.isdir(input_directory): exit_with_error('{0} does not exist or is not a directory'.format(input_directory)) try: metadata = create_metadata_object_from_ncc(find_ncc_path(input_directory), encoding=encoding) except InvalidDAISYBookError as e: exit_with_error('The contents of {0} don\'t seem to be a valid DAISY 2.02 book: {1}'.format(input_directory, str(e))) except ExtractMetadataError as e: exit_with_error(str(e)) output_directory = os.path.join(output_directory, make_safe_filename(metadata.authors), make_safe_filename(metadata.title)) logger.info('Extracting content of book: {0} by {1} from {2} to {3}'.format(metadata.title, metadata.authors, input_directory, output_directory)) source_audio_files = [] destination_audio_files = [] for doc in find_smil_documents(input_directory): parsed_doc = parse_smil_document(doc, encoding=encoding) try: section_title = find_document_title(parsed_doc) logger.debug('Found SMIL document: {0}'.format(section_title)) except ExtractMetadataError as e: exit_with_error('Could not retrieve metadata from SMIL document ({0}): {1}'.format(file, str(e))) section_audio_files = get_audio_filenames_from_smil(parsed_doc) logger.debug('SMIL document spans {0} audio file(s)'.format(len(section_audio_files))) for audio_file in section_audio_files: source_audio_files.append((section_title, os.path.join(input_directory, audio_file))) logger.info('Copying {0} audio files'.format(len(source_audio_files))) try: os.makedirs(output_directory) logger.debug('Created directory: {0}'.format(output_directory)) except (FileExistsError, PermissionError): pass track_number = 1 for section_name, file_path in source_audio_files: destination_filename = '{0:02d} - {1}.{2}'.format(track_number, make_safe_filename(section_name), os.path.splitext(file_path)[-1][1:].lower()) destination_path = os.path.join(output_directory, destination_filename) logger.debug('Copying file: {0} to: {1}'.format(file_path, destination_path)) if is_windows: destination_path = add_path_prefix(destination_path) shutil.copyfile(file_path, destination_path) destination_audio_files.append(os.path.split(destination_path)[-1]) track_number += 1 logger.info('Creating M3U playlist') playlist_filename = '{0}.m3u'.format(make_safe_filename(metadata.title)) playlist_path = os.path.join(output_directory, playlist_filename) logger.debug('M3U playlist path: {0}'.format(playlist_path)) if is_windows: playlist_path = add_path_prefix(playlist_path) with open(playlist_path, 'w', newline=None) as f: f.write('\n'.join(destination_audio_files)) logger.info('Done!') def parse_command_line(): parser = argparse.ArgumentParser() parser.add_argument('-i', '--input-directory', nargs='?', required=True) parser.add_argument('-o', '--output-directory', nargs='?', required=True) parser.add_argument('-e', '--encoding', nargs='?', required=False) parser.add_argument('-d', '--debug', dest='debug', action='store_true', default=False, help='Enable debug logging') args = parser.parse_args() return args def exit_with_error(message): logger.error(message) sys.exit(1) def find_ncc_path(directory): filenames = (NCC_FILENAME, NCC_FILENAME.lower()) for filename in filenames: path = os.path.join(directory, filename) if os.path.exists(path) and os.path.isfile(path): logger.debug('Found NCC file: {0}'.format(path)) return path raise InvalidDAISYBookError('Could not find NCC file') def find_smil_documents(directory): documents = list(filter(lambda smil: not smil.upper().endswith(MASTER_SMIL_FILENAME), glob.iglob(os.path.join(directory, SMIL_GLOB)))) if documents: logger.debug('Found {0} SMIL documents in directory'.format(len(documents))) return natsorted(documents) else: raise InvalidDAISYBookError('No SMIL documents found') def create_metadata_object_from_ncc(ncc_path, encoding='utf-8'): with open(ncc_path, 'r', encoding=encoding) as f: ncc = BeautifulSoup(f, HTML_PARSER) title_tag = ncc.find('meta', attrs={'name': 'dc:title'}) if title_tag is None: raise ExtractMetadataError('The title of the DAISY book could not be found') title = title_tag.attrs.get('content') if not title: raise ExtractMetadataError('The title of the DAISY book is blank') creator_tags = ncc.find_all('meta', attrs={'name': 'dc:creator'}) if not creator_tags: raise ExtractMetadataError('No authors are listed in the DAISY book') authors = ', '.join([tag.attrs.get('content') for tag in creator_tags]) return BookMetadata(authors, title) def parse_smil_document(path, encoding='utf-8'): logger.debug('Parsing SMIL document: {0}'.format(os.path.split(path)[-1])) with open(path, 'r', encoding=encoding) as f: return BeautifulSoup(f, HTML_PARSER) def find_document_title(doc): title_tag = doc.find('meta', attrs={'name': 'title'}) if title_tag is None: raise ExtractMetadataError('Unable to extract title from SMIL document') title = title_tag.attrs.get('content') if not title: raise ExtractMetadataError('SMIL document has no title') return title def get_audio_filenames_from_smil(smil): audio_files = [audio.attrs.get('src') for audio in smil.find_all('audio')] unique_audio_files = [] for file in audio_files: if file not in unique_audio_files: unique_audio_files.append(file) return tuple(unique_audio_files) def add_path_prefix(path): return '\\\\?\\{0}'.format(path) def make_safe_filename(filename): # strip out any disallowed chars and replace with underscores disallowed_ascii = [chr(i) for i in range(0, 32)] disallowed_chars = '<>:"/\\|?*^{0}'.format(''.join(disallowed_ascii)) translator = dict((ord(char), '_') for char in disallowed_chars) safe_filename = filename.replace(': ', ' - ').translate(translator).rstrip('. ') return safe_filename if __name__ == '__main__': main()
jscholes/daisy-extract
extract.py
Python
gpl-3.0
7,728
package com.abada.trazability.datamatrix.decode; /* * #%L * Contramed * %% * Copyright (C) 2013 Abada Servicios Desarrollo (investigacion@abadasoft.com) * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. * #L% */ import com.abada.trazability.datamatrix.code.Codificar; import com.abada.trazability.datamatrix.dato.DatosCodeDecode; import com.abada.trazability.datamatrix.dato.DatosExponentePeso; import com.abada.trazability.datamatrix.dato.DatosExponenteVolumen; import com.abada.trazability.datamatrix.dato.ObjectPeso; import com.abada.trazability.datamatrix.dato.ObjectVolumen; import com.abada.trazability.datamatrix.exceptions.ExceptionCodeDecode; import java.util.Calendar; import java.util.HashMap; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** *Decodificar una cadena en formato GS1 * @author maria */ public class DecodeImpl implements Decode { private static final Log logger=LogFactory.getLog(DecodeImpl.class); /** * Metodo para codificar en forma legible por el humano un string que representa * un formato GS1. * @param ent * @return map */ public Map<DatosCodeDecode, Object> decode(String ent) { logger.debug("Entrada: "+ ent); CompruebaDecode cd = new CompruebaDecode(); String sinparen = cd.quitaParentesis(ent); String a; if (sinparen.startsWith(Codificar.START_TAG)) { a = sinparen.substring(3, sinparen.length()); } else { a = sinparen; } Map<DatosCodeDecode, Object> cadenadeco = new HashMap<DatosCodeDecode, Object>(); /** * Comprobamos que el tamaño del String de entrada es correcto, sino algun * campo no estara bien codificado * El tamaño correcto se corresponde con : * GTIN n2+n14 * BATCH n2+X..20 * Expirate Date n2+n6 en formato YYMMDD * Serial Number n2+X..20 * Wigeht n4+n6 * Dimension n4+n6 * En total tendremos 86 caracteres, teniendo en cuenta que se va a expresar el GTIN con 13 caracteres */ if (a.length() > 86) { //new ExceptionCodeDecode("Cadena a decodificar incorrecta"); String cad = "The size of the chain is superior to the allowed one"; //FIXME falta lanzar la excepcion new ExceptionCodeDecode(cad); } else { String falta = ""; while (a.length() != 0) { try { if (a.substring(0, 1).equals(".")) { return cadenadeco; } DatosCodeDecode dato = cd.recogecaso(a); switch (dato) { case EAN13: //GTIN falta = a.substring(16, a.length()); cadenadeco.put(dato.EAN13, a.substring(2, 16)); a = falta; break; case BATCH: //BATCH //La longitud Es variable a como maximo 20 caracteres int maximalong = cd.comprobarLongitud(a.substring(2, a.length()), 20); for (int i = 0; i < a.length(); i++) { if (a.charAt(i) == ('<') || (a.charAt(i) == '.')) { if (a.charAt(i) == ('<')) { falta = a.substring(maximalong + 2, a.length()); cadenadeco.put(dato.BATCH, a.substring(2, maximalong - 2)); break; } else { falta = a.substring(maximalong, a.length()); cadenadeco.put(dato.BATCH, a.substring(2, maximalong)); break; } } } a = falta; break; case EXPIRATEDATE: //EXPIRATEDATE falta = a.substring(8, a.length()); String fecha = a.substring(2, 8); Calendar cal = cd.fechaCalendar(fecha); cadenadeco.put(dato.EXPIRATEDATE, cal); a = falta; break; case SERIALNUMBER: //SerialNumber //La longitud Es variable a como maximo 20 caracteres int maxlong = cd.comprobarLongitud(a.substring(2, a.length()), 20); for (int i = 0; i < a.length(); i++) { if (a.charAt(i) == ('<') || (a.charAt(i) == '.')) { if (a.charAt(i) == ('<')) { falta = a.substring(maxlong + 2, a.length()); cadenadeco.put(dato.SERIALNUMBER, a.substring(2, maxlong - 2)); break; } else { falta = a.substring(maxlong, a.length()); cadenadeco.put(dato.SERIALNUMBER, a.substring(2, maxlong)); break; } } } a = falta; break; case WEIGHT: //Net weight, kilograms (Variable Measure Trade Item) //Longitud fija de 6 caracteres, por eso al comprobar la cantidad de decimales //que puede representar sera como maximo 5 ObjectPeso op = new ObjectPeso(); falta = falta = a.substring(10, a.length()); DatosExponentePeso caso = cd.recogeExpoPeso(a); op.setExpo(caso); String expop = cd.escribeExpoPeso(a, caso); Double peso = Double.parseDouble(expop); op.setValor(peso); cadenadeco.put(dato.WEIGHT, op); a = falta; break; case DIMENSION: ObjectVolumen ov = new ObjectVolumen(); falta = falta = a.substring(10, a.length()); DatosExponenteVolumen volum = cd.recogeExpoVolumen(a); ov.setExpo(volum); String expov = cd.escribeExpoVolumen(a, volum); Double volumen = Double.parseDouble(expov); ov.setValor(volumen); cadenadeco.put(dato.DIMENSION, ov); a = falta; break; default: break; } } catch (ExceptionCodeDecode ex) { logger.error(ex); } } } return cadenadeco; } }
abada-investigacion/contramed
trazability/trazability-datamatrix-utils/src/main/java/com/abada/trazability/datamatrix/decode/DecodeImpl.java
Java
gpl-3.0
8,180
# frozen_string_literal: true class RenameTableCardExpenses < ActiveRecord::Migration[4.2] def change # noinspection RailsParamDefResolve rename_table :card_expenses, :trip_expenses end end
lssjbrolli/ctcadmin
db/migrate/20140809104441_rename_table_card_expenses.rb
Ruby
gpl-3.0
203
/* * This file is part of Applied Energistics 2. * Copyright (c) 2013 - 2014, AlgorithmX2, All rights reserved. * * Applied Energistics 2 is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Applied Energistics 2 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Applied Energistics 2. If not, see <http://www.gnu.org/licenses/lgpl>. */ package appeng.core; import net.minecraftforge.common.util.ForgeDirection; import appeng.api.IAppEngApi; import appeng.api.definitions.Blocks; import appeng.api.definitions.Items; import appeng.api.definitions.Materials; import appeng.api.definitions.Parts; import appeng.api.exceptions.FailedConnection; import appeng.api.features.IRegistryContainer; import appeng.api.networking.IGridBlock; import appeng.api.networking.IGridConnection; import appeng.api.networking.IGridNode; import appeng.api.storage.IStorageHelper; import appeng.core.api.ApiPart; import appeng.core.api.ApiStorage; import appeng.core.features.registries.RegistryContainer; import appeng.me.GridConnection; import appeng.me.GridNode; import appeng.util.Platform; public final class Api implements IAppEngApi { public static final Api INSTANCE = new Api(); private final ApiPart partHelper; // private MovableTileRegistry MovableRegistry = new MovableTileRegistry(); private final IRegistryContainer registryContainer; private final IStorageHelper storageHelper; private final Materials materials; private final Items items; private final Blocks blocks; private final Parts parts; private final ApiDefinitions definitions; private Api() { this.parts = new Parts(); this.blocks = new Blocks(); this.items = new Items(); this.materials = new Materials(); this.storageHelper = new ApiStorage(); this.registryContainer = new RegistryContainer(); this.partHelper = new ApiPart(); this.definitions = new ApiDefinitions( this.partHelper ); } @Override public IRegistryContainer registries() { return this.registryContainer; } @Override public IStorageHelper storage() { return this.storageHelper; } @Override public ApiPart partHelper() { return this.partHelper; } @Override public Items items() { return this.items; } @Override public Materials materials() { return this.materials; } @Override public Blocks blocks() { return this.blocks; } @Override public Parts parts() { return this.parts; } @Override public ApiDefinitions definitions() { return this.definitions; } @Override public IGridNode createGridNode( final IGridBlock blk ) { if( Platform.isClient() ) { throw new IllegalStateException( "Grid features for " + blk + " are server side only." ); } return new GridNode( blk ); } @Override public IGridConnection createGridConnection( final IGridNode a, final IGridNode b ) throws FailedConnection { return new GridConnection( a, b, ForgeDirection.UNKNOWN ); } }
itachi1706/Applied-Energistics-2
src/main/java/appeng/core/Api.java
Java
gpl-3.0
3,373
/* Copyright (C) 2011 Jason von Nieda <jason@vonnieda.org> This file is part of OpenPnP. OpenPnP is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. OpenPnP is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenPnP. If not, see <http://www.gnu.org/licenses/>. For more information about OpenPnP visit http://openpnp.org */ package org.openpnp.gui; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.FlowLayout; import java.awt.FocusTraversalPolicy; import java.awt.Font; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.Hashtable; import java.util.Locale; import java.util.concurrent.Callable; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSlider; import javax.swing.JTextField; import javax.swing.SwingUtilities; import org.openpnp.ConfigurationListener; import org.openpnp.gui.components.CameraPanel; import org.openpnp.gui.support.Icons; import org.openpnp.gui.support.MessageBoxes; import org.openpnp.gui.support.NozzleItem; import org.openpnp.model.Configuration; import org.openpnp.model.LengthUnit; import org.openpnp.model.Location; import org.openpnp.spi.Camera; import org.openpnp.spi.Head; import org.openpnp.spi.Machine; import org.openpnp.spi.MachineListener; import org.openpnp.spi.Nozzle; import org.openpnp.spi.PasteDispenser; import org.openpnp.util.MovableUtils; import com.google.common.util.concurrent.FutureCallback; import com.jgoodies.forms.layout.ColumnSpec; import com.jgoodies.forms.layout.FormLayout; import com.jgoodies.forms.layout.FormSpecs; import com.jgoodies.forms.layout.RowSpec; public class MachineControlsPanel extends JPanel { private final JFrame frame; private final CameraPanel cameraPanel; private final Configuration configuration; private Nozzle selectedNozzle; private JTextField textFieldX; private JTextField textFieldY; private JTextField textFieldC; private JTextField textFieldZ; private JButton btnStartStop; private JSlider sliderIncrements; private JComboBox comboBoxNozzles; private Color startColor = Color.green; private Color stopColor = new Color(178, 34, 34); private Color droNormalColor = new Color(0xBDFFBE); private Color droEditingColor = new Color(0xF0F0A1); private Color droWarningColor = new Color(0xFF5C5C); private Color droSavedColor = new Color(0x90cce0); private JogControlsPanel jogControlsPanel; private JDialog jogControlsWindow; private volatile double savedX = Double.NaN, savedY = Double.NaN, savedZ = Double.NaN, savedC = Double.NaN; /** * Create the panel. */ public MachineControlsPanel(Configuration configuration, JFrame frame, CameraPanel cameraPanel) { this.frame = frame; this.cameraPanel = cameraPanel; this.configuration = configuration; jogControlsPanel = new JogControlsPanel(configuration, this, frame); createUi(); configuration.addListener(configurationListener); jogControlsWindow = new JDialog(frame, "Jog Controls"); jogControlsWindow.setResizable(false); jogControlsWindow.getContentPane().setLayout(new BorderLayout()); jogControlsWindow.getContentPane().add(jogControlsPanel); } /** * @deprecated See {@link Machine#submit(Runnable)} * @param runnable */ public void submitMachineTask(Runnable runnable) { if (!Configuration.get().getMachine().isEnabled()) { MessageBoxes.errorBox(getTopLevelAncestor(), "Machine Error", "Machine is not started."); return; } Configuration.get().getMachine().submit(runnable); } public void setSelectedNozzle(Nozzle nozzle) { selectedNozzle = nozzle; comboBoxNozzles.setSelectedItem(selectedNozzle); updateDros(); } public Nozzle getSelectedNozzle() { return selectedNozzle; } public PasteDispenser getSelectedPasteDispenser() { try { // TODO: We don't actually have a way to select a dispenser yet, so // until we do we just return the first one. return Configuration.get().getMachine().getHeads().get(0).getPasteDispensers().get(0); } catch (Exception e) { return null; } } public JogControlsPanel getJogControlsPanel() { return jogControlsPanel; } private void setUnits(LengthUnit units) { if (units == LengthUnit.Millimeters) { Hashtable<Integer, JLabel> incrementsLabels = new Hashtable<Integer, JLabel>(); incrementsLabels.put(1, new JLabel("0.01")); incrementsLabels.put(2, new JLabel("0.1")); incrementsLabels.put(3, new JLabel("1.0")); incrementsLabels.put(4, new JLabel("10")); incrementsLabels.put(5, new JLabel("100")); sliderIncrements.setLabelTable(incrementsLabels); } else if (units == LengthUnit.Inches) { Hashtable<Integer, JLabel> incrementsLabels = new Hashtable<Integer, JLabel>(); incrementsLabels.put(1, new JLabel("0.001")); incrementsLabels.put(2, new JLabel("0.01")); incrementsLabels.put(3, new JLabel("0.1")); incrementsLabels.put(4, new JLabel("1.0")); incrementsLabels.put(5, new JLabel("10.0")); sliderIncrements.setLabelTable(incrementsLabels); } else { throw new Error("setUnits() not implemented for " + units); } updateDros(); } public double getJogIncrement() { if (configuration.getSystemUnits() == LengthUnit.Millimeters) { return 0.01 * Math.pow(10, sliderIncrements.getValue() - 1); } else if (configuration.getSystemUnits() == LengthUnit.Inches) { return 0.001 * Math.pow(10, sliderIncrements.getValue() - 1); } else { throw new Error("getJogIncrement() not implemented for " + configuration.getSystemUnits()); } } @Override public void setEnabled(boolean enabled) { super.setEnabled(enabled); homeAction.setEnabled(enabled); goToZeroAction.setEnabled(enabled); jogControlsPanel.setEnabled(enabled); targetCameraAction.setEnabled(enabled); targetToolAction.setEnabled(enabled); } public Location getCurrentLocation() { if (selectedNozzle == null) { return null; } Location l = selectedNozzle.getLocation(); l = l.convertToUnits(configuration.getSystemUnits()); return l; } public void updateDros() { Location l = getCurrentLocation(); if (l == null) { return; } double x, y, z, c; x = l.getX(); y = l.getY(); z = l.getZ(); c = l.getRotation(); double savedX = this.savedX; if (!Double.isNaN(savedX)) { x -= savedX; } double savedY = this.savedY; if (!Double.isNaN(savedY)) { y -= savedY; } double savedZ = this.savedZ; if (!Double.isNaN(savedZ)) { z -= savedZ; } double savedC = this.savedC; if (!Double.isNaN(savedC)) { c -= savedC; } textFieldX.setText(String.format(Locale.US,configuration.getLengthDisplayFormat(), x)); textFieldY.setText(String.format(Locale.US,configuration.getLengthDisplayFormat(), y)); textFieldZ.setText(String.format(Locale.US,configuration.getLengthDisplayFormat(), z)); textFieldC.setText(String.format(Locale.US,configuration.getLengthDisplayFormat(), c)); } private void createUi() { setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); ButtonGroup buttonGroup = new ButtonGroup(); JPanel panel = new JPanel(); add(panel); panel.setLayout(new FormLayout(new ColumnSpec[] { FormSpecs.RELATED_GAP_COLSPEC, ColumnSpec.decode("default:grow"),}, new RowSpec[] { FormSpecs.RELATED_GAP_ROWSPEC, FormSpecs.DEFAULT_ROWSPEC,})); comboBoxNozzles = new JComboBox(); comboBoxNozzles.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { setSelectedNozzle(((NozzleItem) comboBoxNozzles.getSelectedItem()).getNozzle()); } }); panel.add(comboBoxNozzles, "2, 2, fill, default"); JPanel panelDrosParent = new JPanel(); add(panelDrosParent); panelDrosParent.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5)); JPanel panelDros = new JPanel(); panelDrosParent.add(panelDros); panelDros.setLayout(new BoxLayout(panelDros, BoxLayout.Y_AXIS)); JPanel panelDrosFirstLine = new JPanel(); panelDros.add(panelDrosFirstLine); panelDrosFirstLine.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5)); JLabel lblX = new JLabel("X"); lblX.setFont(new Font("Lucida Grande", Font.BOLD, 24)); panelDrosFirstLine.add(lblX); textFieldX = new JTextField(); textFieldX.setEditable(false); textFieldX.setFocusTraversalKeysEnabled(false); textFieldX.setSelectionColor(droEditingColor); textFieldX.setDisabledTextColor(Color.BLACK); textFieldX.setBackground(droNormalColor); textFieldX.setFont(new Font("Lucida Grande", Font.BOLD, 24)); textFieldX.setText("0000.0000"); textFieldX.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (SwingUtilities.isRightMouseButton(e)) { savedX = Double.NaN; } saveXAction.actionPerformed(null); } }); panelDrosFirstLine.add(textFieldX); textFieldX.setColumns(6); Component horizontalStrut = Box.createHorizontalStrut(15); panelDrosFirstLine.add(horizontalStrut); JLabel lblY = new JLabel("Y"); lblY.setFont(new Font("Lucida Grande", Font.BOLD, 24)); panelDrosFirstLine.add(lblY); textFieldY = new JTextField(); textFieldY.setEditable(false); textFieldY.setFocusTraversalKeysEnabled(false); textFieldY.setSelectionColor(droEditingColor); textFieldY.setDisabledTextColor(Color.BLACK); textFieldY.setBackground(droNormalColor); textFieldY.setFont(new Font("Lucida Grande", Font.BOLD, 24)); textFieldY.setText("0000.0000"); textFieldY.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (SwingUtilities.isRightMouseButton(e)) { savedY = Double.NaN; } saveYAction.actionPerformed(null); } }); panelDrosFirstLine.add(textFieldY); textFieldY.setColumns(6); JButton btnTargetTool = new JButton(targetToolAction); panelDrosFirstLine.add(btnTargetTool); btnTargetTool.setToolTipText("Position the tool at the camera's current location."); JPanel panelDrosSecondLine = new JPanel(); panelDros.add(panelDrosSecondLine); panelDrosSecondLine.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5)); JLabel lblC = new JLabel("C"); lblC.setFont(new Font("Lucida Grande", Font.BOLD, 24)); panelDrosSecondLine.add(lblC); textFieldC = new JTextField(); textFieldC.setEditable(false); textFieldC.setFocusTraversalKeysEnabled(false); textFieldC.setSelectionColor(droEditingColor); textFieldC.setDisabledTextColor(Color.BLACK); textFieldC.setBackground(droNormalColor); textFieldC.setText("0000.0000"); textFieldC.setFont(new Font("Lucida Grande", Font.BOLD, 24)); textFieldC.setColumns(6); textFieldC.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (SwingUtilities.isRightMouseButton(e)) { savedC = Double.NaN; } saveCAction.actionPerformed(null); } }); panelDrosSecondLine.add(textFieldC); Component horizontalStrut_1 = Box.createHorizontalStrut(15); panelDrosSecondLine.add(horizontalStrut_1); JLabel lblZ = new JLabel("Z"); lblZ.setFont(new Font("Lucida Grande", Font.BOLD, 24)); panelDrosSecondLine.add(lblZ); textFieldZ = new JTextField(); textFieldZ.setEditable(false); textFieldZ.setFocusTraversalKeysEnabled(false); textFieldZ.setSelectionColor(droEditingColor); textFieldZ.setDisabledTextColor(Color.BLACK); textFieldZ.setBackground(droNormalColor); textFieldZ.setText("0000.0000"); textFieldZ.setFont(new Font("Lucida Grande", Font.BOLD, 24)); textFieldZ.setColumns(6); textFieldZ.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (SwingUtilities.isRightMouseButton(e)) { savedZ = Double.NaN; } saveZAction.actionPerformed(null); } }); panelDrosSecondLine.add(textFieldZ); JButton btnTargetCamera = new JButton(targetCameraAction); panelDrosSecondLine.add(btnTargetCamera); btnTargetCamera.setToolTipText("Position the camera at the tool's current location."); JPanel panelIncrements = new JPanel(); add(panelIncrements); sliderIncrements = new JSlider(); panelIncrements.add(sliderIncrements); sliderIncrements.setMajorTickSpacing(1); sliderIncrements.setValue(1); sliderIncrements.setSnapToTicks(true); sliderIncrements.setPaintLabels(true); sliderIncrements.setPaintTicks(true); sliderIncrements.setMinimum(1); sliderIncrements.setMaximum(5); JPanel panelStartStop = new JPanel(); add(panelStartStop); panelStartStop.setLayout(new BorderLayout(0, 0)); btnStartStop = new JButton(startMachineAction); btnStartStop.setFocusable(true); btnStartStop.setForeground(startColor); panelStartStop.add(btnStartStop); btnStartStop.setFont(new Font("Lucida Grande", Font.BOLD, 48)); btnStartStop.setPreferredSize(new Dimension(160, 70)); setFocusTraversalPolicy(focusPolicy); setFocusTraversalPolicyProvider(true); } private FocusTraversalPolicy focusPolicy = new FocusTraversalPolicy() { @Override public Component getComponentAfter(Container aContainer, Component aComponent) { return sliderIncrements; } @Override public Component getComponentBefore(Container aContainer, Component aComponent) { return sliderIncrements; } @Override public Component getDefaultComponent(Container aContainer) { return sliderIncrements; } @Override public Component getFirstComponent(Container aContainer) { return sliderIncrements; } @Override public Component getInitialComponent(Window window) { return sliderIncrements; } @Override public Component getLastComponent(Container aContainer) { return sliderIncrements; } }; @SuppressWarnings("serial") private Action stopMachineAction = new AbstractAction("STOP") { @Override public void actionPerformed(ActionEvent arg0) { setEnabled(false); Configuration.get().getMachine().submit(new Callable<Void>() { @Override public Void call() throws Exception { Configuration.get().getMachine().setEnabled(false); return null; } }, new FutureCallback<Void>() { @Override public void onSuccess(Void result) { setEnabled(true); } @Override public void onFailure(Throwable t) { MessageBoxes.errorBox(MachineControlsPanel.this, "Stop Failed", t.getMessage()); setEnabled(true); } }, true); } }; @SuppressWarnings("serial") private Action startMachineAction = new AbstractAction("START") { @Override public void actionPerformed(ActionEvent arg0) { setEnabled(false); Configuration.get().getMachine().submit(new Callable<Void>() { @Override public Void call() throws Exception { Configuration.get().getMachine().setEnabled(true); return null; } }, new FutureCallback<Void>() { @Override public void onSuccess(Void result) { setEnabled(true); } @Override public void onFailure(Throwable t) { MessageBoxes.errorBox(MachineControlsPanel.this, "Start Failed", t.getMessage()); setEnabled(true); } }, true); } }; @SuppressWarnings("serial") public Action goToZeroAction = new AbstractAction("Go To Zero") { @Override public void actionPerformed(ActionEvent arg0) { submitMachineTask(new Runnable() { public void run() { try { selectedNozzle.moveToSafeZ(1.0); // Move to 0, 0, 0, 0. selectedNozzle.moveTo(new Location(LengthUnit.Millimeters, 0, 0, 0, 0), 1.0); } catch (Exception e) { e.printStackTrace(); MessageBoxes.errorBox(frame, "Go To Zero Failed", e); } } }); } }; @SuppressWarnings("serial") public Action homeAction = new AbstractAction("Home") { @Override public void actionPerformed(ActionEvent arg0) { submitMachineTask(new Runnable() { public void run() { try { selectedNozzle.getHead().home(); } catch (Exception e) { e.printStackTrace(); MessageBoxes.errorBox(frame, "Homing Failed", e); } } }); } }; public Action showHideJogControlsWindowAction = new AbstractAction("Show Jog Controls") { @Override public void actionPerformed(ActionEvent arg0) { if (jogControlsWindow.isVisible()) { // Hide jogControlsWindow.setVisible(false); putValue(AbstractAction.NAME, "Show Jog Controls"); } else { // Show jogControlsWindow.setVisible(true); jogControlsWindow.pack(); int x = (int) getLocationOnScreen().getX(); int y = (int) getLocationOnScreen().getY(); x += (getSize().getWidth() / 2) - (jogControlsWindow.getSize().getWidth() / 2); y += getSize().getHeight(); jogControlsWindow.setLocation(x, y); putValue(AbstractAction.NAME, "Hide Jog Controls"); } } }; @SuppressWarnings("serial") public Action raiseIncrementAction = new AbstractAction("Raise Jog Increment") { @Override public void actionPerformed(ActionEvent arg0) { sliderIncrements.setValue(Math.min(sliderIncrements.getMaximum(), sliderIncrements.getValue() + 1)); } }; @SuppressWarnings("serial") public Action lowerIncrementAction = new AbstractAction("Lower Jog Increment") { @Override public void actionPerformed(ActionEvent arg0) { sliderIncrements.setValue(Math.max(sliderIncrements.getMinimum(), sliderIncrements.getValue() - 1)); } }; @SuppressWarnings("serial") public Action targetToolAction = new AbstractAction(null, Icons.centerTool) { @Override public void actionPerformed(ActionEvent arg0) { final Location location = cameraPanel.getSelectedCameraLocation(); final Nozzle nozzle = getSelectedNozzle(); submitMachineTask(new Runnable() { public void run() { try { MovableUtils.moveToLocationAtSafeZ(nozzle, location, 1.0); } catch (Exception e) { MessageBoxes.errorBox(frame, "Move Failed", e); } } }); } }; @SuppressWarnings("serial") public Action targetCameraAction = new AbstractAction(null, Icons.centerCamera) { @Override public void actionPerformed(ActionEvent arg0) { final Camera camera = cameraPanel.getSelectedCamera(); if (camera == null) { return; } final Location location = getSelectedNozzle().getLocation(); submitMachineTask(new Runnable() { public void run() { try { MovableUtils.moveToLocationAtSafeZ(camera, location, 1.0); } catch (Exception e) { MessageBoxes.errorBox(frame, "Move Failed", e); } } }); } }; @SuppressWarnings("serial") public Action saveXAction = new AbstractAction(null) { @Override public void actionPerformed(ActionEvent arg0) { if (Double.isNaN(savedX)) { textFieldX.setBackground(droSavedColor); savedX = getCurrentLocation().getX(); } else { textFieldX.setBackground(droNormalColor); savedX = Double.NaN; } EventQueue.invokeLater(new Runnable() { public void run() { updateDros(); } }); } }; @SuppressWarnings("serial") public Action saveYAction = new AbstractAction(null) { @Override public void actionPerformed(ActionEvent arg0) { if (Double.isNaN(savedY)) { textFieldY.setBackground(droSavedColor); savedY = getCurrentLocation().getY(); } else { textFieldY.setBackground(droNormalColor); savedY = Double.NaN; } EventQueue.invokeLater(new Runnable() { public void run() { updateDros(); } }); } }; @SuppressWarnings("serial") public Action saveZAction = new AbstractAction(null) { @Override public void actionPerformed(ActionEvent arg0) { if (Double.isNaN(savedZ)) { textFieldZ.setBackground(droSavedColor); savedZ = getCurrentLocation().getZ(); } else { textFieldZ.setBackground(droNormalColor); savedZ = Double.NaN; } EventQueue.invokeLater(new Runnable() { public void run() { updateDros(); } }); } }; @SuppressWarnings("serial") public Action saveCAction = new AbstractAction(null) { @Override public void actionPerformed(ActionEvent arg0) { if (Double.isNaN(savedC)) { textFieldC.setBackground(droSavedColor); savedC = getCurrentLocation().getRotation(); } else { textFieldC.setBackground(droNormalColor); savedC = Double.NaN; } EventQueue.invokeLater(new Runnable() { public void run() { updateDros(); } }); } }; private MachineListener machineListener = new MachineListener.Adapter() { @Override public void machineHeadActivity(Machine machine, Head head) { EventQueue.invokeLater(new Runnable() { public void run() { updateDros(); } }); } @Override public void machineEnabled(Machine machine) { btnStartStop.setAction(machine.isEnabled() ? stopMachineAction : startMachineAction); btnStartStop.setForeground(machine.isEnabled() ? stopColor : startColor); setEnabled(true); } @Override public void machineEnableFailed(Machine machine, String reason) { btnStartStop.setAction(machine.isEnabled() ? stopMachineAction : startMachineAction); btnStartStop.setForeground(machine.isEnabled() ? stopColor : startColor); } @Override public void machineDisabled(Machine machine, String reason) { btnStartStop.setAction(machine.isEnabled() ? stopMachineAction : startMachineAction); btnStartStop.setForeground(machine.isEnabled() ? stopColor : startColor); setEnabled(false); } @Override public void machineDisableFailed(Machine machine, String reason) { btnStartStop.setAction(machine.isEnabled() ? stopMachineAction : startMachineAction); btnStartStop.setForeground(machine.isEnabled() ? stopColor : startColor); } }; private ConfigurationListener configurationListener = new ConfigurationListener.Adapter() { @Override public void configurationComplete(Configuration configuration) { Machine machine = configuration.getMachine(); if (machine != null) { machine.removeListener(machineListener); } for (Head head : machine.getHeads()) { for (Nozzle nozzle : head.getNozzles()) { comboBoxNozzles.addItem(new NozzleItem(nozzle)); } } setSelectedNozzle(((NozzleItem) comboBoxNozzles.getItemAt(0)).getNozzle()); setUnits(configuration.getSystemUnits()); machine.addListener(machineListener); btnStartStop.setAction(machine.isEnabled() ? stopMachineAction : startMachineAction); btnStartStop.setForeground(machine.isEnabled() ? stopColor : startColor); setEnabled(machine.isEnabled()); } }; }
TinWhiskers/openpnp
src/main/java/org/openpnp/gui/MachineControlsPanel.java
Java
gpl-3.0
25,064
(function() { 'use strict'; angular .module('weatheropendataApp') .config(stateConfig); stateConfig.$inject = ['$stateProvider']; function stateConfig($stateProvider) { $stateProvider.state('register', { parent: 'account', url: '/register', data: { authorities: [], pageTitle: 'register.title' }, views: { 'content@': { templateUrl: 'app/account/register/register.html', controller: 'RegisterController', controllerAs: 'vm' } }, resolve: { translatePartialLoader: ['$translate', '$translatePartialLoader', function ($translate, $translatePartialLoader) { $translatePartialLoader.addPart('register'); return $translate.refresh(); }] } }); } })();
hackathinho/open-clean-energy
backend-weather/src/main/webapp/app/account/register/register.state.js
JavaScript
gpl-3.0
993
/* * MindmapsDB - A Distributed Semantic Database * Copyright (C) 2016 Mindmaps Research Ltd * * MindmapsDB is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MindmapsDB is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MindmapsDB. If not, see <http://www.gnu.org/licenses/gpl.txt>. */ package io.mindmaps.graql; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import io.mindmaps.MindmapsTransaction; import io.mindmaps.core.model.Concept; import io.mindmaps.graql.internal.parser.GraqlLexer; import org.antlr.v4.runtime.ANTLRInputStream; import org.antlr.v4.runtime.BaseErrorListener; import org.antlr.v4.runtime.Token; import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; /** * An autocomplete result suggesting keywords, types and variables that the user may wish to type */ public class Autocomplete { private final ImmutableSet<String> candidates; private final int cursorPosition; /** * @param transaction the transaction to find types in * @param query the query to autocomplete * @param cursorPosition the cursor position in the query * @return an autocomplete object containing potential candidates and cursor position to autocomplete from */ public static Autocomplete create(MindmapsTransaction transaction, String query, int cursorPosition) { return new Autocomplete(transaction, query, cursorPosition); } /** * @return all candidate autocomplete words */ public Set<String> getCandidates() { return candidates; } /** * @return the cursor position that autocompletions should start from */ public int getCursorPosition() { return cursorPosition; } /** * @param transaction the transaction to find types in * @param query the query to autocomplete * @param cursorPosition the cursor position in the query */ private Autocomplete(MindmapsTransaction transaction, String query, int cursorPosition) { Optional<? extends Token> optToken = getCursorToken(query, cursorPosition); candidates = ImmutableSet.copyOf(findCandidates(transaction, query, optToken)); this.cursorPosition = findCursorPosition(cursorPosition, optToken); } /** * @param transaction the transaction to find types in * @param query a graql query * @param optToken the token the cursor is on in the query * @return a set of potential autocomplete words */ private static Set<String> findCandidates(MindmapsTransaction transaction, String query, Optional<? extends Token> optToken) { Set<String> allCandidates = Stream.of(getKeywords(), getTypes(transaction), getVariables(query)) .flatMap(Function.identity()).collect(Collectors.toSet()); return optToken.map( token -> { Set<String> candidates = allCandidates.stream() .filter(candidate -> candidate.startsWith(token.getText())) .collect(Collectors.toSet()); if (candidates.size() == 1 && candidates.iterator().next().equals(token.getText())) { return Sets.newHashSet(" "); } else { return candidates; } } ).orElse(allCandidates); } /** * @param cursorPosition the current cursor position * @param optToken the token the cursor is on in the query * @return the new cursor position to start autocompleting from */ private int findCursorPosition(int cursorPosition, Optional<? extends Token> optToken) { return optToken .filter(token -> !candidates.contains(" ")) .map(Token::getStartIndex) .orElse(cursorPosition); } /** * @return all Graql keywords */ private static Stream<String> getKeywords() { HashSet<String> keywords = new HashSet<>(); for (int i = 1; GraqlLexer.VOCABULARY.getLiteralName(i) != null; i ++) { String name = GraqlLexer.VOCABULARY.getLiteralName(i); keywords.add(name.replaceAll("'", "")); } return keywords.stream(); } /** * @param transaction the transaction to find types in * @return all type IDs in the ontology */ private static Stream<String> getTypes(MindmapsTransaction transaction) { return transaction.getMetaType().instances().stream().map(Concept::getId); } /** * @param query a graql query * @return all variable names occurring in the query */ private static Stream<String> getVariables(String query) { List<? extends Token> allTokens = getTokens(query); if (allTokens.size() > 0) allTokens.remove(allTokens.size() - 1); return allTokens.stream() .filter(t -> t.getType() == GraqlLexer.VARIABLE) .map(Token::getText); } /** * @param query a graql query * @param cursorPosition the cursor position in the query * @return the token at the cursor position in the given graql query */ private static Optional<? extends Token> getCursorToken(String query, int cursorPosition) { if (query == null) return Optional.empty(); return getTokens(query).stream() .filter(t -> t.getStartIndex() <= cursorPosition && t.getStopIndex() >= cursorPosition - 1) .findFirst(); } /** * @param query a graql query * @return a list of tokens from running the lexer on the query */ private static List<? extends Token> getTokens(String query) { ANTLRInputStream input = new ANTLRInputStream(query); GraqlLexer lexer = new GraqlLexer(input); // Ignore syntax errors lexer.removeErrorListeners(); lexer.addErrorListener(new BaseErrorListener()); return lexer.getAllTokens(); } }
duckofyork/mindmapsdb
mindmaps-graql/src/main/java/io/mindmaps/graql/Autocomplete.java
Java
gpl-3.0
6,589
using UnityEngine; using System.Collections; using System.Collections.Generic; public class Camel : GamePiece { public override List<GridCell>GetMovementCells(GameGrid grid, GridCell cell) { return grid.GetLeapCells(cell, 3, 1); } public override List<GridCell>GetAttackCells(GameGrid grid, GridCell cell) { return GetMovementCells(grid, cell); } }
matthewvroman/single-player-chess
Assets/Scripts/GamePieces/Camel.cs
C#
gpl-3.0
365
package org.betonquest.betonquest.objectives; import lombok.CustomLog; import org.betonquest.betonquest.BetonQuest; import org.betonquest.betonquest.Instruction; import org.betonquest.betonquest.api.Condition; import org.betonquest.betonquest.api.Objective; import org.betonquest.betonquest.api.QuestEvent; import org.betonquest.betonquest.conditions.ChestItemCondition; import org.betonquest.betonquest.events.ChestTakeEvent; import org.betonquest.betonquest.exceptions.InstructionParseException; import org.betonquest.betonquest.exceptions.ObjectNotFoundException; import org.betonquest.betonquest.exceptions.QuestRuntimeException; import org.betonquest.betonquest.id.NoID; import org.betonquest.betonquest.utils.PlayerConverter; import org.betonquest.betonquest.utils.location.CompoundLocation; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.HandlerList; import org.bukkit.event.Listener; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.inventory.InventoryHolder; /** * Requires the player to put items in the chest. Items can optionally NOT * disappear once the chest is closed. */ @SuppressWarnings("PMD.CommentRequired") @CustomLog public class ChestPutObjective extends Objective implements Listener { private final Condition chestItemCondition; private final QuestEvent chestTakeEvent; private final CompoundLocation loc; public ChestPutObjective(final Instruction instruction) throws InstructionParseException { super(instruction); template = ObjectiveData.class; // extract location loc = instruction.getLocation(); final String location = instruction.current(); final String items = instruction.next(); try { chestItemCondition = new ChestItemCondition(new Instruction(instruction.getPackage(), new NoID(instruction.getPackage()), "chestitem " + location + " " + items)); } catch (InstructionParseException | ObjectNotFoundException e) { throw new InstructionParseException("Could not create inner chest item condition: " + e.getMessage(), e); } if (instruction.hasArgument("items-stay")) { chestTakeEvent = null; } else { try { chestTakeEvent = new ChestTakeEvent(new Instruction(instruction.getPackage(), new NoID(instruction.getPackage()), "chesttake " + location + " " + items)); } catch (final ObjectNotFoundException e) { throw new InstructionParseException("Could not create inner chest take event: " + e.getMessage(), e); } } } @SuppressWarnings("PMD.CyclomaticComplexity") @EventHandler(ignoreCancelled = true) public void onChestClose(final InventoryCloseEvent event) { if (!(event.getPlayer() instanceof Player)) { return; } final String playerID = PlayerConverter.getID((Player) event.getPlayer()); if (!containsPlayer(playerID)) { return; } try { final Location targetChestLocation = loc.getLocation(playerID); final Block block = targetChestLocation.getBlock(); if (!(block.getState() instanceof InventoryHolder)) { final World world = targetChestLocation.getWorld(); LOG.warn(instruction.getPackage(), String.format("Error in '%s' chestput objective: Block at location x:%d y:%d z:%d in world '%s' isn't a chest!", instruction.getID().getFullID(), targetChestLocation.getBlockX(), targetChestLocation.getBlockY(), targetChestLocation.getBlockZ(), world == null ? "null" : world.getName())); return; } final InventoryHolder chest = (InventoryHolder) block.getState(); if (!chest.equals(event.getInventory().getHolder())) { return; } if (chestItemCondition.handle(playerID) && checkConditions(playerID)) { completeObjective(playerID); if (chestTakeEvent != null) { chestTakeEvent.handle(playerID); } } } catch (final QuestRuntimeException e) { LOG.warn(instruction.getPackage(), "Error while handling '" + instruction.getID() + "' objective: " + e.getMessage(), e); } } @Override public void start() { Bukkit.getPluginManager().registerEvents(this, BetonQuest.getInstance()); } @Override public void stop() { HandlerList.unregisterAll(this); } @Override public String getDefaultDataInstruction() { return ""; } @Override public String getProperty(final String name, final String playerID) { return ""; } }
Co0sh/BetonQuest
src/main/java/org/betonquest/betonquest/objectives/ChestPutObjective.java
Java
gpl-3.0
5,067
/** * File ./src/main/java/de/lemo/dms/db/mapping/CourseAssignmentMining.java * Lemo-Data-Management-Server for learning analytics. * Copyright (C) 2013 * Leonard Kappe, Andreas Pursian, Sebastian Schwarzrock, Boris Wenzlaff * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ /** * File ./main/java/de/lemo/dms/db/mapping/CourseAssignmentMining.java * Date 2013-01-24 * Project Lemo Learning Analytics */ package de.lemo.dms.db.mapping; import java.util.Map; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Transient; import de.lemo.dms.db.mapping.abstractions.ICourseLORelation; import de.lemo.dms.db.mapping.abstractions.ICourseRatedObjectAssociation; import de.lemo.dms.db.mapping.abstractions.ILearningObject; import de.lemo.dms.db.mapping.abstractions.IMappingClass; import de.lemo.dms.db.mapping.abstractions.IRatedObject; /** * This class represents the relationship between the courses and assignments. * @author Sebastian Schwarzrock */ @Entity @Table(name = "course_assignment") public class CourseAssignmentMining implements ICourseLORelation, IMappingClass, ICourseRatedObjectAssociation { private long id; private CourseMining course; private AssignmentMining assignment; private Long platform; @Override public boolean equals(final IMappingClass o) { if (!(o instanceof CourseAssignmentMining)) { return false; } if ((o.getId() == this.getId()) && (o instanceof CourseAssignmentMining)) { return true; } return false; } @Override public int hashCode() { return (int) id; } /** * standard getter for the attribut course * * @return a course in which the quiz is used */ @Override @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="course_id") public CourseMining getCourse() { return this.course; } /** * standard setter for the attribut course * * @param course * a course in which the quiz is used */ public void setCourse(final CourseMining course) { this.course = course; } /** * parameterized setter for the attribut course * * @param course * the id of a course in which the quiz is used * @param courseMining * a list of new added courses, which is searched for the course with the id submitted in the course * parameter * @param oldCourseMining * a list of course in the miningdatabase, which is searched for the course with the id submitted in the * course parameter */ public void setCourse(final long course, final Map<Long, CourseMining> courseMining, final Map<Long, CourseMining> oldCourseMining) { if (courseMining.get(course) != null) { this.course = courseMining.get(course); courseMining.get(course).addCourseAssignment(this); } if ((this.course == null) && (oldCourseMining.get(course) != null)) { this.course = oldCourseMining.get(course); oldCourseMining.get(course).addCourseAssignment(this); } } /** * standard getter for the attribut assignment * * @return the quiz which is used in the course */ @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="assignment_id") public AssignmentMining getAssignment() { return this.assignment; } /** * standard setter for the attribut assignment * * @param assignment * the assignment which is used in the course */ public void setAssignment(final AssignmentMining assignment) { this.assignment = assignment; } /** * parameterized setter for the attribut assignment * * @param id * the id of the quiz in which the action takes place * @param assignmentMining * a list of new added quiz, which is searched for the quiz with the qid and qtype submitted in the other * parameters * @param oldAssignmentMining * a list of quiz in the miningdatabase, which is searched for the quiz with the qid and qtype submitted * in the other parameters */ public void setAssignment(final long assignment, final Map<Long, AssignmentMining> assignmentMining, final Map<Long, AssignmentMining> oldAssignmentMining) { if (assignmentMining.get(assignment) != null) { this.assignment = assignmentMining.get(assignment); assignmentMining.get(assignment).addCourseAssignment(this); } if ((this.assignment == null) && (oldAssignmentMining.get(assignment) != null)) { this.assignment = oldAssignmentMining.get(assignment); oldAssignmentMining.get(assignment).addCourseAssignment(this); } } /** * standard setter for the attribut id * * @param id * the identifier for the assoziation between course and assignment */ public void setId(final long id) { this.id = id; } /** * standard getter for the attribut id * * @return the identifier for the assoziation between course and assignment */ @Override @Id public long getId() { return this.id; } @Column(name="platform") public Long getPlatform() { return this.platform; } public void setPlatform(final Long platform) { this.platform = platform; } @Override @Transient public IRatedObject getRatedObject() { return this.assignment; } @Override @Transient public Long getPrefix() { return this.assignment.getPrefix(); } @Override @Transient public ILearningObject getLearningObject() { return this.getAssignment(); } }
LemoProject/lemo2
src/main/java/de/lemo/dms/db/mapping/CourseAssignmentMining.java
Java
gpl-3.0
6,152
#!/usr/bin/python # -*- coding: utf-8 -*- """ This file is part of XBMC Mega Pack Addon. Copyright (C) 2014 Wolverine (xbmcmegapack@gmail.com) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/gpl-3.0.html """ class Countries_Tajikistan(): '''Class that manages this specific menu context.''' def open(self, plugin, menu): menu.add_xplugins(plugin.get_xplugins(dictionaries=["Channels", "Events", "Live", "Movies", "Sports", "TVShows"], countries=["Tajikistan"]))
xbmcmegapack/plugin.video.megapack.dev
resources/lib/menus/home_countries_tajikistan.py
Python
gpl-3.0
1,117
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Migration_modifica_coluna_hologated_null extends CI_Migration { public function up() { $this->dbforge->modify_column('selection_process_user_subscription', [ 'homologated' => ['type' => 'tinyint(1)', 'null' => TRUE, 'default' => NULL] ]); } public function down() { $this->dbforge->modify_column('selection_process_user_subscription', [ 'homologated' => ['type' => 'tinyint(1)', 'null' => FALSE, 'default' => FALSE] ]); } }
Sistema-Integrado-Gestao-Academica/SiGA
application/migrations/162_modifica_coluna_hologated_null.php
PHP
gpl-3.0
581
/** * initSession * * @module :: Policy * @description :: make sure all session related values are properly setup * */ module.exports = function(req, res, next) { // make sure the appdev session obj is created. req.session.appdev = req.session.appdev || ADCore.session.default(); // if this is a socket request, then initialize the socket info: if (req.isSocket) { ADCore.socket.init(req); } // ok, our session is properly setup. next(); };
appdevdesigns/appdev-core
api/policies/initSession.js
JavaScript
gpl-3.0
500
/* * Copyright (C) 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.media.cts; import android.app.Presentation; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.graphics.SurfaceTexture; import android.graphics.Typeface; import android.graphics.drawable.ColorDrawable; import android.hardware.display.DisplayManager; import android.hardware.display.VirtualDisplay; import android.media.MediaCodec; import android.media.MediaCodec.BufferInfo; import android.media.MediaCodecInfo; import android.media.MediaCodecInfo.CodecCapabilities; import android.media.MediaCodecInfo.CodecProfileLevel; import android.media.MediaCodecList; import android.media.MediaFormat; import android.opengl.GLES11Ext; import android.opengl.GLES20; import android.opengl.Matrix; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Looper; import android.os.Message; import android.os.Parcel; import android.test.AndroidTestCase; import android.util.AttributeSet; import android.util.Log; import android.util.Size; import android.view.Display; import android.view.Surface; import android.view.TextureView; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.view.WindowManager; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; import android.media.cts.R; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; /** * Tests to check if MediaCodec encoding works with composition of multiple virtual displays * The test also tries to destroy and create virtual displays repeatedly to * detect any issues. The test itself does not check the output as it is already done in other * tests. */ public class EncodeVirtualDisplayWithCompositionTest extends AndroidTestCase { private static final String TAG = "EncodeVirtualDisplayWithCompositionTest"; private static final boolean DBG = true; private static final String MIME_TYPE = MediaFormat.MIMETYPE_VIDEO_AVC; private static final long DEFAULT_WAIT_TIMEOUT_MS = 3000; private static final long DEFAULT_WAIT_TIMEOUT_US = 3000000; private static final int COLOR_RED = makeColor(100, 0, 0); private static final int COLOR_BLUE = makeColor(0, 100, 0); private static final int COLOR_GREEN = makeColor(0, 0, 100); private static final int COLOR_GREY = makeColor(100, 100, 100); private static final int BITRATE_1080p = 20000000; private static final int BITRATE_720p = 14000000; private static final int BITRATE_800x480 = 14000000; private static final int BITRATE_DEFAULT = 10000000; private static final int IFRAME_INTERVAL = 10; private static final int MAX_NUM_WINDOWS = 3; private static Handler sHandlerForRunOnMain = new Handler(Looper.getMainLooper()); private Surface mEncodingSurface; private OutputSurface mDecodingSurface; private volatile boolean mCodecConfigReceived = false; private volatile boolean mCodecBufferReceived = false; private EncodingHelper mEncodingHelper; private MediaCodec mDecoder; private final ByteBuffer mPixelBuf = ByteBuffer.allocateDirect(4); private volatile boolean mIsQuitting = false; private Throwable mTestException; private VirtualDisplayPresentation mLocalPresentation; private RemoteVirtualDisplayPresentation mRemotePresentation; private ByteBuffer[] mDecoderInputBuffers; /** event listener for test without verifying output */ private EncoderEventListener mEncoderEventListener = new EncoderEventListener() { @Override public void onCodecConfig(ByteBuffer data, MediaCodec.BufferInfo info) { mCodecConfigReceived = true; } @Override public void onBufferReady(ByteBuffer data, MediaCodec.BufferInfo info) { mCodecBufferReceived = true; } @Override public void onError(String errorMessage) { fail(errorMessage); } }; /* TEST_COLORS static initialization; need ARGB for ColorDrawable */ private static int makeColor(int red, int green, int blue) { return 0xff << 24 | (red & 0xff) << 16 | (green & 0xff) << 8 | (blue & 0xff); } public void testVirtualDisplayRecycles() throws Exception { doTestVirtualDisplayRecycles(3); } public void testRendering800x480Locally() throws Throwable { Log.i(TAG, "testRendering800x480Locally"); if (isConcurrentEncodingDecodingSupported(800, 480, BITRATE_800x480)) { runTestRenderingInSeparateThread(800, 480, false, false); } else { Log.i(TAG, "SKIPPING testRendering800x480Locally(): codec not supported"); } } public void testRenderingMaxResolutionLocally() throws Throwable { Log.i(TAG, "testRenderingMaxResolutionLocally"); Size maxRes = checkMaxConcurrentEncodingDecodingResolution(); if (maxRes == null) { Log.i(TAG, "SKIPPING testRenderingMaxResolutionLocally(): codec not supported"); } else { Log.w(TAG, "Trying resolution " + maxRes); runTestRenderingInSeparateThread(maxRes.getWidth(), maxRes.getHeight(), false, false); } } public void testRendering800x480Remotely() throws Throwable { Log.i(TAG, "testRendering800x480Remotely"); if (isConcurrentEncodingDecodingSupported(800, 480, BITRATE_800x480)) { runTestRenderingInSeparateThread(800, 480, true, false); } else { Log.i(TAG, "SKIPPING testRendering800x480Remotely(): codec not supported"); } } public void testRenderingMaxResolutionRemotely() throws Throwable { Log.i(TAG, "testRenderingMaxResolutionRemotely"); Size maxRes = checkMaxConcurrentEncodingDecodingResolution(); if (maxRes == null) { Log.i(TAG, "SKIPPING testRenderingMaxResolutionRemotely(): codec not supported"); } else { Log.w(TAG, "Trying resolution " + maxRes); runTestRenderingInSeparateThread(maxRes.getWidth(), maxRes.getHeight(), true, false); } } public void testRendering800x480RemotelyWith3Windows() throws Throwable { Log.i(TAG, "testRendering800x480RemotelyWith3Windows"); if (isConcurrentEncodingDecodingSupported(800, 480, BITRATE_800x480)) { runTestRenderingInSeparateThread(800, 480, true, true); } else { Log.i(TAG, "SKIPPING testRendering800x480RemotelyWith3Windows(): codec not supported"); } } public void testRendering800x480LocallyWith3Windows() throws Throwable { Log.i(TAG, "testRendering800x480LocallyWith3Windows"); if (isConcurrentEncodingDecodingSupported(800, 480, BITRATE_800x480)) { runTestRenderingInSeparateThread(800, 480, false, true); } else { Log.i(TAG, "SKIPPING testRendering800x480LocallyWith3Windows(): codec not supported"); } } /** * Run rendering test in a separate thread. This is necessary as {@link OutputSurface} requires * constructing it in a non-test thread. * @param w * @param h * @throws Exception */ private void runTestRenderingInSeparateThread(final int w, final int h, final boolean runRemotely, final boolean multipleWindows) throws Throwable { mTestException = null; Thread renderingThread = new Thread(new Runnable() { public void run() { try { doTestRenderingOutput(w, h, runRemotely, multipleWindows); } catch (Throwable t) { t.printStackTrace(); mTestException = t; } } }); renderingThread.start(); renderingThread.join(60000); assertTrue(!renderingThread.isAlive()); if (mTestException != null) { throw mTestException; } } private void doTestRenderingOutput(int w, int h, boolean runRemotely, boolean multipleWindows) throws Throwable { if (DBG) { Log.i(TAG, "doTestRenderingOutput for w:" + w + " h:" + h); } try { mIsQuitting = false; mDecoder = MediaCodec.createDecoderByType(MIME_TYPE); MediaFormat decoderFormat = MediaFormat.createVideoFormat(MIME_TYPE, w, h); mDecodingSurface = new OutputSurface(w, h); mDecoder.configure(decoderFormat, mDecodingSurface.getSurface(), null, 0); mDecoder.start(); mDecoderInputBuffers = mDecoder.getInputBuffers(); mEncodingHelper = new EncodingHelper(); mEncodingSurface = mEncodingHelper.startEncoding(w, h, new EncoderEventListener() { @Override public void onCodecConfig(ByteBuffer data, BufferInfo info) { if (DBG) { Log.i(TAG, "onCodecConfig l:" + info.size); } handleEncodedData(data, info); } @Override public void onBufferReady(ByteBuffer data, BufferInfo info) { if (DBG) { Log.i(TAG, "onBufferReady l:" + info.size); } handleEncodedData(data, info); } @Override public void onError(String errorMessage) { fail(errorMessage); } private void handleEncodedData(ByteBuffer data, BufferInfo info) { if (mIsQuitting) { if (DBG) { Log.i(TAG, "ignore data as test is quitting"); } return; } int inputBufferIndex = mDecoder.dequeueInputBuffer(DEFAULT_WAIT_TIMEOUT_US); if (inputBufferIndex < 0) { if (DBG) { Log.i(TAG, "dequeueInputBuffer returned:" + inputBufferIndex); } return; } assertTrue(inputBufferIndex >= 0); ByteBuffer inputBuffer = mDecoderInputBuffers[inputBufferIndex]; inputBuffer.clear(); inputBuffer.put(data); mDecoder.queueInputBuffer(inputBufferIndex, 0, info.size, info.presentationTimeUs, info.flags); } }); GlCompositor compositor = new GlCompositor(); if (DBG) { Log.i(TAG, "start composition"); } compositor.startComposition(mEncodingSurface, w, h, multipleWindows ? 3 : 1); if (DBG) { Log.i(TAG, "create display"); } Renderer renderer = null; if (runRemotely) { mRemotePresentation = new RemoteVirtualDisplayPresentation(getContext(), compositor.getWindowSurface(multipleWindows? 1 : 0), w, h); mRemotePresentation.connect(); mRemotePresentation.start(); renderer = mRemotePresentation; } else { mLocalPresentation = new VirtualDisplayPresentation(getContext(), compositor.getWindowSurface(multipleWindows? 1 : 0), w, h); mLocalPresentation.createVirtualDisplay(); mLocalPresentation.createPresentation(); renderer = mLocalPresentation; } if (DBG) { Log.i(TAG, "start rendering and check"); } renderColorAndCheckResult(renderer, w, h, COLOR_RED); renderColorAndCheckResult(renderer, w, h, COLOR_BLUE); renderColorAndCheckResult(renderer, w, h, COLOR_GREEN); renderColorAndCheckResult(renderer, w, h, COLOR_GREY); mIsQuitting = true; if (runRemotely) { mRemotePresentation.disconnect(); } else { mLocalPresentation.dismissPresentation(); mLocalPresentation.destroyVirtualDisplay(); } compositor.stopComposition(); } finally { if (mEncodingHelper != null) { mEncodingHelper.stopEncoding(); mEncodingHelper = null; } if (mDecoder != null) { mDecoder.stop(); mDecoder.release(); mDecoder = null; } if (mDecodingSurface != null) { mDecodingSurface.release(); mDecodingSurface = null; } } } private static final int NUM_MAX_RETRY = 120; private static final int IMAGE_WAIT_TIMEOUT_MS = 1000; private void renderColorAndCheckResult(Renderer renderer, int w, int h, int color) throws Exception { BufferInfo info = new BufferInfo(); for (int i = 0; i < NUM_MAX_RETRY; i++) { renderer.doRendering(color); int bufferIndex = mDecoder.dequeueOutputBuffer(info, DEFAULT_WAIT_TIMEOUT_US); if (DBG) { Log.i(TAG, "decoder dequeueOutputBuffer returned " + bufferIndex); } if (bufferIndex < 0) { continue; } mDecoder.releaseOutputBuffer(bufferIndex, true); if (mDecodingSurface.checkForNewImage(IMAGE_WAIT_TIMEOUT_MS)) { mDecodingSurface.drawImage(); if (checkSurfaceFrameColor(w, h, color)) { Log.i(TAG, "color " + Integer.toHexString(color) + " matched"); return; } } else if(DBG) { Log.i(TAG, "no rendering yet"); } } fail("Color did not match"); } private boolean checkSurfaceFrameColor(int w, int h, int color) { // Read a pixel from the center of the surface. Might want to read from multiple points // and average them together. int x = w / 2; int y = h / 2; GLES20.glReadPixels(x, y, 1, 1, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, mPixelBuf); int r = mPixelBuf.get(0) & 0xff; int g = mPixelBuf.get(1) & 0xff; int b = mPixelBuf.get(2) & 0xff; int redExpected = (color >> 16) & 0xff; int greenExpected = (color >> 8) & 0xff; int blueExpected = color & 0xff; if (approxEquals(redExpected, r) && approxEquals(greenExpected, g) && approxEquals(blueExpected, b)) { return true; } Log.i(TAG, "expected 0x" + Integer.toHexString(color) + " got 0x" + Integer.toHexString(makeColor(r, g, b))); return false; } /** * Determines if two color values are approximately equal. */ private static boolean approxEquals(int expected, int actual) { final int MAX_DELTA = 4; return Math.abs(expected - actual) <= MAX_DELTA; } private static final int NUM_CODEC_CREATION = 5; private static final int NUM_DISPLAY_CREATION = 10; private static final int NUM_RENDERING = 10; private void doTestVirtualDisplayRecycles(int numDisplays) throws Exception { Size maxSize = getMaxSupportedEncoderSize(); if (maxSize == null) { Log.i(TAG, "no codec found, skipping"); return; } VirtualDisplayPresentation[] virtualDisplays = new VirtualDisplayPresentation[numDisplays]; for (int i = 0; i < NUM_CODEC_CREATION; i++) { mCodecConfigReceived = false; mCodecBufferReceived = false; if (DBG) { Log.i(TAG, "start encoding"); } EncodingHelper encodingHelper = new EncodingHelper(); mEncodingSurface = encodingHelper.startEncoding(maxSize.getWidth(), maxSize.getHeight(), mEncoderEventListener); GlCompositor compositor = new GlCompositor(); if (DBG) { Log.i(TAG, "start composition"); } compositor.startComposition(mEncodingSurface, maxSize.getWidth(), maxSize.getHeight(), numDisplays); for (int j = 0; j < NUM_DISPLAY_CREATION; j++) { if (DBG) { Log.i(TAG, "create display"); } for (int k = 0; k < numDisplays; k++) { virtualDisplays[k] = new VirtualDisplayPresentation(getContext(), compositor.getWindowSurface(k), maxSize.getWidth()/numDisplays, maxSize.getHeight()); virtualDisplays[k].createVirtualDisplay(); virtualDisplays[k].createPresentation(); } if (DBG) { Log.i(TAG, "start rendering"); } for (int k = 0; k < NUM_RENDERING; k++) { for (int l = 0; l < numDisplays; l++) { virtualDisplays[l].doRendering(COLOR_RED); } // do not care how many frames are actually rendered. Thread.sleep(1); } for (int k = 0; k < numDisplays; k++) { virtualDisplays[k].dismissPresentation(); virtualDisplays[k].destroyVirtualDisplay(); } compositor.recreateWindows(); } if (DBG) { Log.i(TAG, "stop composition"); } compositor.stopComposition(); if (DBG) { Log.i(TAG, "stop encoding"); } encodingHelper.stopEncoding(); assertTrue(mCodecConfigReceived); assertTrue(mCodecBufferReceived); } } interface EncoderEventListener { public void onCodecConfig(ByteBuffer data, MediaCodec.BufferInfo info); public void onBufferReady(ByteBuffer data, MediaCodec.BufferInfo info); public void onError(String errorMessage); } private class EncodingHelper { private MediaCodec mEncoder; private volatile boolean mStopEncoding = false; private EncoderEventListener mEventListener; private int mW; private int mH; private Thread mEncodingThread; private Surface mEncodingSurface; private Semaphore mInitCompleted = new Semaphore(0); Surface startEncoding(int w, int h, EncoderEventListener eventListener) { mStopEncoding = false; mW = w; mH = h; mEventListener = eventListener; mEncodingThread = new Thread(new Runnable() { @Override public void run() { try { doEncoding(); } catch (Exception e) { e.printStackTrace(); mEventListener.onError(e.toString()); } } }); mEncodingThread.start(); try { if (DBG) { Log.i(TAG, "wait for encoder init"); } mInitCompleted.acquire(); if (DBG) { Log.i(TAG, "wait for encoder done"); } } catch (InterruptedException e) { fail("should not happen"); } return mEncodingSurface; } void stopEncoding() { try { mStopEncoding = true; mEncodingThread.join(); } catch(InterruptedException e) { // just ignore } finally { mEncodingThread = null; } } private void doEncoding() throws Exception { final int TIMEOUT_USEC_NORMAL = 1000000; MediaFormat format = MediaFormat.createVideoFormat(MIME_TYPE, mW, mH); format.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface); int bitRate = BITRATE_DEFAULT; if (mW == 1920 && mH == 1080) { bitRate = BITRATE_1080p; } else if (mW == 1280 && mH == 720) { bitRate = BITRATE_720p; } else if (mW == 800 && mH == 480) { bitRate = BITRATE_800x480; } format.setInteger(MediaFormat.KEY_BIT_RATE, bitRate); format.setInteger(MediaFormat.KEY_FRAME_RATE, 30); format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, IFRAME_INTERVAL); MediaCodecList mcl = new MediaCodecList(MediaCodecList.REGULAR_CODECS); String codecName = null; if ((codecName = mcl.findEncoderForFormat(format)) == null) { throw new RuntimeException("encoder "+ MIME_TYPE + " not support : " + format.toString()); } mEncoder = MediaCodec.createByCodecName(codecName); mEncoder.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE); mEncodingSurface = mEncoder.createInputSurface(); mEncoder.start(); mInitCompleted.release(); if (DBG) { Log.i(TAG, "starting encoder"); } try { ByteBuffer[] encoderOutputBuffers = mEncoder.getOutputBuffers(); MediaCodec.BufferInfo info = new MediaCodec.BufferInfo(); while (!mStopEncoding) { int index = mEncoder.dequeueOutputBuffer(info, TIMEOUT_USEC_NORMAL); if (DBG) { Log.i(TAG, "encoder dequeOutputBuffer returned " + index); } if (index >= 0) { if ((info.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) != 0) { Log.i(TAG, "codec config data"); ByteBuffer encodedData = encoderOutputBuffers[index]; encodedData.position(info.offset); encodedData.limit(info.offset + info.size); mEventListener.onCodecConfig(encodedData, info); mEncoder.releaseOutputBuffer(index, false); } else if ((info.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) { Log.i(TAG, "EOS, stopping encoding"); break; } else { ByteBuffer encodedData = encoderOutputBuffers[index]; encodedData.position(info.offset); encodedData.limit(info.offset + info.size); mEventListener.onBufferReady(encodedData, info); mEncoder.releaseOutputBuffer(index, false); } } else if (index == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED){ Log.i(TAG, "output buffer changed"); encoderOutputBuffers = mEncoder.getOutputBuffers(); } } } catch (Exception e) { e.printStackTrace(); throw e; } finally { mEncoder.stop(); mEncoder.release(); mEncoder = null; mEncodingSurface.release(); mEncodingSurface = null; } } } /** * Handles composition of multiple SurfaceTexture into a single Surface */ private class GlCompositor implements SurfaceTexture.OnFrameAvailableListener { private Surface mSurface; private int mWidth; private int mHeight; private volatile int mNumWindows; private GlWindow mTopWindow; private Thread mCompositionThread; private Semaphore mStartCompletionSemaphore; private Semaphore mRecreationCompletionSemaphore; private Looper mLooper; private Handler mHandler; private InputSurface mEglHelper; private int mGlProgramId = 0; private int mGluMVPMatrixHandle; private int mGluSTMatrixHandle; private int mGlaPositionHandle; private int mGlaTextureHandle; private float[] mMVPMatrix = new float[16]; private TopWindowVirtualDisplayPresentation mTopPresentation; private static final String VERTEX_SHADER = "uniform mat4 uMVPMatrix;\n" + "uniform mat4 uSTMatrix;\n" + "attribute vec4 aPosition;\n" + "attribute vec4 aTextureCoord;\n" + "varying vec2 vTextureCoord;\n" + "void main() {\n" + " gl_Position = uMVPMatrix * aPosition;\n" + " vTextureCoord = (uSTMatrix * aTextureCoord).xy;\n" + "}\n"; private static final String FRAGMENT_SHADER = "#extension GL_OES_EGL_image_external : require\n" + "precision mediump float;\n" + "varying vec2 vTextureCoord;\n" + "uniform samplerExternalOES sTexture;\n" + "void main() {\n" + " gl_FragColor = texture2D(sTexture, vTextureCoord);\n" + "}\n"; void startComposition(Surface surface, int w, int h, int numWindows) throws Exception { mSurface = surface; mWidth = w; mHeight = h; mNumWindows = numWindows; mCompositionThread = new Thread(new CompositionRunnable()); mStartCompletionSemaphore = new Semaphore(0); mCompositionThread.start(); waitForStartCompletion(); } void stopComposition() { try { if (mLooper != null) { mLooper.quit(); mCompositionThread.join(); } } catch (InterruptedException e) { // don't care } mCompositionThread = null; mSurface = null; mStartCompletionSemaphore = null; } Surface getWindowSurface(int windowIndex) { return mTopPresentation.getSurface(windowIndex); } void recreateWindows() throws Exception { mRecreationCompletionSemaphore = new Semaphore(0); Message msg = mHandler.obtainMessage(CompositionHandler.DO_RECREATE_WINDOWS); mHandler.sendMessage(msg); if(!mRecreationCompletionSemaphore.tryAcquire(DEFAULT_WAIT_TIMEOUT_MS, TimeUnit.MILLISECONDS)) { fail("recreation timeout"); } mTopPresentation.waitForSurfaceReady(DEFAULT_WAIT_TIMEOUT_MS); } @Override public void onFrameAvailable(SurfaceTexture surface) { if (DBG) { Log.i(TAG, "onFrameAvailable " + surface); } GlWindow w = mTopWindow; if (w != null) { w.markTextureUpdated(); requestUpdate(); } else { Log.w(TAG, "top window gone"); } } private void requestUpdate() { Thread compositionThread = mCompositionThread; if (compositionThread == null || !compositionThread.isAlive()) { return; } Message msg = mHandler.obtainMessage(CompositionHandler.DO_RENDERING); mHandler.sendMessage(msg); } private int loadShader(int shaderType, String source) throws GlException { int shader = GLES20.glCreateShader(shaderType); checkGlError("glCreateShader type=" + shaderType); GLES20.glShaderSource(shader, source); GLES20.glCompileShader(shader); int[] compiled = new int[1]; GLES20.glGetShaderiv(shader, GLES20.GL_COMPILE_STATUS, compiled, 0); if (compiled[0] == 0) { Log.e(TAG, "Could not compile shader " + shaderType + ":"); Log.e(TAG, " " + GLES20.glGetShaderInfoLog(shader)); GLES20.glDeleteShader(shader); shader = 0; } return shader; } private int createProgram(String vertexSource, String fragmentSource) throws GlException { int vertexShader = loadShader(GLES20.GL_VERTEX_SHADER, vertexSource); if (vertexShader == 0) { return 0; } int pixelShader = loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentSource); if (pixelShader == 0) { return 0; } int program = GLES20.glCreateProgram(); checkGlError("glCreateProgram"); if (program == 0) { Log.e(TAG, "Could not create program"); } GLES20.glAttachShader(program, vertexShader); checkGlError("glAttachShader"); GLES20.glAttachShader(program, pixelShader); checkGlError("glAttachShader"); GLES20.glLinkProgram(program); int[] linkStatus = new int[1]; GLES20.glGetProgramiv(program, GLES20.GL_LINK_STATUS, linkStatus, 0); if (linkStatus[0] != GLES20.GL_TRUE) { Log.e(TAG, "Could not link program: "); Log.e(TAG, GLES20.glGetProgramInfoLog(program)); GLES20.glDeleteProgram(program); program = 0; } return program; } private void initGl() throws GlException { mEglHelper = new InputSurface(mSurface); mEglHelper.makeCurrent(); mGlProgramId = createProgram(VERTEX_SHADER, FRAGMENT_SHADER); mGlaPositionHandle = GLES20.glGetAttribLocation(mGlProgramId, "aPosition"); checkGlError("glGetAttribLocation aPosition"); if (mGlaPositionHandle == -1) { throw new RuntimeException("Could not get attrib location for aPosition"); } mGlaTextureHandle = GLES20.glGetAttribLocation(mGlProgramId, "aTextureCoord"); checkGlError("glGetAttribLocation aTextureCoord"); if (mGlaTextureHandle == -1) { throw new RuntimeException("Could not get attrib location for aTextureCoord"); } mGluMVPMatrixHandle = GLES20.glGetUniformLocation(mGlProgramId, "uMVPMatrix"); checkGlError("glGetUniformLocation uMVPMatrix"); if (mGluMVPMatrixHandle == -1) { throw new RuntimeException("Could not get attrib location for uMVPMatrix"); } mGluSTMatrixHandle = GLES20.glGetUniformLocation(mGlProgramId, "uSTMatrix"); checkGlError("glGetUniformLocation uSTMatrix"); if (mGluSTMatrixHandle == -1) { throw new RuntimeException("Could not get attrib location for uSTMatrix"); } Matrix.setIdentityM(mMVPMatrix, 0); Log.i(TAG, "initGl w:" + mWidth + " h:" + mHeight); GLES20.glViewport(0, 0, mWidth, mHeight); float[] vMatrix = new float[16]; float[] projMatrix = new float[16]; // max window is from (0,0) to (mWidth - 1, mHeight - 1) float wMid = mWidth / 2f; float hMid = mHeight / 2f; // look from positive z to hide windows in lower z Matrix.setLookAtM(vMatrix, 0, wMid, hMid, 5f, wMid, hMid, 0f, 0f, 1.0f, 0.0f); Matrix.orthoM(projMatrix, 0, -wMid, wMid, -hMid, hMid, 1, 10); Matrix.multiplyMM(mMVPMatrix, 0, projMatrix, 0, vMatrix, 0); createWindows(); } private void createWindows() throws GlException { mTopWindow = new GlWindow(this, 0, 0, mWidth, mHeight); mTopWindow.init(); mTopPresentation = new TopWindowVirtualDisplayPresentation(mContext, mTopWindow.getSurface(), mWidth, mHeight, mNumWindows); mTopPresentation.createVirtualDisplay(); mTopPresentation.createPresentation(); ((TopWindowPresentation) mTopPresentation.getPresentation()).populateWindows(); } private void cleanupGl() { if (mTopPresentation != null) { mTopPresentation.dismissPresentation(); mTopPresentation.destroyVirtualDisplay(); mTopPresentation = null; } if (mTopWindow != null) { mTopWindow.cleanup(); mTopWindow = null; } if (mEglHelper != null) { mEglHelper.release(); mEglHelper = null; } } private void doGlRendering() throws GlException { if (DBG) { Log.i(TAG, "doGlRendering"); } mTopWindow.updateTexImageIfNecessary(); GLES20.glClearColor(0.0f, 1.0f, 0.0f, 1.0f); GLES20.glClear(GLES20.GL_DEPTH_BUFFER_BIT | GLES20.GL_COLOR_BUFFER_BIT); GLES20.glUseProgram(mGlProgramId); GLES20.glUniformMatrix4fv(mGluMVPMatrixHandle, 1, false, mMVPMatrix, 0); mTopWindow.onDraw(mGluSTMatrixHandle, mGlaPositionHandle, mGlaTextureHandle); checkGlError("window draw"); if (DBG) { final IntBuffer pixels = IntBuffer.allocate(1); GLES20.glReadPixels(mWidth / 2, mHeight / 2, 1, 1, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, pixels); Log.i(TAG, "glReadPixels returned 0x" + Integer.toHexString(pixels.get(0))); } mEglHelper.swapBuffers(); } private void doRecreateWindows() throws GlException { mTopPresentation.dismissPresentation(); mTopPresentation.destroyVirtualDisplay(); mTopWindow.cleanup(); createWindows(); mRecreationCompletionSemaphore.release(); } private void waitForStartCompletion() throws Exception { if (!mStartCompletionSemaphore.tryAcquire(DEFAULT_WAIT_TIMEOUT_MS, TimeUnit.MILLISECONDS)) { fail("start timeout"); } mStartCompletionSemaphore = null; mTopPresentation.waitForSurfaceReady(DEFAULT_WAIT_TIMEOUT_MS); } private class CompositionRunnable implements Runnable { @Override public void run() { try { Looper.prepare(); mLooper = Looper.myLooper(); mHandler = new CompositionHandler(); initGl(); // init done mStartCompletionSemaphore.release(); Looper.loop(); } catch (GlException e) { e.printStackTrace(); fail("got gl exception"); } finally { cleanupGl(); mHandler = null; mLooper = null; } } } private class CompositionHandler extends Handler { private static final int DO_RENDERING = 1; private static final int DO_RECREATE_WINDOWS = 2; @Override public void handleMessage(Message msg) { try { switch(msg.what) { case DO_RENDERING: { doGlRendering(); } break; case DO_RECREATE_WINDOWS: { doRecreateWindows(); } break; } } catch (GlException e) { //ignore as this can happen during tearing down } } } private class GlWindow { private static final int FLOAT_SIZE_BYTES = 4; private static final int TRIANGLE_VERTICES_DATA_STRIDE_BYTES = 5 * FLOAT_SIZE_BYTES; private static final int TRIANGLE_VERTICES_DATA_POS_OFFSET = 0; private static final int TRIANGLE_VERTICES_DATA_UV_OFFSET = 3; private int mBlX; private int mBlY; private int mWidth; private int mHeight; private int mTextureId = 0; // 0 is invalid private volatile SurfaceTexture mSurfaceTexture; private volatile Surface mSurface; private FloatBuffer mVerticesData; private float[] mSTMatrix = new float[16]; private AtomicInteger mNumTextureUpdated = new AtomicInteger(0); private GlCompositor mCompositor; /** * @param blX X coordinate of bottom-left point of window * @param blY Y coordinate of bottom-left point of window * @param w window width * @param h window height */ public GlWindow(GlCompositor compositor, int blX, int blY, int w, int h) { mCompositor = compositor; mBlX = blX; mBlY = blY; mWidth = w; mHeight = h; int trX = blX + w; int trY = blY + h; float[] vertices = new float[] { // x, y, z, u, v mBlX, mBlY, 0, 0, 0, trX, mBlY, 0, 1, 0, mBlX, trY, 0, 0, 1, trX, trY, 0, 1, 1 }; Log.i(TAG, "create window " + this + " blX:" + mBlX + " blY:" + mBlY + " trX:" + trX + " trY:" + trY); mVerticesData = ByteBuffer.allocateDirect( vertices.length * FLOAT_SIZE_BYTES) .order(ByteOrder.nativeOrder()).asFloatBuffer(); mVerticesData.put(vertices).position(0); } /** * initialize the window for composition. counter-part is cleanup() * @throws GlException */ public void init() throws GlException { int[] textures = new int[1]; GLES20.glGenTextures(1, textures, 0); mTextureId = textures[0]; GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, mTextureId); checkGlError("glBindTexture mTextureID"); GLES20.glTexParameterf(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_NEAREST); GLES20.glTexParameterf(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_NEAREST); GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE); GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE); checkGlError("glTexParameter"); mSurfaceTexture = new SurfaceTexture(mTextureId); mSurfaceTexture.setDefaultBufferSize(mWidth, mHeight); mSurface = new Surface(mSurfaceTexture); mSurfaceTexture.setOnFrameAvailableListener(mCompositor); } public void cleanup() { mNumTextureUpdated.set(0); if (mTextureId != 0) { int[] textures = new int[] { mTextureId }; GLES20.glDeleteTextures(1, textures, 0); } GLES20.glFinish(); if (mSurface != null) { mSurface.release(); mSurface = null; } if (mSurfaceTexture != null) { mSurfaceTexture.release(); mSurfaceTexture = null; } } /** * make texture as updated so that it can be updated in the next rendering. */ public void markTextureUpdated() { mNumTextureUpdated.incrementAndGet(); } /** * update texture for rendering if it is updated. */ public void updateTexImageIfNecessary() { int numTextureUpdated = mNumTextureUpdated.getAndDecrement(); if (numTextureUpdated > 0) { if (DBG) { Log.i(TAG, "updateTexImageIfNecessary " + this); } mSurfaceTexture.updateTexImage(); mSurfaceTexture.getTransformMatrix(mSTMatrix); } if (numTextureUpdated < 0) { fail("should not happen"); } } /** * draw the window. It will not be drawn at all if the window is not visible. * @param uSTMatrixHandle shader handler for the STMatrix for texture coordinates * mapping * @param aPositionHandle shader handle for vertex position. * @param aTextureHandle shader handle for texture */ public void onDraw(int uSTMatrixHandle, int aPositionHandle, int aTextureHandle) { GLES20.glActiveTexture(GLES20.GL_TEXTURE0); GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, mTextureId); mVerticesData.position(TRIANGLE_VERTICES_DATA_POS_OFFSET); GLES20.glVertexAttribPointer(aPositionHandle, 3, GLES20.GL_FLOAT, false, TRIANGLE_VERTICES_DATA_STRIDE_BYTES, mVerticesData); GLES20.glEnableVertexAttribArray(aPositionHandle); mVerticesData.position(TRIANGLE_VERTICES_DATA_UV_OFFSET); GLES20.glVertexAttribPointer(aTextureHandle, 2, GLES20.GL_FLOAT, false, TRIANGLE_VERTICES_DATA_STRIDE_BYTES, mVerticesData); GLES20.glEnableVertexAttribArray(aTextureHandle); GLES20.glUniformMatrix4fv(uSTMatrixHandle, 1, false, mSTMatrix, 0); GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4); } public SurfaceTexture getSurfaceTexture() { return mSurfaceTexture; } public Surface getSurface() { return mSurface; } } } static void checkGlError(String op) throws GlException { int error; while ((error = GLES20.glGetError()) != GLES20.GL_NO_ERROR) { Log.e(TAG, op + ": glError " + error); throw new GlException(op + ": glError " + error); } } public static class GlException extends Exception { public GlException(String msg) { super(msg); } } private interface Renderer { void doRendering(final int color) throws Exception; } private static class VirtualDisplayPresentation implements Renderer { protected final Context mContext; protected final Surface mSurface; protected final int mWidth; protected final int mHeight; protected VirtualDisplay mVirtualDisplay; protected TestPresentationBase mPresentation; private final DisplayManager mDisplayManager; VirtualDisplayPresentation(Context context, Surface surface, int w, int h) { mContext = context; mSurface = surface; mWidth = w; mHeight = h; mDisplayManager = (DisplayManager)context.getSystemService(Context.DISPLAY_SERVICE); } void createVirtualDisplay() { runOnMainSync(new Runnable() { @Override public void run() { mVirtualDisplay = mDisplayManager.createVirtualDisplay( TAG, mWidth, mHeight, 200, mSurface, DisplayManager.VIRTUAL_DISPLAY_FLAG_OWN_CONTENT_ONLY | DisplayManager.VIRTUAL_DISPLAY_FLAG_PRESENTATION); } }); } void destroyVirtualDisplay() { runOnMainSync(new Runnable() { @Override public void run() { mVirtualDisplay.release(); } }); } void createPresentation() { runOnMainSync(new Runnable() { @Override public void run() { mPresentation = doCreatePresentation(); mPresentation.show(); } }); } protected TestPresentationBase doCreatePresentation() { return new TestPresentation(mContext, mVirtualDisplay.getDisplay()); } TestPresentationBase getPresentation() { return mPresentation; } void dismissPresentation() { runOnMainSync(new Runnable() { @Override public void run() { mPresentation.dismiss(); } }); } @Override public void doRendering(final int color) throws Exception { runOnMainSync(new Runnable() { @Override public void run() { mPresentation.doRendering(color); } }); } } private static class TestPresentationBase extends Presentation { public TestPresentationBase(Context outerContext, Display display) { // This theme is required to prevent an extra view from obscuring the presentation super(outerContext, display, android.R.style.Theme_Holo_Light_NoActionBar_TranslucentDecor); getWindow().setType(WindowManager.LayoutParams.TYPE_PRIVATE_PRESENTATION); getWindow().addFlags(WindowManager.LayoutParams.FLAG_LOCAL_FOCUS_MODE); getWindow().addFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED); } public void doRendering(int color) { // to be implemented by child } } private static class TestPresentation extends TestPresentationBase { private ImageView mImageView; public TestPresentation(Context outerContext, Display display) { super(outerContext, display); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mImageView = new ImageView(getContext()); mImageView.setImageDrawable(new ColorDrawable(COLOR_RED)); mImageView.setLayoutParams(new LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); setContentView(mImageView); } public void doRendering(int color) { if (DBG) { Log.i(TAG, "doRendering " + Integer.toHexString(color)); } mImageView.setImageDrawable(new ColorDrawable(color)); } } private static class TopWindowPresentation extends TestPresentationBase { private FrameLayout[] mWindowsLayout = new FrameLayout[MAX_NUM_WINDOWS]; private CompositionTextureView[] mWindows = new CompositionTextureView[MAX_NUM_WINDOWS]; private final int mNumWindows; private final Semaphore mWindowWaitSemaphore = new Semaphore(0); public TopWindowPresentation(int numWindows, Context outerContext, Display display) { super(outerContext, display); mNumWindows = numWindows; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (DBG) { Log.i(TAG, "TopWindowPresentation onCreate, numWindows " + mNumWindows); } setContentView(R.layout.composition_layout); mWindowsLayout[0] = (FrameLayout) findViewById(R.id.window0); mWindowsLayout[1] = (FrameLayout) findViewById(R.id.window1); mWindowsLayout[2] = (FrameLayout) findViewById(R.id.window2); } public void populateWindows() { runOnMain(new Runnable() { public void run() { for (int i = 0; i < mNumWindows; i++) { mWindows[i] = new CompositionTextureView(getContext()); mWindows[i].setLayoutParams(new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); mWindowsLayout[i].setVisibility(View.VISIBLE); mWindowsLayout[i].addView(mWindows[i]); mWindows[i].startListening(); } mWindowWaitSemaphore.release(); } }); } public void waitForSurfaceReady(long timeoutMs) throws Exception { mWindowWaitSemaphore.tryAcquire(DEFAULT_WAIT_TIMEOUT_MS, TimeUnit.MILLISECONDS); for (int i = 0; i < mNumWindows; i++) { if(!mWindows[i].waitForSurfaceReady(timeoutMs)) { fail("surface wait timeout"); } } } public Surface getSurface(int windowIndex) { Surface surface = mWindows[windowIndex].getSurface(); assertNotNull(surface); return surface; } } private static class TopWindowVirtualDisplayPresentation extends VirtualDisplayPresentation { private final int mNumWindows; TopWindowVirtualDisplayPresentation(Context context, Surface surface, int w, int h, int numWindows) { super(context, surface, w, h); assertNotNull(surface); mNumWindows = numWindows; } void waitForSurfaceReady(long timeoutMs) throws Exception { ((TopWindowPresentation) mPresentation).waitForSurfaceReady(timeoutMs); } Surface getSurface(int windowIndex) { return ((TopWindowPresentation) mPresentation).getSurface(windowIndex); } protected TestPresentationBase doCreatePresentation() { return new TopWindowPresentation(mNumWindows, mContext, mVirtualDisplay.getDisplay()); } } private static class RemoteVirtualDisplayPresentation implements Renderer { /** argument: Surface, int w, int h, return none */ private static final int BINDER_CMD_START = IBinder.FIRST_CALL_TRANSACTION; /** argument: int color, return none */ private static final int BINDER_CMD_RENDER = IBinder.FIRST_CALL_TRANSACTION + 1; private final Context mContext; private final Surface mSurface; private final int mWidth; private final int mHeight; private IBinder mService; private final Semaphore mConnectionWait = new Semaphore(0); private final ServiceConnection mConnection = new ServiceConnection() { public void onServiceConnected(ComponentName arg0, IBinder arg1) { mService = arg1; mConnectionWait.release(); } public void onServiceDisconnected(ComponentName arg0) { //ignore } }; RemoteVirtualDisplayPresentation(Context context, Surface surface, int w, int h) { mContext = context; mSurface = surface; mWidth = w; mHeight = h; } void connect() throws Exception { Intent intent = new Intent(); intent.setClassName("android.media.cts", "android.media.cts.RemoteVirtualDisplayService"); mContext.bindService(intent, mConnection, Context.BIND_AUTO_CREATE); if (!mConnectionWait.tryAcquire(DEFAULT_WAIT_TIMEOUT_MS, TimeUnit.MILLISECONDS)) { fail("cannot bind to service"); } } void disconnect() { mContext.unbindService(mConnection); } void start() throws Exception { Parcel parcel = Parcel.obtain(); mSurface.writeToParcel(parcel, 0); parcel.writeInt(mWidth); parcel.writeInt(mHeight); mService.transact(BINDER_CMD_START, parcel, null, 0); } @Override public void doRendering(int color) throws Exception { Parcel parcel = Parcel.obtain(); parcel.writeInt(color); mService.transact(BINDER_CMD_RENDER, parcel, null, 0); } } private static Size getMaxSupportedEncoderSize() { final Size[] standardSizes = new Size[] { new Size(1920, 1080), new Size(1280, 720), new Size(720, 480), new Size(352, 576) }; MediaCodecList mcl = new MediaCodecList(MediaCodecList.REGULAR_CODECS); for (Size sz : standardSizes) { MediaFormat format = MediaFormat.createVideoFormat( MIME_TYPE, sz.getWidth(), sz.getHeight()); format.setInteger(MediaFormat.KEY_FRAME_RATE, 15); // require at least 15fps if (mcl.findEncoderForFormat(format) != null) { return sz; } } return null; } /** * Check maximum concurrent encoding / decoding resolution allowed. * Some H/Ws cannot support maximum resolution reported in encoder if decoder is running * at the same time. * Check is done for 4 different levels: 1080p, 720p, 800x480, 480p * (The last one is required by CDD.) */ private Size checkMaxConcurrentEncodingDecodingResolution() { if (isConcurrentEncodingDecodingSupported(1920, 1080, BITRATE_1080p)) { return new Size(1920, 1080); } else if (isConcurrentEncodingDecodingSupported(1280, 720, BITRATE_720p)) { return new Size(1280, 720); } else if (isConcurrentEncodingDecodingSupported(800, 480, BITRATE_800x480)) { return new Size(800, 480); } else if (isConcurrentEncodingDecodingSupported(720, 480, BITRATE_DEFAULT)) { return new Size(720, 480); } Log.i(TAG, "SKIPPING test: concurrent encoding and decoding is not supported"); return null; } private boolean isConcurrentEncodingDecodingSupported(int w, int h, int bitRate) { MediaCodecList mcl = new MediaCodecList(MediaCodecList.REGULAR_CODECS); MediaFormat testFormat = MediaFormat.createVideoFormat(MIME_TYPE, w, h); testFormat.setInteger(MediaFormat.KEY_BIT_RATE, bitRate); testFormat.setInteger(MediaFormat.KEY_FRAME_RATE, 30); if (mcl.findDecoderForFormat(testFormat) == null || mcl.findEncoderForFormat(testFormat) == null) { return false; } MediaCodec decoder = null; OutputSurface decodingSurface = null; MediaCodec encoder = null; Surface encodingSurface = null; try { decoder = MediaCodec.createDecoderByType(MIME_TYPE); MediaFormat decoderFormat = MediaFormat.createVideoFormat(MIME_TYPE, w, h); decodingSurface = new OutputSurface(w, h); decodingSurface.makeCurrent(); decoder.configure(decoderFormat, decodingSurface.getSurface(), null, 0); decoder.start(); MediaFormat format = MediaFormat.createVideoFormat(MIME_TYPE, w, h); format.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface); format.setInteger(MediaFormat.KEY_BIT_RATE, bitRate); format.setInteger(MediaFormat.KEY_FRAME_RATE, 30); format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, IFRAME_INTERVAL); encoder = MediaCodec.createEncoderByType(MIME_TYPE);; encoder.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE); encodingSurface = encoder.createInputSurface(); encoder.start(); encoder.stop(); decoder.stop(); } catch (Exception e) { e.printStackTrace(); Log.i(TAG, "This H/W does not support w:" + w + " h:" + h); return false; } finally { if (encodingSurface != null) { encodingSurface.release(); } if (encoder != null) { encoder.release(); } if (decoder != null) { decoder.release(); } if (decodingSurface != null) { decodingSurface.release(); } } return true; } private static void runOnMain(Runnable runner) { sHandlerForRunOnMain.post(runner); } private static void runOnMainSync(Runnable runner) { SyncRunnable sr = new SyncRunnable(runner); sHandlerForRunOnMain.post(sr); sr.waitForComplete(); } private static final class SyncRunnable implements Runnable { private final Runnable mTarget; private boolean mComplete; public SyncRunnable(Runnable target) { mTarget = target; } public void run() { mTarget.run(); synchronized (this) { mComplete = true; notifyAll(); } } public void waitForComplete() { synchronized (this) { while (!mComplete) { try { wait(); } catch (InterruptedException e) { //ignore } } } } } }
wiki2014/Learning-Summary
alps/cts/tests/tests/media/src/android/media/cts/EncodeVirtualDisplayWithCompositionTest.java
Java
gpl-3.0
59,181
#include "MapState.hpp" namespace states { MapState::MapState(engine::Engine& engine) : GameState(engine), renderer(engine, world), saveFileHandler(engine), pauseState(engine, world, renderer) { suspended = false; }; void MapState::init() { world::PerspectiveState initialPerspective; initialPerspective.fovy = 45.f; initialPerspective.aspect = engine.getWindowHandler().getViewportRatio(); initialPerspective.zNear = 0.1f; initialPerspective.zFar = 10000.f; data::CameraState initialCamera; initialCamera.lookAt = glm::vec3(); initialCamera.distance = 80; initialCamera.rotationAroundX = M_PI / 4.f; initialCamera.rotationAroundY = 0; world.getCamera().init(initialPerspective, initialCamera); world.init(); city.name = "Warsaw"; city.people = 57950; city.money = 445684; world.getMap().setCurrentCity(&city); createNewWorld(); geometry.init(engine, world); init_brushes(); tree_shape = std::make_shared<geometry::Circle>(0.20f); if (!renderer.init()) { engine.stop(); return; } setCurrentAction(MapStateAction::PLACE_BUILDING); this->pole_a = std::make_shared<data::PowerLinePole>(glm::vec2(5, 5)); this->pole_b = std::make_shared<data::PowerLinePole>(glm::vec2(5, 10)); this->pole_c = std::make_shared<data::PowerLinePole>(glm::vec2(5, 15)); world.getMap().add_power_pole(pole_a); world.getMap().add_power_pole(pole_b); world.getMap().add_power_pole(pole_c); world.getMap().add_power_cable(std::make_shared<data::PowerLineCable>(*pole_a, *pole_b)); world.getMap().add_power_cable(std::make_shared<data::PowerLineCable>(*pole_b, *pole_c)); world.getTimer().start(); }; void MapState::init_brushes() noexcept { tree_brush = std::make_unique<input::Brush>(data::Position<float>(), TREE_BRUSH_RADIUS_NORMAL, TREE_BRUSH_BORDER_WIDTH); tree_brush->set_base_colors(glm::vec4(1, 1, 1, 0.05f), glm::vec4(1, 1, 1, 0.4f)); tree_brush->set_active_colors(glm::vec4(1, 1, 0, 0.1f), glm::vec4(1, 1, 0, 0.4f)); } void MapState::cleanup() { renderer.cleanup(); world.cleanup(); } void MapState::update(std::chrono::milliseconds delta) { if (rmbPressed) { handleMapDragging(delta); } if (rotatingClockwise) { handleRotatingAroundY(delta, true); } if (rotatingCounterClockwise) { handleRotatingAroundY(delta, false); } if (rotatingUpwards) { handleRotatingAroundX(delta, true); } if (rotatingDownwards) { handleRotatingAroundX(delta, false); } glm::ivec2 selectionEnd; if (geometry.hitField(engine.getWindowHandler().getMousePositionNormalized(), selectionEnd)) { if (!selection->isSelecting()) { selection->from(selectionEnd); } selection->to(selectionEnd); } if (selection->isSelecting() && MapStateAction::PLACE_BUILDING == currentAction) { glm::vec2 selection_size = selection->getTo() - selection->getFrom() + glm::ivec2(1, 1); auto to_add_shape = std::make_shared<geometry::AABB>(glm::vec2(), selection_size); auto colliders = collides_with(data::CollisionLayer::BUILDINGS); geometry::Collidable to_add(data::CollisionLayer::BUILDINGS, colliders, to_add_shape, selection->getFrom()); if (!world.get_collision_space().if_collides(to_add)) { selection->markValid(); } else { selection->markInvalid(); } } if (MapStateAction::PLACE_ROAD == currentAction && selection->isSelecting()) { data::Position from(selection->getFrom()); data::Position to(selection->getTo()); // FIXME(kantoniak): What if chunk in the middle is not active in the scene? Is it allowed. bool chunk_exists = world.getMap().chunkExists(from.getChunk()) && world.getMap().chunkExists(to.getChunk()); if (!chunk_exists) { selection->markInvalid(); } else { geometry::Collidable::ptr candidate = selection_to_AABB(*selection, data::CollisionLayer::ROADS); if (!world.get_collision_space().if_collides(*candidate)) { selection->markValid(); } else { selection->markInvalid(); } } } if (currentAction == MapStateAction::PLACE_TREES) { glm::vec3 hitpoint; if (geometry.hitGround(engine.getWindowHandler().getMousePositionNormalized(), hitpoint)) { tree_brush->set_center(glm::vec2(hitpoint.x, hitpoint.z)); if (tree_brush->get_radius() > TREE_BRUSH_RADIUS_SINGLE && tree_brush->is_active()) { if (glm::distance(saved_tree_brush_hitpoint, tree_brush->get_center().getGlobal()) > 2.f) { saved_tree_brush_hitpoint = tree_brush->get_center().getGlobal(); insert_trees_from_brush(); } } } } if (MapStateAction::PLACE_POWER_LINES == currentAction) { this->current_tool->update(); } // TODO(kantoniak): Remove temporary poles float angle = (world.getTimer().get_turn_number() / 12.f) * M_PI * 2.f; glm::vec2 pos_delta(cos(angle), sin(angle)); pole_a->set_translation(glm::vec2(5, 5) + pos_delta * 2.f); pole_c->set_translation(glm::vec2(5, 15) + -pos_delta * 2.f); float mid_angle = (fmod(world.getTimer().get_turn_number(), 24.f) / 24.f) * M_PI * 2.f; pole_b->set_rotation(mid_angle); pole_a->set_rotation(2 * M_PI - mid_angle); world.update(delta); }; void MapState::render() { renderer.prepareFrame(); if (current_tool) { this->current_tool->pre_render(renderer); } renderer.renderWorld(*selection, current_brush, current_tool); #ifdef _DEBUG renderer.renderWorldDebug(); renderer.renderDebug(); #endif renderer.flushWorld(); engine.getDebugInfo().onRenderWorldEnd(); engine.getUI().startFrame(); renderer.renderUI(); #ifdef _DEBUG renderer.renderDebugUI(); #endif engine.getUI().endFrame(); renderer.sendFrame(); }; void MapState::onKey(int key, int, int action, int mods) { // TODO(kantoniak): Refactor MapState::onKey by the end of march. If it's April you can start laughing now :) if (key == GLFW_KEY_MINUS && action != GLFW_RELEASE) { world.getCamera().zoom(-5); } if (key == GLFW_KEY_EQUAL && action != GLFW_RELEASE) { world.getCamera().zoom(5); } // Rotation around Y if (key == GLFW_KEY_Q && action == GLFW_PRESS) { rotatingClockwise = true; } else if (key == GLFW_KEY_Q && action == GLFW_RELEASE) { rotatingClockwise = false; } if (key == GLFW_KEY_E && action == GLFW_PRESS) { rotatingCounterClockwise = true; } else if (key == GLFW_KEY_E && action == GLFW_RELEASE) { rotatingCounterClockwise = false; } // Rotation around X if (key == GLFW_KEY_HOME && action == GLFW_PRESS) { rotatingUpwards = true; } else if (key == GLFW_KEY_HOME && action == GLFW_RELEASE) { rotatingUpwards = false; } if (key == GLFW_KEY_END && action == GLFW_PRESS) { rotatingDownwards = true; } else if (key == GLFW_KEY_END && action == GLFW_RELEASE) { rotatingDownwards = false; } if (key == GLFW_KEY_N && action == GLFW_PRESS) { engine.getSettings().rendering.renderNormals = !engine.getSettings().rendering.renderNormals; engine.getLogger().debug(std::string("Normals view: %s"), (engine.getSettings().rendering.renderNormals ? "on" : "off")); } if (key == GLFW_KEY_M && action == GLFW_PRESS) { engine.getLogger().debug("Road nodes debug: %s", (engine.getSettings().rendering.renderRoadNodesAsMarkers ? "on" : "off")); engine.getSettings().rendering.renderRoadNodesAsMarkers = !engine.getSettings().rendering.renderRoadNodesAsMarkers; renderer.markTileDataForUpdate(); } if (key == GLFW_KEY_G && action == GLFW_PRESS) { engine.getSettings().world.showGrid = !engine.getSettings().world.showGrid; } if (mods == GLFW_MOD_CONTROL) { if (GLFW_KEY_1 <= key && key <= GLFW_KEY_9 && action == GLFW_PRESS) { newBuildingHeight = key - GLFW_KEY_1 + 1; } } else { if (GLFW_KEY_1 <= key && key <= GLFW_KEY_1 + world.getTimer().getMaxSpeed() - 1 && action == GLFW_PRESS) { world.getTimer().setSpeed(key - GLFW_KEY_1 + 1); world.getTimer().start(); } } if (key == GLFW_KEY_GRAVE_ACCENT && action == GLFW_PRESS) { world.getTimer().pause(); } if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) { switchToPauseState(); } if (key == GLFW_KEY_Z && action == GLFW_PRESS) { setCurrentAction(MapStateAction::PLACE_BUILDING); } if (key == GLFW_KEY_X && action == GLFW_PRESS) { setCurrentAction(MapStateAction::PLACE_ZONE); } if (key == GLFW_KEY_C && action == GLFW_PRESS) { setCurrentAction(MapStateAction::PLACE_ROAD); } if (key == GLFW_KEY_V && action == GLFW_PRESS) { setCurrentAction(MapStateAction::PLACE_TREES); } if (key == GLFW_KEY_B && action == GLFW_PRESS) { setCurrentAction(MapStateAction::BULDOZE); } if (key == GLFW_KEY_N && action == GLFW_RELEASE && mods == GLFW_MOD_CONTROL) { this->createNewWorld(); } if (key == GLFW_KEY_S && action == GLFW_RELEASE && mods == GLFW_MOD_CONTROL) { saveFileHandler.createSave(world); } if (key == GLFW_KEY_L && action == GLFW_RELEASE && mods == GLFW_MOD_CONTROL) { world.get_collision_space().clear(); world.getMap().cleanup(); saveFileHandler.loadSave(world); renderer.markTileDataForUpdate(); renderer.markBuildingDataForUpdate(); } // Power lines if (key == GLFW_KEY_P && action == GLFW_PRESS) { setCurrentAction(MapStateAction::PLACE_POWER_LINES); } if (currentAction == MapStateAction::PLACE_TREES) { switch (action) { case GLFW_PRESS: { if (key == GLFW_KEY_LEFT_ALT) { tree_brush->set_radius(TREE_BRUSH_RADIUS_SINGLE); renderer.mark_brush_dirty(); } if (key == GLFW_KEY_LEFT_CONTROL) { tree_brush->set_radius(TREE_BRUSH_RADIUS_SMALL); renderer.mark_brush_dirty(); } if (key == GLFW_KEY_LEFT_SHIFT) { tree_brush->set_radius(TREE_BRUSH_RADIUS_BIG); renderer.mark_brush_dirty(); } break; } case GLFW_RELEASE: { if (key != GLFW_KEY_LEFT_ALT && key != GLFW_KEY_LEFT_SHIFT && key != GLFW_KEY_LEFT_CONTROL) { break; } if (tree_brush->get_radius() != TREE_BRUSH_RADIUS_NORMAL) { tree_brush->set_radius(TREE_BRUSH_RADIUS_NORMAL); renderer.mark_brush_dirty(); } break; } } } } void MapState::onMouseButton(int button, int action, int mods) { if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS) { selection->start(selection->getFrom()); } else if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_RELEASE) { selection->stop(); if (MapStateAction::PLACE_BUILDING == currentAction) { glm::ivec2 size = selection->getTo() - selection->getFrom() + glm::ivec2(1, 1); auto to_add = std::make_shared<data::Building>(); to_add->width = size.x; to_add->length = size.y; to_add->level = newBuildingHeight; to_add->x = selection->getFrom().x; to_add->y = selection->getFrom().y; auto to_add_shape = std::make_shared<geometry::AABB>(glm::vec2(), glm::vec2(size.x, size.y)); auto colliders = collides_with(data::CollisionLayer::BUILDINGS); to_add->body = std::make_shared<geometry::Collidable>(data::CollisionLayer::BUILDINGS, colliders, to_add_shape, selection->getFrom()); if (!world.get_collision_space().if_collides(*to_add->body)) { // Delete colliding trees auto collidables = world.get_collision_space().find_colliding_with(*to_add->body); delete_collidables(collidables); // Insert building to_add->body->set_user_data(to_add.get()); world.get_collision_space().insert(to_add->body); world.getMap().add_building(to_add); renderer.markBuildingDataForUpdate(); } } if (MapStateAction::PLACE_ROAD == currentAction && selection->isValid()) { geometry::Collidable::ptr candidate = selection_to_AABB(*selection, data::CollisionLayer::ROADS); if (!world.get_collision_space().if_collides(*candidate)) { // Delete colliding trees auto collidables = world.get_collision_space().find_colliding_with(*candidate); delete_collidables(collidables); // Create and insert roads auto* s = static_cast<input::LineSelection*>(selection.get()); const std::vector<input::LineSelection> selections = s->divideByChunk(); std::vector<data::Road> roads; for (auto& selection : selections) { geometry::Collidable::ptr road_body = selection_to_AABB(selection, data::CollisionLayer::ROADS); world.get_collision_space().insert(road_body); roads.emplace_back(selection.getSelected(), road_body); } world.getMap().addRoads(roads); renderer.markTileDataForUpdate(); } } if (MapStateAction::BULDOZE == currentAction) { // FIXME(kantoniak): Remove roads on buildozer geometry::Collidable::ptr selection_phantom = selection_to_AABB(*selection, data::CollisionLayer::NONE); geometry::Collidable::layer_key to_delete = data::CollisionLayer::BUILDINGS | data::CollisionLayer::TREES; auto collidables = world.get_collision_space().collisions_with(*selection_phantom, to_delete); delete_collidables(collidables); renderer.markBuildingDataForUpdate(); } } if (button == GLFW_MOUSE_BUTTON_RIGHT) { if (action == GLFW_PRESS) { rmbPressed = true; dragStart = engine.getWindowHandler().getMousePosition(); } else { rmbPressed = false; } } if (current_brush && button == GLFW_MOUSE_BUTTON_LEFT) { if (action == GLFW_PRESS) { current_brush->set_active(true); glm::vec3 hitpoint; if (geometry.hitGround(engine.getWindowHandler().getMousePositionNormalized(), hitpoint)) { saved_tree_brush_hitpoint = glm::vec2(hitpoint.x, hitpoint.z); if (current_brush->get_radius() == TREE_BRUSH_RADIUS_SINGLE) { insert_trees_around(saved_tree_brush_hitpoint, {glm::vec2()}); } else { insert_trees_from_brush(); } } } else if (action == GLFW_RELEASE) { current_brush->set_active(false); } renderer.mark_brush_dirty(); } if (current_tool) { current_tool->on_mouse_button(button, action, mods); } } void MapState::onScroll(double, double yoffset) { world.getCamera().zoom(yoffset * 5); } void MapState::onWindowFocusChange(int focused) { if (!focused) { switchToPauseState(); } } void MapState::onWindowResize(int width, int height) { world.getCamera().updateAspect(width / (float)height); } geometry::Collidable::ptr MapState::selection_to_AABB(const input::Selection& selection, data::CollisionLayer layer) const noexcept { glm::vec2 selection_size = selection.getTo() - selection.getFrom() + glm::ivec2(1, 1); auto to_add_shape = std::make_shared<geometry::AABB>(glm::vec2(), selection_size); geometry::Collidable::layer_key colliders = collides_with(static_cast<data::CollisionLayer>(layer)); return std::make_shared<geometry::Collidable>(layer, colliders, to_add_shape, selection.getFrom()); } void MapState::delete_collidables(const std::vector<geometry::Collidable::ptr>& collidables) noexcept { // TODO(kantoniak): Allow for reuse with different tools for (auto& collidable : collidables) { if (collidable->get_user_data() != nullptr) { switch (collidable->get_layer_key()) { case data::CollisionLayer::BUILDINGS: { const data::Building& building = *static_cast<data::Building*>(collidable->get_user_data()); world.getMap().remove_building(building); break; } case data::CollisionLayer::TREES: { const data::Tree& tree = *static_cast<data::Tree*>(collidable->get_user_data()); world.getMap().remove_tree(tree); break; } } } world.get_collision_space().remove(*collidable); } } data::Tree::ptr MapState::create_random_tree(const data::Position<float>& position, geometry::Collidable::ptr tree_body) noexcept { const auto type = static_cast<data::Tree::Type>(rand() % data::Tree::TREE_TYPE_COUNT); const float age = 100.f * static_cast<float>(rand()) / static_cast<float>(RAND_MAX); const float rotation = 2.f * M_PI * static_cast<float>(rand()) / static_cast<float>(RAND_MAX); return std::make_shared<data::Tree>(type, position, rotation, age, tree_body); } void MapState::insert_trees_from_brush() noexcept { static const float tree_density = 2.5f; const float brush_radius = current_brush->get_radius(); size_t point_count = tree_density * brush_radius * brush_radius; std::vector<glm::vec2> points = geometry.distribute_in_circle(point_count, brush_radius, 3.f); insert_trees_around(saved_tree_brush_hitpoint, points); } void MapState::insert_trees_around(const glm::vec2& center, const std::vector<glm::vec2>& points) noexcept { for (auto& point : points) { const glm::vec2 tree_center(center + point); // Skip trees outside chunks // FIXME(kantoniak): This should handle when there are multiple chunks on the board if (tree_center.x < 0 || data::Chunk::SIDE_LENGTH < tree_center.x || tree_center.y < 0 || data::Chunk::SIDE_LENGTH < tree_center.y) { continue; } auto colliders = collides_with(data::CollisionLayer::TREES); auto collidable_ptr = std::make_shared<geometry::Collidable>(data::CollisionLayer::TREES, colliders, tree_shape, tree_center); if (!world.get_collision_space().if_collides(*collidable_ptr)) { auto tree_ptr = create_random_tree(tree_center, collidable_ptr); collidable_ptr->set_user_data(tree_ptr.get()); world.get_collision_space().insert(collidable_ptr); world.getMap().add_tree(tree_ptr); } } } void MapState::createNewWorld() { world.getMap().cleanup(); const glm::ivec2 mapSize = glm::ivec2(1, 1); for (int x = 0; x < mapSize.x; x++) { for (int y = 0; y < mapSize.y; y++) { world.getMap().createChunk(glm::ivec2(x, y)); } } } void MapState::createRandomWorld() { /*const glm::ivec2 mapSize = glm::ivec2(2, 2); for (int x = 0; x < mapSize.x; x++) { for (int y = 0; y < mapSize.y; y++) { world.getMap().createChunk(glm::ivec2(x, y)); } } for (int x = 0; x < mapSize.x; x++) { for (int y = 0; y < mapSize.y; y++) { auto chunkPos = glm::ivec2(x, y); int lotX = 0; for (int i = 2; i < 11; i++) { data::Lot lot; lot.position.setLocal(glm::ivec2(lotX + 2, 2), chunkPos); lot.size = glm::ivec2(i, 6); switch (i % 4) { case 0: lot.direction = data::Direction::N; break; case 1: lot.direction = data::Direction::S; break; case 2: lot.direction = data::Direction::W; break; case 3: lot.direction = data::Direction::E; break; } world.getMap().addLot(lot); lotX += 1 + i; } } } // TEST road division renderer.markTileDataForUpdate(); constexpr unsigned int minBuildingSide = 2; constexpr unsigned int maxBuildingSideDifference = 3; constexpr unsigned int minBuildingHeight = 1; constexpr unsigned int maxBuildingHeightDifference = 6; constexpr unsigned int maxCollisionTries = 20; const unsigned int buildingCount = (mapSize.x * mapSize.y) * (data::Chunk::SIDE_LENGTH * data::Chunk::SIDE_LENGTH / 4) * 0.02f; for (unsigned int i = 0; i < buildingCount; i++) { data::buildings::Building test; for (unsigned int i = 0; i < maxCollisionTries; i++) { test.width = rand() % maxBuildingSideDifference + minBuildingSide; test.length = rand() % maxBuildingSideDifference + minBuildingSide; test.level = rand() % maxBuildingHeightDifference + minBuildingHeight; test.x = rand() % (data::Chunk::SIDE_LENGTH * mapSize.x - test.width + 1); test.y = rand() % (data::Chunk::SIDE_LENGTH * mapSize.y - test.length + 1); if (!geometry.checkCollisions(test)) { world.getMap().addBuilding(test); break; } } }*/ } void MapState::setCurrentAction(MapStateAction action) { currentAction = action; renderer.setLeftMenuActiveIcon(currentAction - MapStateAction::PLACE_BUILDING); // Reset brush, selection and tool engine.getSettings().rendering.renderSelection = false; current_brush = nullptr; renderer.mark_brush_dirty(); this->current_tool.reset(); switch (action) { case MapStateAction::PLACE_BUILDING: engine.getSettings().rendering.renderSelection = true; selection = std::make_unique<input::Selection>(); selection->setColors(glm::vec4(1, 1, 0.f, 0.4f), glm::vec4(1, 1, 0.f, 0.4f), glm::vec4(1, 0, 0, 0.4f)); break; case MapStateAction::PLACE_ZONE: break; case MapStateAction::PLACE_POWER_LINES: { auto tool_ptr = std::make_shared<input::PowerLineTool>(engine.getWindowHandler(), world, renderer.get_model_manager(), geometry, current_brush); this->current_tool = tool_ptr; this->current_brush = tool_ptr->get_brush_ptr(); break; } case MapStateAction::PLACE_ROAD: engine.getSettings().rendering.renderSelection = true; selection = std::make_unique<input::LineSelection>(1); selection->setColors(glm::vec4(1, 1, 0.f, 0.4f), glm::vec4(1, 1, 0.f, 0.4f), glm::vec4(1, 0, 0, 0.4f)); break; case MapStateAction::PLACE_TREES: current_brush = tree_brush; tree_brush->set_center(glm::vec2(10, 10)); renderer.mark_brush_dirty(); break; case MapStateAction::BULDOZE: engine.getSettings().rendering.renderSelection = true; selection = std::make_unique<input::Selection>(); selection->setColors(glm::vec4(1, 0.f, 0.f, 0.2f), glm::vec4(1, 0.f, 0.f, 0.6f), glm::vec4(1, 0, 0, 1.f)); break; } } void MapState::handleMapDragging(std::chrono::milliseconds delta) { const glm::vec2 mousePosition = engine.getWindowHandler().getMousePosition(); const glm::vec2 dragDelta = mousePosition - dragStart; float dragSpeed = 0.2f * delta.count() / 1000.f; world.getCamera().move(dragSpeed * glm::vec3(dragDelta.x, 0.f, dragDelta.y)); } void MapState::handleRotatingAroundY(std::chrono::milliseconds delta, bool clockwise) { float rotationDelta = M_PI * delta.count() / 1000.f; float modifier = (clockwise ? 1.f : -1.f); world.getCamera().rotateAroundY(rotationDelta * modifier); } void MapState::handleRotatingAroundX(std::chrono::milliseconds delta, bool upwards) { float rotationDelta = M_PI * delta.count() / 1000.f; float modifier = (upwards ? 1.f : -1.f); world.getCamera().rotateAroundX(rotationDelta * modifier); } void MapState::switchToPauseState() { engine.pushState(pauseState); } }
kantoniak/konstruisto
src/states/MapState.cpp
C++
gpl-3.0
22,882
Monster = ring.create([AbstractIcon], { constructor: function() { this.sprite = objPhaser.add.sprite(0, 0, Constants.ASSET_MONSTER); this.sprite.animations.add("fly"); this.sprite.animations.play("fly", 3, true); this.type = Constants.ASSET_MONSTER; this.anim = 0; this.sinchange = 0; }, update: function(gamespeed) { this.$super(gamespeed); /*this.anim++; if (this.anim % Constants.MONSTER_LEVITATE_SPEED == 0) { this.sinchange++; this.sprite.y += Math.round(Math.sin(this.sinchange) * Constants.MONSTER_LEVITATE_ACCELERATION); }*/ }, toString: function() { return "Monster"; } });
gfrymer/GGJ2015-BSAS-Duality
src/entities/Monster.js
JavaScript
gpl-3.0
629
function direction(dir, neg) { if (dir == 'x') { return function (num) { num = num == null ? 1 : num; return new Tile(this.x + (neg ? -num : num), this.y); }; } return function (num) { num = num == null ? 1 : num; return new Tile(this.x, this.y + (neg ? -num : num)); }; } var Tile = new Class({ initialize: function (x, y, layer) { this.width = GetTileWidth(); this.height = GetTileHeight(); if (arguments.length > 1) { this.layer = [layer, GetPersonLayer(Arq.config.player)].pick(); this.id = GetTile(x, y, this.layer); this.x = x; this.y = y; this.pixelX = this.width * x; this.pixelY = this.height * y; } else this.id = x; this.name = GetTileName(this.id); }, north: direction('y', true), south: direction('y'), east: direction('x'), west: direction('x', true), place: function (person) { SetPersonX(person, this.pixelX + this.width / 2); SetPersonY(person, this.pixelY + this.height / 2); return this; }, set: function (tile) { if (typeof tile == 'string') tile = Tile.name(tile); SetTile(this.x, this.y, this.layer, typeof tile == 'number' ? tile : tile.id); return this; } }); function creator(create) { return function (x, y, layer) { if (arguments.length == 1) { var coords = x; x = coords.x; y = coords.y; } return create(x, y, layer); }; } Tile.id = function (id) new Tile(id); Tile.name = function (name) { var n = GetNumTiles(); while (n--) { if (GetTileName(n) == name) return Tile.id(n); } }; Tile.tile = creator(function (x, y, layer) new Tile(x, y, layer)); Tile.pixels = creator(function (x, y, layer) new Tile(Math.floor(x / GetTileWidth()), Math.floor(y / GetTileHeight()), layer)); Tile.under = function (person) Tile.pixels(GetPersonX(person), GetPersonY(person), GetPersonLayer(person)); Tile.current = function () Tile.under(Arq.config.player); exports.Tile = Tile;
alpha123/Arq
tile.js
JavaScript
gpl-3.0
2,213
<?php namespace ModulusContent\Entity; use Doctrine\ORM\Mapping as ORM; /** * ItensMenu * * @ORM\Table(name="itens_menu") * @ORM\Entity(repositoryClass="ModulusContent\Repository\ItensMenu") */ class ItensMenu { /** * @var integer * * @ORM\Column(name="id", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $id; /** * @var string * * @ORM\Column(name="label", type="string", length=100, nullable=false) */ private $label; /** * @var string * * @ORM\Column(name="title", type="string", length=100, nullable=false) */ private $title; /** * @var string * * @ORM\Column(name="url", type="string", length=255, nullable=true) */ private $url; /** * @var integer * * @ORM\Column(name="ordem", type="integer", nullable=false) */ private $ordem; /** * @var \Menu * * @ORM\ManyToOne(targetEntity="Menu") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="menu_id", referencedColumnName="id") * }) */ private $menu; /** * @var \ItensMenu * * @ORM\ManyToOne(targetEntity="ItensMenu") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="parent_item_menu_id", referencedColumnName="id") * }) */ private $parentItemMenu; /** * @var \SiteContent * * @ORM\ManyToOne(targetEntity="SiteContent") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="site_content_id", referencedColumnName="id") * }) */ private $siteContent; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set label * * @param string $label * @return ItensMenu */ public function setLabel($label) { $this->label = $label; return $this; } /** * Get label * * @return string */ public function getLabel() { return $this->label; } /** * Set title * * @param string $title * @return ItensMenu */ public function setTitle($title) { $this->title = $title; return $this; } /** * Get title * * @return string */ public function getTitle() { return $this->title; } /** * Set url * * @param string $url * @return ItensMenu */ public function setUrl($url) { $this->url = $url; return $this; } /** * Get url * * @return string */ public function getUrl() { return $this->url; } /** * Set ordem * * @param integer $ordem * @return ItensMenu */ public function setOrdem($ordem) { $this->ordem = $ordem; return $this; } /** * Get ordem * * @return integer */ public function getOrdem() { return $this->ordem; } /** * Set menu * * @param \Menu $menu * @return ItensMenu */ public function setMenu(Menu $menu = null) { $this->menu = $menu; return $this; } /** * Get menu * * @return \Menu */ public function getMenu() { return $this->menu; } /** * Set parentItemMenu * * @param \ItensMenu $parentItemMenu * @return ItensMenu */ public function setParentItemMenu(ItensMenu $parentItemMenu = null) { $this->parentItemMenu = $parentItemMenu; return $this; } /** * Get parentItemMenu * * @return \ItensMenu */ public function getParentItemMenu() { return $this->parentItemMenu; } /** * Set siteContent * * @param \SiteContent $siteContent * @return ItensMenu */ public function setSiteContent(SiteContent $siteContent = null) { $this->siteContent = $siteContent; return $this; } /** * Get siteContent * * @return \SiteContent */ public function getSiteContent() { return $this->siteContent; } }
ZF2-Modulus/ModulusContent
src/ModulusContent/Entity/ItensMenu.php
PHP
gpl-3.0
4,282
// TinyXML2Demo.cpp : ¶¨Òå¿ØÖÆÌ¨Ó¦ÓóÌÐòµÄÈë¿Úµã¡£ // #include "stdafx.h" #include "tinyxml2.h" #include <stdio.h> #include <iostream> #include <sstream> #include <vector> #include <map> #include <time.h> using namespace std; using namespace tinyxml2; const char* NODE_XML = "Node.xml"; const char* NODE_ACG_H = "../AcgDemo/NodeAcg.h"; template<class TData> string DebugData(const TData& data) { ostringstream oss; oss << data; return oss.str(); } template<class TData> string DebugData(const vector<TData>& dataVec) { ostringstream oss; for each (const TData& data in dataVec) { oss << data << " "; } return oss.str(); } template<class TData1, class TData2> string DebugData(const map<TData1, TData2>& dataMap) { ostringstream oss; for each (pair<TData1, TData2> data in dataMap) { oss << "[" << DebugData(data.first) << " " << DebugData(data.second) << "]"; } return oss.str(); } void DebugElement(FILE* fp, const char* pszSpace, const char* pszPrefix, const char* pszName, const char* pszType, bool bPrintName) { if (bPrintName) fprintf(fp, "%soss << \"%s:\"", pszSpace, pszName); else fprintf(fp, "%soss", pszSpace); if (!strncmp(pszType, "Ms", 2)) { fprintf(fp, " << DebugClass(%s%s);\n", pszPrefix, pszName); } else if (!strncmp(pszType, "vector", 6)) { fprintf(fp, " << \"[ \";\n"); char pszVecType[64] = { 0 }; const char* pszLT = strchr(pszType, '<'); const char* pszGT = strrchr(pszType, '>'); strncpy_s(pszVecType, 64, pszLT + 1, pszGT - pszLT - 1); fprintf(fp, "%sfor_each(%s%s.begin(), %s%s.end(), [&oss](const %s& data)->void\n", pszSpace, pszPrefix, pszName, pszPrefix, pszName, pszVecType); fprintf(fp, "%s{\n", pszSpace); char pszNewSpace[1024] = { 0 }; strncpy_s(pszNewSpace, 1024, pszSpace, strlen(pszSpace)); strcat_s(pszNewSpace, 1024, " "); DebugElement(fp, pszNewSpace, "", "data", pszVecType, false); fprintf(fp, "%s});\n", pszSpace); fprintf(fp, "%soss << \"] \";\n", pszSpace); } else if (!strncmp(pszType, "map", 3)) { fprintf(fp, " << \"{ \";\n"); char keyType[64] = { 0 }; char valType[64] = { 0 }; char pairType[64] = { 0 }; const char* pszLT = strchr(pszType, '<'); const char* pszComma = strchr(pszType, ','); const char* pszGT = strrchr(pszType, '>'); strncpy_s(keyType, 64, pszLT + 1, pszComma - pszLT - 1); strncpy_s(valType, 64, pszComma + 1, pszGT - pszComma - 1); strncpy_s(pairType, 64, pszLT + 1, pszGT - pszLT - 1); fprintf(fp, "%sfor_each(%s%s.begin(), %s%s.end(), [&oss](const pair<%s>& data)->void\n", pszSpace, pszPrefix, pszName, pszPrefix, pszName, pairType); fprintf(fp, "%s{\n", pszSpace); char pszNewSpace[1024] = { 0 }; strncpy_s(pszNewSpace, 1024, pszSpace, strlen(pszSpace)); strcat_s(pszNewSpace, 1024, " "); fprintf(fp, "%soss << \"[ \";\n", pszNewSpace); DebugElement(fp, pszNewSpace, "", "data.first", keyType, false); DebugElement(fp, pszNewSpace, "", "data.second", valType, false); fprintf(fp, "%soss << \"]\";\n", pszNewSpace); fprintf(fp, "%s});\n", pszSpace); fprintf(fp, "%soss << \" } \";\n", pszSpace); } else { fprintf(fp, " << %s%s << \" \";\n", pszPrefix, pszName); } } //string DebugClass(MsUserInfoLite& mb) //{ // ostringstream oss; // // oss << DebugData(mb.roleId) << " " << DebugData(mb.roleName); // // return oss.str(); //} void AutoGenClass() { FILE* fp; fopen_s(&fp, NODE_ACG_H, "w"); if (!fp) { printf("error open file %s\n", NODE_ACG_H); return; } XMLDocument *pDoc = new XMLDocument(); XMLError errorId = pDoc->LoadFile(NODE_XML); if (errorId != XML_SUCCESS) { fclose(fp); printf("error load xml: %d %s\n", errorId, NODE_XML); return; } XMLElement* pRoot = pDoc->RootElement(); XMLElement* pCppText = pRoot->FirstChildElement("CppText"); fprintf(fp, "%s\n", pCppText->GetText()); XMLElement* pMessage = pRoot->FirstChildElement("Message"); while (pMessage) { const char* pszName = pMessage->Attribute("name"); const char* pszBase = pMessage->Attribute("base"); fprintf(fp, "class Ms%s", pszName); if (pszBase) fprintf(fp, " : public Ms%s", pszBase); fprintf(fp, "\n"); fprintf(fp, "{\n"); fprintf(fp, "public:\n"); fprintf(fp, " Ms%s(){}\n", pszName); fprintf(fp, "\npublic:\n"); XMLElement* pVar = pMessage->FirstChildElement("Var"); while (pVar) { const char* pszName = pVar->Attribute("name"); const char* pszType = pVar->Attribute("type"); fprintf(fp, " %s %s;\n", pszType, pszName); pVar = pVar->NextSiblingElement(); } fprintf(fp, "};\n\n\n"); pMessage = pMessage->NextSiblingElement(); } fclose(fp); } void AutoGenDebugClass() { FILE* fp; fopen_s(&fp, NODE_ACG_H, "a"); if (!fp) { printf("error open file: %s\n", NODE_ACG_H); return; } XMLDocument *pDoc = new XMLDocument(); XMLError errorId = pDoc->LoadFile(NODE_XML); if (errorId != XML_SUCCESS) { fclose(fp); printf("error load xml: %d %s\n", errorId, NODE_XML); return; } XMLElement* pRoot = pDoc->RootElement(); XMLElement* pMessage = pRoot->FirstChildElement("Message"); while (pMessage) { const char* pszName = pMessage->Attribute("name"); const char* pszBase = pMessage->Attribute("base"); fprintf(fp, "string DebugClass(const class Ms%s& mb)\n", pszName); fprintf(fp, "{\n"); char pszSpace[1024] = " "; fprintf(fp, "%sostringstream oss;\n", pszSpace); fprintf(fp, "%soss << \"{ \";\n", pszSpace); if (pszBase) { fprintf(fp, "%soss << \"Ms%s: \" << DebugClass(static_cast<const Ms%s&>(mb));\n", pszSpace, pszBase, pszBase); } XMLElement* pVar = pMessage->FirstChildElement("Var"); while (pVar) { const char* pszName = pVar->Attribute("name"); const char* pszType = pVar->Attribute("type"); DebugElement(fp, pszSpace, "mb.", pszName, pszType, true); pVar = pVar->NextSiblingElement(); } fprintf(fp, "%soss << \"} \";\n", pszSpace); fprintf(fp, "%sreturn oss.str();\n", pszSpace); fprintf(fp, "}\n"); pMessage = pMessage->NextSiblingElement(); } fclose(fp); } int main() { //printf("/\\"); //printf("\n"); if ((void)0, 0) { printf("i am void 0\n"); } else { printf("i am not void 0\n"); } AutoGenClass(); AutoGenDebugClass(); //FILE* fp; //fopen_s(&fp, "../AcgDemo/NodeAcg.h", "a"); //XMLDocument *pDoc = new XMLDocument(); //XMLError errorId = pDoc->LoadFile(NODE_XML); //if (errorId != XML_SUCCESS) //{ // fclose(fp); // printf("error load xml: %d %s\n", errorId, NODE_XML); // system("pause"); // return 0; //} //XMLElement* pRoot = pDoc->RootElement(); //XMLElement* pMessage = pRoot->FirstChildElement("Message"); //while (pMessage) //{ // const char* pszName = pMessage->Attribute("name"); // const char* pszBase = pMessage->Attribute("base"); // fprintf(fp, "string DebugClass(class Ms%s& mb)\n", pszName); // fprintf(fp, "{\n"); // fprintf(fp, " ostringstream oss;\n"); // XMLElement* pVar = pMessage->FirstChildElement("Var"); // while (pVar) // { // const char* pszName = pVar->Attribute("name"); // const char* pszType = pVar->Attribute("type"); // DebugElement(fp, "mb.", pszName, pszType); // //if( !strncmp(pszType, "Ms", 2) ) // // printf(" oss << DebugClass(mb.%s);\n", pszName); // //else if( !strncmp(pszType, "vector", 6)) // //else // // printf(" oss << DebugData(mb.%s);\n", pszName); // pVar = pVar->NextSiblingElement(); // } // fprintf(fp, " return oss.str();\n"); // fprintf(fp, "}\n"); // // pMessage = pMessage->NextSiblingElement(); //} //while (pMessage) //{ // const char* pszName = pMessage->Attribute("name"); // const char* pszBase = pMessage->Attribute("base"); // XMLElement* pVar = pMessage->FirstChildElement("Var"); // while (pVar) // { // printf("var name:%s type:%s\n", pVar->Attribute("name"), pVar->Attribute("type")); // pVar = pVar->NextSiblingElement(); // } // pMessage = pMessage->NextSiblingElement(); //} //int nNum = 1; //printf("debug 1: %s\n", DebugData(nNum).c_str()); //vector<int> numVec; //numVec.push_back(1); //numVec.push_back(1); //numVec.push_back(3); //printf("debug vector: %s\n", DebugData(numVec).c_str()); //map<int, int> numMap; //numMap[1] = 1; //numMap[2] = 2; //numMap[3] = 3; //printf("debug map: %s\n", DebugData(numMap).c_str()); //fclose(fp); system("pause"); return 0; }
windpenguin/TinyXML2Demo
TinyXML2Demo/TinyXML2Demo.cpp
C++
gpl-3.0
8,301
class Deputy < User has_many :users, :through => :substitutions, :dependent => :restrict, :inverse_of => :deputies end
informatom/qm
app/models/deputy.rb
Ruby
gpl-3.0
121
/* Copyright (C) 2016 Julien Le Fur This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ var CST = require('../../constants.js'); var fs = require('fs'); var util = require('util'); function execute(args,options,input,ctx,callback){ if(ctx[CST.OBJ.TEMPLATE]==undefined){ return callback(new Error(util.format(CST.MSG_ERR.TEMPLATE_NOT_EXIST,args[CST.OBJ.TEMPLATE]))); } var template=`./${config.get('simusPath')}/${args[CST.OBJ.SERVICE]}/${args[CST.OBJ.API]}/${args[CST.OBJ.TEMPLATE]}`; fs.unlink(template, (err)=>{ if(err) return callback(new Error(util.format(CST.MSG_ERR.TEMPLATE_DELETE,args[CST.OBJ.TEMPLATE]))); else{ return callback(null,args,options,input,ctx); } }); } module.exports = execute
Ju-Li-An/gs_engine
lib/dataAccess/fs/template/delete.js
JavaScript
gpl-3.0
1,386
<?php /* * TreeChecker: Error recognition for genealogical trees * * Copyright (C) 2014 Digital Humanities Lab, Faculty of Humanities, Universiteit Utrecht * Corry Gellatly <corry.gellatly@gmail.com> * Martijn van der Klis <M.H.vanderKlis@uu.nl> * * Class that defines an event details object * * Derived from webtrees: Web based Family History software * Copyright (C) 2014 webtrees development team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ if (!defined('WT_WEBTREES')) { header('HTTP/1.0 403 Forbidden'); exit; } class WT_Fact { private $fact_id = null; // Unique identifier for this fact private $parent = null; // The GEDCOM record from which this fact is taken. private $gedcom = null; // The raw GEDCOM data for this fact private $tag = null; // The GEDCOM tag for this record private $is_old = false; // Is this a pending record? private $is_new = false; // Is this a pending record? private $date = null; // The WT_Date object for the "2 DATE ..." attribute private $place = null; // The WT_Place object for the "2 PLAC ..." attribute private $lati = null; // The WT_Lati object for the "2 LATI ..." attribute private $long = null; // The WT_Long object for the "2 LONG ..." attribute // Temporary(!) variables that are used by other scripts public $temp = null; // Timeline controller public $sortOrder = 0; // sort_facts() // Create an event objects from a gedcom fragment. // We need the parent object (to check privacy) and a (pseudo) fact ID to // identify the fact within the record. public function __construct($gedcom, WT_GedcomRecord $parent, $fact_id) { if (preg_match('/^1 ('.WT_REGEX_TAG.')/', $gedcom, $match)) { $this->gedcom = $gedcom; $this->parent = $parent; $this->fact_id = $fact_id; $this->tag = $match[1]; } else { // TODO need to rewrite code that passes dummy data to this function //throw new Exception('Invalid GEDCOM data passed to WT_Fact::_construct('.$gedcom.')'); } } // Get the value of level 1 data in the fact // Allow for multi-line values public function getValue() { if (preg_match('/^1 (?:' . $this->tag . ') ?(.*(?:(?:\n2 CONT ?.*)*))/', $this->gedcom, $match)) { return preg_replace("/\n2 CONT ?/", "\n", $match[1]); } else { return null; } } // Get the record to which this fact links public function getTarget() { $xref = trim($this->getValue(), '@'); switch ($this->tag) { case 'FAMC': case 'FAMS': return WT_Family::getInstance($xref, $this->getParent()->getGedcomId()); case 'HUSB': case 'WIFE': case 'CHIL': return WT_Individual::getInstance($xref, $this->getParent()->getGedcomId()); case 'SOUR': return WT_Source::getInstance($xref, $this->getParent()->getGedcomId()); case 'OBJE': return WT_Media::getInstance($xref, $this->getParent()->getGedcomId()); case 'REPO': return WT_Repository::getInstance($xref, $this->getParent()->getGedcomId()); case 'NOTE': return WT_Note::getInstance($xref, $this->getParent()->getGedcomId()); default: return WT_GedcomRecord::getInstance($xref, $this->getParent()->getGedcomId()); } } // Get the value of level 2 data in the fact public function getAttribute($tag) { if (preg_match('/\n2 (?:' . $tag . ') ?(.*(?:(?:\n3 CONT ?.*)*)*)/', $this->gedcom, $match)) { return preg_replace("/\n3 CONT ?/", "\n", $match[1]); } else { return null; } } // Do the privacy rules allow us to display this fact to the current user public function canShow($access_level=WT_USER_ACCESS_LEVEL) { // TODO - use the privacy settings for $this->gedcom_id, not the default gedcom. global $person_facts, $global_facts; // // Does this record have an explicit RESN? // if (strpos($this->gedcom, "\n2 RESN confidential")) { // return WT_PRIV_NONE >= $access_level; // } // if (strpos($this->gedcom, "\n2 RESN privacy")) { // return WT_PRIV_USER >= $access_level; // } // if (strpos($this->gedcom, "\n2 RESN none")) { // return true; // } // // // Does this record have a default RESN? // $xref = $this->parent->getXref(); // if (isset($person_facts[$xref][$this->tag])) { // return $person_facts[$xref][$this->tag] >= $access_level; // } // if (isset($global_facts[$this->tag])) { // return $global_facts[$this->tag] >= $access_level; // } // No restrictions - it must be public return true; } // Check whether this fact is protected against edit public function canEdit() { // Managers can edit anything // Members cannot edit RESN, CHAN and locked records return $this->parent->canEdit() && !$this->isOld() && ( WT_USER_GEDCOM_ADMIN || WT_USER_CAN_EDIT && strpos($this->gedcom, "\n2 RESN locked")===false && $this->getTag()!='RESN' && $this->getTag()!='CHAN' ); } // The place where the event occured. public function getPlace() { if ($this->place === null) { $this->place = new WT_Place($this->getAttribute('PLAC'), $this->getParent()->getGedcomId()); } return $this->place; } // The latitude where the event occured. public function getLati() { if ($this->lati === null) { $this->lati = new WT_Place($this->getAttribute('LATI'), $this->getParent()->getGedcomId()); } return $this->lati; } // The longitude where the event occured. public function getLong() { if ($this->long === null) { $this->long = new WT_Place($this->getAttribute('LONG'), $this->getParent()->getGedcomId()); } return $this->long; } // We can call this function many times, especially when sorting, // so keep a copy of the date. public function getDate() { if ($this->date === null) { $this->date = new WT_Date($this->getAttribute('DATE')); } return $this->date; } // The raw GEDCOM data for this fact public function getGedcom() { return $this->gedcom; } // Unique identifier for the fact public function getFactId() { return $this->fact_id; } // What sort of fact is this? public function getTag() { return $this->tag; } // Used to convert a real fact (e.g. BIRT) into a close-relative’s fact (e.g. _BIRT_CHIL) public function setTag($tag) { $this->tag = $tag; } // The Person/Family record where this WT_Fact came from public function getParent() { return $this->parent; } public function getLabel() { switch($this->tag) { case 'EVEN': case 'FACT': if ($this->getAttribute('TYPE')) { // Custom FACT/EVEN - with a TYPE return WT_I18N::translate(WT_Filter::escapeHtml($this->getAttribute('TYPE'))); } // no break - drop into next case default: return WT_Gedcom_Tag::getLabel($this->tag, $this->parent); } } // Is this a pending edit? public function setIsOld() { $this->is_old = true; $this->is_new = false; } public function isOld() { return $this->is_old; } public function setIsNew() { $this->is_new = true; $this->is_old = false; } public function isNew() { return $this->is_new; } // Source citations linked to this fact public function getCitations() { preg_match_all('/\n(2 SOUR @(' . WT_REGEX_XREF . ')@(?:\n[3-9] .*)*)/', $this->getGedcom(), $matches, PREG_SET_ORDER); $citations = array(); foreach ($matches as $match) { $source = WT_Source::getInstance($match[2], $this->getParent()->getGedcomId()); if ($source->canShow()) { $citations[] = $match[1]; } } return $citations; } // Notes (inline and objects) linked to this fact public function getNotes() { $notes = array(); preg_match_all('/\n2 NOTE ?(.*(?:\n3.*)*)/', $this->getGedcom(), $matches); foreach ($matches[1] as $match) { $note = preg_replace("/\n3 CONT ?/", "\n", $match); if (preg_match('/@(' . WT_REGEX_XREF . ')@/', $note, $nmatch)) { $note = WT_Note::getInstance($nmatch[1], $this->getParent()->getGedcomId()); if ($note && $note->canShow()) { // A note object $notes[] = $note; } } else { // An inline note $notes[] = $note; } } return $notes; } // Media objects linked to this fact public function getMedia() { $media = array(); preg_match_all('/\n2 OBJE @(' . WT_REGEX_XREF . ')@/', $this->getGedcom(), $matches); foreach ($matches[1] as $match) { $obje = WT_Media::getInstance($match, $this->getParent()->getGedcomId()); if ($obje->canShow()) { $media[] = $obje; } } return $media; } // A one-line summary of the fact - for charts, etc. public function summary() { global $SHOW_PARENTS_AGE; $attributes = array(); $target = $this->getTarget(); if ($target) { $attributes[] = $target->getFullName(); } else { $value = $this->getValue(); if ($value && $value!='Y') { $attributes[] = '<span dir="auto">' . WT_Filter::escapeHtml($value) . '</span>'; } $date = $this->getDate(); if ($this->getTag() == 'BIRT' && $SHOW_PARENTS_AGE && $this->getParent() instanceof WT_Individual) { $attributes[] = $date->display() . format_parents_age($this->getParent(), $date); } else { $attributes[] = $date->display(); } $place = $this->getPlace()->getShortName(); if ($place) { $attributes[] = $place; } } $html = WT_Gedcom_Tag::getLabelValue($this->getTag(), implode(' — ', $attributes), $this->getParent()); if ($this->isNew()) { return '<div class="new">' . $html . '</div>'; } elseif ($this->isOld()) { return '<div class="old">' . $html . '</div>'; } else { return $html; } } // Display an icon for this fact. // Icons are held in a theme subfolder. Not all themes provide icons. public function Icon() { $icon = 'images/facts/' . $this->getTag() . '.png'; $dir = substr(WT_CSS_URL, strlen(WT_STATIC_URL)); if (file_exists($dir . $icon)) { return '<img src="' . WT_CSS_URL . $icon . '" title="' . WT_Gedcom_Tag::getLabel($this->getTag()) . '">'; } elseif (file_exists($dir . 'images/facts/NULL.png')) { // Spacer image - for alignment - until we move to a sprite. return '<img src="' . WT_CSS_URL . 'images/facts/NULL.png">'; } else { return ''; } } /** * Static Helper functions to sort events * * @param WT_Fact $a Fact one * @param WT_Fact $b Fact two * * @return integer */ public static function CompareDate(WT_Fact $a, WT_Fact $b) { if ($a->getDate()->isOK() && $b->getDate()->isOK()) { // If both events have dates, compare by date $ret = WT_Date::Compare($a->getDate(), $b->getDate()); if ($ret == 0) { // If dates are the same, compare by fact type $ret = self::CompareType($a, $b); // If the fact type is also the same, retain the initial order if ($ret == 0) { $ret = $a->sortOrder - $b->sortOrder; } } return $ret; } else { // One or both events have no date - retain the initial order return $a->sortOrder - $b->sortOrder; } } /** * Static method to compare two events by their type. * * @param WT_Fact $a Fact one * @param WT_Fact $b Fact two * * @return integer */ public static function CompareType(WT_Fact $a, WT_Fact $b) { global $factsort; if (empty($factsort)) { $factsort = array_flip( array( 'BIRT', '_HNM', 'ALIA', '_AKA', '_AKAN', 'ADOP', '_ADPF', '_ADPF', '_BRTM', 'CHR', 'BAPM', 'FCOM', 'CONF', 'BARM', 'BASM', 'EDUC', 'GRAD', '_DEG', 'EMIG', 'IMMI', 'NATU', '_MILI', '_MILT', 'ENGA', 'MARB', 'MARC', 'MARL', '_MARI', '_MBON', 'MARR', 'MARR_CIVIL', 'MARR_RELIGIOUS', 'MARR_PARTNERS', 'MARR_UNKNOWN', '_COML', '_STAT', '_SEPR', 'DIVF', 'MARS', '_BIRT_CHIL', 'DIV', 'ANUL', '_BIRT_', '_MARR_', '_DEAT_','_BURI_', // other events of close relatives 'CENS', 'OCCU', 'RESI', 'PROP', 'CHRA', 'RETI', 'FACT', 'EVEN', '_NMR', '_NMAR', 'NMR', 'NCHI', 'WILL', '_HOL', '_????_', 'DEAT', '_FNRL', 'CREM', 'BURI', '_INTE', '_YART', '_NLIV', 'PROB', 'TITL', 'COMM', 'NATI', 'CITN', 'CAST', 'RELI', 'SSN', 'IDNO', 'TEMP', 'SLGC', 'BAPL', 'CONL', 'ENDL', 'SLGS', 'ADDR', 'PHON', 'EMAIL', '_EMAIL', 'EMAL', 'FAX', 'WWW', 'URL', '_URL', 'FILE', // For media objects 'AFN', 'REFN', '_PRMN', 'REF', 'RIN', '_UID', 'OBJE', 'NOTE', 'SOUR', 'CHAN', '_TODO', ) ); } // Facts from same families stay grouped together // Keep MARR and DIV from the same families from mixing with events from other FAMs // Use the original order in which the facts were added if (($a->parent instanceof WT_Family) && ($b->parent instanceof WT_Family) && ($a->parent !== $b->parent) ) { return $a->sortOrder - $b->sortOrder; } $atag = $a->getTag(); $btag = $b->getTag(); // Events not in the above list get mapped onto one that is. if (!array_key_exists($atag, $factsort)) { if (preg_match('/^(_(BIRT|MARR|DEAT|BURI)_)/', $atag, $match)) { $atag = $match[1]; } else { $atag = "_????_"; } } if (!array_key_exists($btag, $factsort)) { if (preg_match('/^(_(BIRT|MARR|DEAT|BURI)_)/', $btag, $match)) { $btag = $match[1]; } else { $btag = "_????_"; } } // - Don't let dated after DEAT/BURI facts sort non-dated facts before DEAT/BURI // - Treat dated after BURI facts as BURI instead if (($a->getAttribute('DATE') != null) && ($factsort[$atag] > $factsort['BURI']) && ($factsort[$atag] < $factsort['CHAN']) ) { $atag = 'BURI'; } if (($b->getAttribute('DATE') != null) && ($factsort[$btag] > $factsort['BURI']) && ($factsort[$btag] < $factsort['CHAN']) ) { $btag = 'BURI'; } $ret = $factsort[$atag] - $factsort[$btag]; // If facts are the same then put dated facts before non-dated facts if ($ret == 0) { if (($a->getAttribute('DATE') != null) && ($b->getAttribute('DATE') == null) ) { return -1; } if (($b->getAttribute('DATE') != null) && ($a->getAttribute('DATE')==null) ) { return 1; } // If no sorting preference, then keep original ordering $ret = $a->sortOrder - $b->sortOrder; } return $ret; } // Allow native PHP functions such as array_unique() to work with objects public function __toString() { return $this->fact_id . '@' . $this->parent->getXref(); } }
cgeltly/treechecker
app/models/webtrees/Fact.php
PHP
gpl-3.0
14,911
import Palabra from '../../models/palabras' import { GROUP_ID } from '../../config' /** * Obtiene el ranking de palabras más usadas. * @param {*} msg */ const ranking = async msg => { if(msg.chat.id !== GROUP_ID) return; try { let palabras = await Palabra.find({}).sort('-amount').exec(); if (palabras.length >= 3) { await msg.reply.text( `${palabras[0].palabra} (${palabras[0].amount} veces), ` + `${palabras[1].palabra} (${palabras[1].amount} veces), ` + `${palabras[2].palabra} (${palabras[2].amount} veces)` ); } else if (palabras.length === 2) { await msg.reply.text( `${palabras[0].palabra} (${palabras[0].amount} veces), ` + `${palabras[1].palabra} (${palabras[1].amount} veces)` ); } else if (palabras.length === 1) { await msg.reply.text( `${palabras[0].palabra} (${palabras[0].amount} veces)` ); } else { await msg.reply.text('Hablen más por favor'); } return 0; } catch (err) { console.error(err.message || err); return; } }; export default bot => bot.on(['/ranking'], ranking)
jesusgn90/etsiit-moderator
lib/lib/estadisticas/estadisticas.js
JavaScript
gpl-3.0
1,257
# from mainsite.models import Web_Region context = {'title': 'my static title', 'description': 'my static description', 'data': 'my static data', } def get_context(request): # region_list = Web_Region.objects.values_list('region_name', flat=True) context.update({'data': 'my dynamic data'}) return context
sstacha/uweb-vagrant
files/docroot/files/test.data.py
Python
gpl-3.0
364
var Octopi = function(words) { this.uid = 0; this.tree = {$$: []}; this.table = {}; words = (words || []); for (var i = 0; i < words.length; i++) this.add(words[i]); }; /** * Take serialized Octopi data as string and initialize the Octopi object * @param json String The serialized Octopi trie */ Octopi.load = function(json){ var oct = new Octopi(); var o = JSON.parse(json); oct.uid = o.uid; oct.tree = o.tree; oct.table = o.table; return oct; } Octopi.prototype = { constructor: Octopi, /** * Add a new element to the trie * @param key String prefix to look up * @param data Object returned by trie */ add: function(key, data) { var id = ++this.uid; var sub = this.tree; this.table[id] = data || key; sub.$$.push(id); for (var i = 0; i < key.length; i++) { var c = key[i]; sub = sub[c] || (sub[c] = {$$:[]}); sub.$$.push(id); } }, /** * Return the list of elements in the trie for a given query * @param key String The prefix to lookup */ get: function(key) { var sub = this.tree; var tbl = this.table; for (var i = 0; i < key.length; i++) if (!(sub = sub[key[i]])) return []; return sub.$$.map(function(id) { return tbl[id]; }); }, /** * Serialize the Octopi trie as string * * @return String */ serialize: function(){ var o = { uid: this.uid, tree: this.tree, table: this.table } return JSON.stringify(o); } }; //Search core code var trie_data = AUTOCOMPLETE_PLUGIN_REPLACE; var Autocomplete = function() { this.oct = new Octopi(); }; Autocomplete.prototype = { load_data: function(data) { for (var i = 0; data[i]; i++) { var info = { 'w': data[i][0], 'd': data[i][1], 's': data[i][2] } this.oct.add(data[i][0], info) } }, get: function(str) { // Fixme: cleanup malicious input var candidates = this.oct.get(str); return candidates.sort(function(a,b){ return (a.s < b.s) ? 1: -1; } ); } }; // Export needed functions/data to the global context window.Autocomplete = Autocomplete; window.trie_data = trie_data;
ebursztein/SiteFab
plugins/site/rendering/autocomplete/autocomplete.js
JavaScript
gpl-3.0
2,263
<?php namespace at\eisisoft\partywithme\api; /** * Created by PhpStorm. * User: Florian * Date: 05.03.2016 * Time: 09:11 */ use at\eisisoft\partywithme as pwm; use function at\eisisoft\partywithme\api\fetchEvents; use function at\eisisoft\partywithme\api\toJSON; require_once "../hidden/partials/jsonHeader.php"; $fbLogin = isFbLogin(); $sql = file_get_contents(resolveFileRelativeToHidden("resources/sql/api/allevents.sql")); if (fetchEvents($fbLogin)) { try { $connection = pwm\MySQLHelper::getConnection(); $pstmt = $connection->prepare($sql); $pstmt->bindValue(":userId", $fbLogin[FB_USER_ID_KEY], \PDO::PARAM_STR); toJSON($pstmt);; } catch (\PDOException $e) { echo "[]"; } } ?>
reisi007/Party-With-Me
api/listEvents.php
PHP
gpl-3.0
743
(function() { var billerModule = angular.module('billerModule'); billerModule.filter('offset', function() { return function(input, start) { start = parseInt(start, 10); return input != null ? input.slice(start) : []; }; }); billerModule.directive('billRecalculationInfo', function() { return { restrict : 'AE', templateUrl : 'html/bills/bill-recalculation-info.html', controller : ['$scope', '$rootScope', '$http', function($scope, $rootScope, $http) { $scope.init = function() { $scope.itemsPerPage = 10; $scope.pageCurrentBills = 0; $scope.pageNonExistingBills = 0; }; $scope.setCurrentBillsPage = function(value) { $scope.pageCurrentBills = value; }; $scope.setNonExistingBillsPage = function(value) { $scope.pageNonExistingBills = value; }; $scope.init(); }], require : '^ngModel', replace : 'true', scope : { entity : '=ngModel' } }; }); billerModule.controller('BillRecalculationCtrl', [ '$scope', '$rootScope', '$routeParams', '$http', 'dialogs', function($scope, $rootScope, $routeParams, $http, dialogs) { $scope.init = function() { $scope.modes = [ { id: 'byStore', label:'Por establecimiento' }, { id: 'byCompany', label:'Por operador' }, { id: 'allBills', label:'Todos' } ]; $scope.months = [ { id: '1', label: "Enero"}, { id: '2', label: "Febrero"}, { id: '3', label: "Marzo"}, { id: '4', label: "Abril"}, { id: '5', label: "Mayo"}, { id: '6', label: "Junio"}, { id: '7', label: "Julio"}, { id: '8', label: "Agosto"}, { id: '9', label: "Septiembre"}, { id: '10', label: "Octubre"}, { id: '11', label: "Noviembre"}, { id: '12', label: "Diciembre"}, ]; $scope.options = { mode: $scope.modes[0]}; }; $scope.prepareBill = function() { $http.get('rest/recalculation/prepare/bill', { params: { y: $scope.options.year, m: $scope.options.month != null ? $scope.options.month.id : null, s: $scope.options.store != null && $scope.options.mode.id == 'byStore' ? $scope.options.store.id : null, c: $scope.options.company != null && $scope.options.mode.id == 'byCompany' ? $scope.options.company.id : null } }).success(function(data) { $scope.message = data; $scope.prepareResult = data.payload; }); }; $scope.cancelBillRecalculation = function() { $scope.prepareResult = null; }; $scope.executeBillRecalculation = function() { var dlg = dialogs.confirm('Confirmacion','Desea recalcular la factura? Los ajustes manuales se perderan'); dlg.result.then(function(btn){ $scope.message = {code: 200, info: ['billRecalculation.inProgress']}; $scope.isLoading = true; $scope.prepareResult.recalculateLiquidation = $scope.recalculateLiquidation; $http.post('rest/recalculation/execute/bill', $scope.prepareResult ).success(function(data) { $scope.message = data; $scope.results = data.payload; $scope.isLoading = false; }); }); }; $scope.init(); }]); })();
labcabrera/biller
biller-web/src/main/webapp/js/controllers/bill-recalculation-ctrl.js
JavaScript
gpl-3.0
3,019
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.1-b02-fcs // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2010.12.22 at 06:47:20 AM EET // package bias.extension.DashBoard.xmlb; import jakarta.xml.bind.annotation.XmlRegistry; /** * This object contains factory methods for each * Java content interface and Java element interface * generated in the bias.extension.DashBoard.xmlb package. * <p>An ObjectFactory allows you to programatically * construct new instances of the Java representation * for XML content. The Java representation of XML * content can consist of schema derived interfaces * and classes representing the binding of schema * type definitions, element declarations and model * groups. Factory methods for each of these are * provided in this class. * */ @XmlRegistry public class ObjectFactory { /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: bias.extension.DashBoard.xmlb * */ public ObjectFactory() { } /** * Create an instance of {@link Frames } * */ public Frames createFrames() { return new Frames(); } /** * Create an instance of {@link Frame } * */ public Frame createFrame() { return new Frame(); } }
kion/Bias
src/bias/extension/DashBoard/xmlb/ObjectFactory.java
Java
gpl-3.0
1,528
<?php /** * TrcIMPLAN Sitio Web - Retrospectiva y estado actual del empleo en Torreón y la Zona Metropolitana de La Laguna * * Copyright (C) 2017 Guillermo Valdés Lozano <guivaloz@movimientolibre.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * @package TrcIMPLANSitioWeb */ namespace Blog; /** * Clase RestrospectivaEstadoActualEmpleo */ class RestrospectivaEstadoActualEmpleo extends \Base\PublicacionSchemaBlogPosting { /** * Constructor */ public function __construct() { // Ejecutar constructor en el padre parent::__construct(); // Título, autor y fecha $this->nombre = 'Retrospectiva y estado actual del empleo en Torreón y la ZML'; $this->autor = 'Lic. Rodrigo González Morales'; $this->fecha = '2014-09-26T08:05'; // El nombre del archivo a crear $this->archivo = 'retrospectiva-estado-actual-empleo'; // La descripción y claves dan información a los buscadores y redes sociales $this->descripcion = 'El empleo es uno de los principales indicadores, que muestra el desempeño económico de una ciudad, región o país. Desde hace 9 años Torreón y la Zona Metropolitana de la Laguna se habían separado a la alza de la media nacional.'; $this->claves = 'IMPLAN, Torreon, Empleo'; // Ruta al archivo HTML con el contenido $this->contenido_archivo_html = 'lib/Blog/RestrospectivaEstadoActualEmpleo.html'; // Para el Organizador $this->categorias = array('Empleo'); $this->fuentes = array(); $this->regiones = array(); } // constructor } // Clase RestrospectivaEstadoActualEmpleo ?>
TRCIMPLAN/trcimplan.github.io
lib/Blog/RestrospectivaEstadoActualEmpleo.php
PHP
gpl-3.0
2,450
package org.betonquest.betonquest.conditions; import org.betonquest.betonquest.Instruction; import org.betonquest.betonquest.api.Condition; import org.betonquest.betonquest.exceptions.InstructionParseException; import org.betonquest.betonquest.utils.PlayerConverter; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import java.util.Locale; @SuppressWarnings("PMD.CommentRequired") public class RideCondition extends Condition { private EntityType vehicle; private boolean any; public RideCondition(final Instruction instruction) throws InstructionParseException { super(instruction, true); final String name = instruction.next(); if ("any".equalsIgnoreCase(name)) { any = true; } else { try { vehicle = EntityType.valueOf(name.toUpperCase(Locale.ROOT)); } catch (final IllegalArgumentException e) { throw new InstructionParseException("Entity type " + name + " does not exist.", e); } } } @Override protected Boolean execute(final String playerID) { final Entity entity = PlayerConverter.getPlayer(playerID).getVehicle(); return entity != null && (any || entity.getType() == vehicle); } }
Co0sh/BetonQuest
src/main/java/org/betonquest/betonquest/conditions/RideCondition.java
Java
gpl-3.0
1,282
// // StateUtils.cs // // Author: // Willem Van Onsem <vanonsem.willem@gmail.com> // // Copyright (c) 2014 Willem Van Onsem // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. using System; using System.Collections.Generic; using System.Linq; using NUtils.Collections; namespace NUtils.Automata { /// <summary> /// Utility functions for <see cref="T:IState`2"/> instances. /// </summary> public static class StateUtils { #region Blankets /// <summary> /// Calculate the blanket of the given <see cref="T:IState`2"/> for the given <paramref name="blankettag"/>. /// </summary> /// <returns>The blanket.</returns> /// <param name="state">Current.</param> /// <param name="blankettag">Blankettag.</param> /// <typeparam name="TStateTag">The 1st type parameter.</typeparam> /// <typeparam name="TEdgeTag">The 2nd type parameter.</typeparam> /// <remarks> /// <para>A blanket is the set of states that can be reached by applying zero, one or more times the given tag onto the given state.</para> /// <para>Each state is included in its own blanket.</para> /// <para>The algorithm avoids loops by storing the already visited states.</para> /// <para>The order of the blanken is unique depth-first.</para> /// </remarks> public static IEnumerable<IState<TStateTag,TEdgeTag>> GetBlanket<TStateTag,TEdgeTag> (this IState<TStateTag,TEdgeTag> state, TEdgeTag blankettag) { yield return state; IState<TStateTag,TEdgeTag> current; Queue<IState<TStateTag,TEdgeTag>> todo = new Queue<IState<TStateTag, TEdgeTag>> (); HashSet<IState<TStateTag,TEdgeTag>> seen = new HashSet<IState<TStateTag, TEdgeTag>> (); seen.Add (state); todo.Enqueue (state); while (todo.Count > 0x00) { current = todo.Dequeue (); foreach (IState<TStateTag,TEdgeTag> target in current.TaggedEdges(blankettag).SelectMany ((x => x.ResultingStates))) { if (seen.Add (target)) { yield return target; todo.Enqueue (target); } } } } #endregion } }
KommuSoft/NUtils
NUtils/Automata/StateUtils.cs
C#
gpl-3.0
2,615
#!/usr/bin/python """ DES-CHAN: A Framework for Channel Assignment Algorithms for Testbeds This module provides a class to represent network graphs and conflict graphs. Authors: Matthias Philipp <mphilipp@inf.fu-berlin.de>, Felix Juraschek <fjuraschek@gmail.com> Copyright 2008-2013, Freie Universitaet Berlin (FUB). All rights reserved. These sources were developed at the Freie Universitaet Berlin, Computer Systems and Telematics / Distributed, embedded Systems (DES) group (http://cst.mi.fu-berlin.de, http://www.des-testbed.net) ------------------------------------------------------------------------------- This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ . -------------------------------------------------------------------------------- For further information and questions please use the web site http://www.des-testbed.net """ import re import sys class Graph: def __init__(self, vertices=[]): # initialize internal data structures self.values = dict() self.distances = dict() # set vertex names and distances for vertex in vertices: self.add_vertex(vertex) def add_vertex(self, new_vertex): """Adds the given vertex to the graph. """ # do nothing if vertex already exists if new_vertex in self.get_vertices(): return # otherwise set up data structures for new vertex self.values[new_vertex] = dict() self.distances[new_vertex] = dict() for old_vertex in self.get_vertices(): self.set_edge_value((old_vertex, new_vertex), None, False) self.set_distance(old_vertex, new_vertex, sys.maxint) # distance to itself is 0 self.set_distance(new_vertex, new_vertex, 0) def remove_vertex(self, vertex): """Removes the given vertex from the graph. """ del self.values[vertex] del self.distances[vertex] for v in self.get_vertices(): del self.values[v][vertex] del self.distances[v][vertex] def get_vertices(self): """Returns a list that contains all vertices of the graph. """ return set(self.values.keys()) def set_edge_value(self, edge, value, update=True): """Sets the value of the given edge. The edge is represented by a tuple of two vertices. """ v1, v2 = edge self.values[v1][v2] = value # we implement an undirected graph self.values[v2][v1] = value # update distance information # None, "", False, and 0 correspond to no edge if value: self.set_distance(v1, v2, 1) # other shortest paths may have changed if update: self.update_distances() def set_distance(self, v1, v2, d): """Sets the distance between the two vertices. """ self.distances[v1][v2] = d # we implement an undirected graph self.distances[v2][v1] = d def get_edge_value(self, edge): """Returns the value of the given edge. The edge is represented by a tuple of two vertices. """ v1, v2 = edge return self.values[v1][v2] def get_distance(self, v1, v2): """Returns the distance between v1 and v2. """ return self.distances[v1][v2] def get_edges(self, get_all=False): """Returns a dictionary that contains all edges as keys and the corresponding edge values as values. Only edges that have a value are returned. By default the graph is assumed to be undirected. If the optional parameter get_all is True, all vertices are returned. """ edges = dict() remaining_vertices = self.get_vertices() for v1 in self.get_vertices(): for v2 in remaining_vertices: value = self.get_edge_value((v1, v2)) # None, "", False, and 0 correspond to no edge if value: edges[(v1, v2)] = value # graph is assumed to be undirected, therefore discard # duplicate edges if not explicitly requested if not get_all: remaining_vertices.remove(v1) return edges def merge(self, graph): """Merges the current graph with the specified graph. The new graph contains the union of both vertex sets and the corresponding edge values. """ # add missing vertices for vertex in graph.get_vertices() - self.get_vertices(): self.add_vertex(vertex) # set edge values for edge, edge_value in graph.get_edges().items(): self.set_edge_value(edge, edge_value, False) self.update_distances() def get_adjacency_matrix(self): """Returns the graph's adjacency matrix as a formatted string. """ vertices = self.values.keys() maxlen = 4 # get maximum length of vertex names for proper layout for vertex in vertices: if len(str(vertex)) > maxlen: maxlen = len(str(vertex)) # print column heads matrix = "".rjust(maxlen) + " |" for vertex in vertices: matrix += " " + str(vertex).rjust(maxlen) + " |" # print without trailing | matrix = matrix[:-1] + "\n" # generate row separator matrix += "-" * maxlen + "-+" for i in range(len(vertices)): matrix += "-" + "-" * maxlen + "-+" # print without trailing + matrix = matrix[:-1] + "\n" # print rows for v1 in vertices: matrix += str(v1).ljust(maxlen) + " |" for v2 in vertices: matrix += " " + self._get_edge_value_as_text((v1, v2)).rjust(maxlen) + " |" # print without trailing | matrix = matrix[:-1] + "\n" return matrix def get_graphviz(self, label=""): """Returns a string representation of the graph in the dot language from the graphviz project. """ left_vertices = set(self.values.keys()) graph = "Graph G {\n" if label != "": graph += "\tgraph [label = \"%s\", labelloc=t]\n" % label for v1 in self.values.keys(): for v2 in left_vertices: if self.get_edge_value((v1, v2)): graph += "\t\"" + str(v1) + "\" -- \"" + str(v2) + "\" " graph += "[label = \"" + str(self.get_edge_value((v1, v2))) + "\"]\n" # undirected graph, therefore discard double connections left_vertices.remove(v1) graph += "}\n" return graph def write_to_file(self, file_name, use_graphviz=False): """Writes a textual representation of the graph to the specified file. If the optional parameter use_graphviz is True, the graph is represented in the dot language from the graphviz project. """ file = open(file_name, 'w') if use_graphviz: file.write(self.get_graphviz()) else: file.write(self.get_adjacency_matrix()) file.close() def read_from_dotfile(self, file_name): """Reads the graph from a graphviz dot file. """ file = open(file_name, 'r') # clear current data self.__init__() # match following lines # "t9-035" -- "t9-146" [label = "1"] edge_re = re.compile('\s*"(.+)" -- "(.+)" \[label = "(.+)"\]') for line in file: edge_ma = edge_re.match(line) if edge_ma: v1 = edge_ma.group(1) v2 = edge_ma.group(2) value = edge_ma.group(3) self.add_vertex(v1) self.add_vertex(v2) self.set_edge_value((v1, v2), value, False) file.close() self.update_distances() def read_from_file(self, file_name): """Reads the graph from a file containing an adjacency matrix as generated by get_adjacency_matrix() or write_to_file(). The dot format is not supported. """ file = open(file_name, 'r') # line counter i = 0; vertices = list() for line in file: i += 1 # first line contains the vertex names if i == 1: # first element is empty, therefore discard it for vertex in line.split("|")[1:]: vertices.append(vertex.strip()) # clear current data and set new vertices self.__init__(vertices) if i > 2: row = line.split("|") # first element is the vertex name v1 = row[0].strip() # remaining elements are edge values row = row[1:] for v2 in vertices: value = row[vertices.index(v2)].strip() if value == '': value = None self.set_edge_value((v1, v2), value, False) file.close() self.update_distances() def update_distances(self): """Updates the distance matrix with the number of hops between all vertex pairs. """ # Floyd Warshall algorithm # calculate all shortest paths for k in self.get_vertices(): remaining_vertices = self.get_vertices() for v1 in self.get_vertices(): for v2 in remaining_vertices: d = min(self.get_distance(v1, v2), self.get_distance(v1, k) + self.get_distance(k, v2)) self.set_distance(v1, v2, d) remaining_vertices.remove(v1) def get_neighbors(self, vertex): """Returns a set that contains all direct neighbors of the given vertex. """ neighbors = set() for v1, v2 in self.get_edges().keys(): if v1 == vertex: neighbors.add(v2) elif v2 == vertex: neighbors.add(v1) return neighbors def copy(self): """Returns a new Graph object that contains the same vertices and edges. """ remaining_vertices = self.get_vertices() g = Graph(list(remaining_vertices)) for v1 in self.get_vertices(): for v2 in remaining_vertices: g.set_edge_value((v1, v2), self.get_edge_value((v1, v2))) g.set_distance(v1, v2, self.get_distance(v1, v2)) remaining_vertices.remove(v1) return g def copy_fast(self): """Returns a new Graph object that contains the same vertices and edges. """ remaining_vertices = self.get_vertices() g = Graph(list(remaining_vertices)) e = self.get_edges() for (v1, v2), chans in self.get_edges().iteritems(): g.set_edge_value((v1,v2), self.get_edge_value((v1, v2)), update=False) g.set_distance(v1, v2, self.get_distance(v1, v2)) return g def _get_edge_value_as_text(self, edge): """Returns a textual representation of the value of the given edge. The edge is represented by a tuple of two vertices. """ v1, v2 = edge if not self.values[v1][v2]: return "" else: return str(self.values[v1][v2]) class ConflictGraphVertex: def __init__(self, conflict_graph, nw_graph_edge): self.conflict_graph = conflict_graph self.nw_graph_edge = nw_graph_edge self.channels = None def __str__(self): return "%s_%s" % (self.nw_graph_edge) def get_channel(self): """Returns the channel of the link in the network graph that corresponds to this vertex. """ return int(self.conflict_graph.network_graph.get_edge_value(self.nw_graph_edge)) def set_channel(self, channel): """Sets the channel in the network graph and computes the resulting conflict graph. """ # update network graph self.conflict_graph.network_graph.set_edge_value(self.nw_graph_edge, str(channel)) # update conflict graph # NOTE the change: We do not have to recalculate ALL edges, just the onces # adjacent to the changed one are enough! gives us O(n) instead of O(n*n) self.conflict_graph.update_edge(self) # self.conflict_graph.update_edges() def get_nw_graph_neighbor(self, node_name): """Returns the neigbor in the network graph corresponding to the link. """ if node_name not in self.nw_graph_edge: return None if self.nw_graph_edge[0] == node_name: return self.nw_graph_edge[1] else: return self.nw_graph_edge[0] class ConflictGraph(Graph): def __init__(self, network_graph, interference_model): # store the original network graph for later reference self.network_graph = network_graph self.interference_model = interference_model vertices = set() # each edge in the network graph corresponds to a vertex in the conflict # graph for edge in network_graph.get_edges().keys(): vertices.add(ConflictGraphVertex(self, edge)) # call constructor of the super-class with new vertex set Graph.__init__(self, vertices) # set edges according to interference model self.update_edges() def update_edges(self): """Updates all edges of the ConflictGraph regarding the current channel assignment and the applied interference model. """ remaining_vertices = self.get_vertices() for v1 in self.get_vertices(): for v2 in remaining_vertices: # get edge value according to the interference model value = self.interference_model.get_interference(self.network_graph, v1.nw_graph_edge, v2.nw_graph_edge) self.set_edge_value((v1, v2), value, False) # graph is undirected remaining_vertices.remove(v1) def update_edge(self, cg_vertex): """Updates all edges that are adjacent to the supplied cg_vertex. """ remaining_vertices = self.get_vertices() for v2 in self.get_vertices(): # get edge value according to the interference model value = self.interference_model.get_interference(self.network_graph, cg_vertex.nw_graph_edge, v2.nw_graph_edge) self.set_edge_value((cg_vertex, v2), value, False) def get_vertices_for_node(self, node_name): """Returns a set containing all vertices that correspond to links that are incident to the given node. """ vertices = set() for vertex in self.get_vertices(): if vertex.nw_graph_edge[0] == node_name or \ vertex.nw_graph_edge[1] == node_name: vertices.add(vertex) return vertices def get_vertex(self, node1, node2): """Returns the vertex that corresponds to the link between the two given node names, or None, if such vertex does not exist. """ for vertex in self.get_vertices(): if (vertex.nw_graph_edge[0] == node1 and \ vertex.nw_graph_edge[1] == node2) or \ (vertex.nw_graph_edge[0] == node2 and \ vertex.nw_graph_edge[1] == node1): return vertex return None def get_interference_sum(self): """Returns the overall interference which is calculated by summing up all edge values. """ sum = 0 for value in self.get_edges().values(): sum += value return sum def get_vertex_names(self): vertex_names = set() for vertex in self.get_vertices(): vertex_names.add(str(vertex)) return vertex_names def update(self, network_graph): old_edges = self.network_graph.get_edges() new_edges = network_graph.get_edges() # do nothing if graphs are equal if new_edges == old_edges: return old_edges_keys = set(old_edges.keys()) new_edges_keys = set(new_edges.keys()) # assign new network graph self.network_graph = network_graph # update conflict graph for new_edge in new_edges_keys - old_edges_keys: # create a new conflict graph vertex for each new network graph edge self.add_vertex(ConflictGraphVertex(self, new_edge)) for obsolete_edge in old_edges_keys - new_edges_keys: # remove conflict graph vertices for obsolete edges self.remove_vertex(self.get_vertex(obsolete_edge[0], obsolete_edge[1])) self.update_edges() # this only runs if the module was *not* imported if __name__ == '__main__': g = Graph(["a", "b", "c", "d", "e"]) g.set_edge_value(("a", "b"), 40) g.set_edge_value(("b", "c"), 40) g.set_edge_value(("c", "d"), 40) g.set_edge_value(("d", "e"), 40) print g.get_adjacency_matrix()
des-testbed/des_chan
graph.py
Python
gpl-3.0
18,151
module.exports = function (grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), sass: { dist: { options: { style: 'compressed' }, files: { 'assets/css/global.css': 'src/sass/global.scss' } } }, concat: { options: { separator: ';' }, dist: { src: ['src/js/**.js'], dest: 'assets/js/global.js' } }, uglify: { my_target: { files: { 'assets/js/global.min.js': ['assets/js/global.js'] } } }, autoprefixer: { options: { map: true, browsers: ['Last 8 versions', 'IE > 7', '> 1%'] }, css: { src: 'assets/css/*.css' } }, watch: { sass: { files: ['src/sass/**/*.scss'], tasks: ['sass', 'autoprefixer'] }, js: { files: ['src/js/**/*.js'], tasks: ['concat', 'uglify'] } } }); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-sass'); grunt.loadNpmTasks('grunt-autoprefixer'); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.registerTask('default', ['sass', 'autoprefixer', 'concat', 'uglify']); };
Treenity/bbpress-wp-support
gruntfile.js
JavaScript
gpl-3.0
1,604
package it.kytech.skywars; import java.util.Arrays; import java.util.HashMap; import java.util.Vector; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginDescriptionFile; import it.kytech.skywars.MessageManager.PrefixType; import it.kytech.skywars.commands.AddWall; import it.kytech.skywars.commands.CreateArena; import it.kytech.skywars.commands.DelArena; import it.kytech.skywars.commands.Disable; import it.kytech.skywars.commands.Enable; import it.kytech.skywars.commands.ForceStart; import it.kytech.skywars.commands.Join; import it.kytech.skywars.commands.Leave; import it.kytech.skywars.commands.LeaveQueue; import it.kytech.skywars.commands.ListArenas; import it.kytech.skywars.commands.ListPlayers; import it.kytech.skywars.commands.Reload; import it.kytech.skywars.commands.ResetSpawns; import it.kytech.skywars.commands.SetLobbySpawn; import it.kytech.skywars.commands.SetLobbyWall; import it.kytech.skywars.commands.SetSpawn; import it.kytech.skywars.commands.Spectate; import it.kytech.skywars.commands.SubCommand; import it.kytech.skywars.commands.Teleport; import it.kytech.skywars.commands.Vote; public class CommandHandler implements CommandExecutor { private Plugin plugin; private HashMap < String, SubCommand > commands; private HashMap < String, Integer > helpinfo; private MessageManager msgmgr = MessageManager.getInstance(); public CommandHandler(Plugin plugin) { this.plugin = plugin; commands = new HashMap < String, SubCommand > (); helpinfo = new HashMap < String, Integer > (); loadCommands(); loadHelpInfo(); } private void loadCommands() { commands.put("createarena", new CreateArena()); commands.put("join", new Join()); commands.put("addwall", new AddWall()); commands.put("setspawn", new SetSpawn()); commands.put("getcount", new ListArenas()); commands.put("disable", new Disable()); commands.put("start", new ForceStart()); commands.put("enable", new Enable()); commands.put("vote", new Vote()); commands.put("leave", new Leave()); commands.put("setlobbyspawn", new SetLobbySpawn()); commands.put("setlobbywall", new SetLobbyWall()); commands.put("resetspawns", new ResetSpawns()); commands.put("delarena", new DelArena()); commands.put("spectate", new Spectate()); commands.put("lq", new LeaveQueue()); commands.put("leavequeue", new LeaveQueue()); commands.put("list", new ListPlayers()); commands.put("tp", new Teleport()); commands.put("reload", new Reload()); commands.put("reload", new Reload()); } private void loadHelpInfo() { //you can do this by iterating thru the hashmap from a certian index btw instead of using a new hashmap, //plus, instead of doing three differnet ifs, just iterate thru and check if the value == the page helpinfo.put("createarena", 3); helpinfo.put("join", 1); helpinfo.put("addwall", 3); helpinfo.put("setspawn", 3); helpinfo.put("getcount", 3); helpinfo.put("disable", 2); helpinfo.put("start", 2); helpinfo.put("enable", 2); helpinfo.put("vote", 1); helpinfo.put("leave", 1); helpinfo.put("setlobbyspawn", 3); helpinfo.put("resetspawns", 3); helpinfo.put("delarena", 3); helpinfo.put("flag", 3); helpinfo.put("spectate", 1); helpinfo.put("lq", 1); helpinfo.put("leavequeue", 1); helpinfo.put("list", 1); } @Override public boolean onCommand(CommandSender sender, Command cmd1, String commandLabel, String[] args) { PluginDescriptionFile pdfFile = plugin.getDescription(); if (!(sender instanceof Player)) { msgmgr.logMessage(PrefixType.WARNING, "Only in-game players can use SurvivalGames commands! "); return true; } Player player = (Player) sender; if (SkyWars.config_todate == false) { msgmgr.sendMessage(PrefixType.WARNING, "The config file is out of date. Please tell an administrator to reset the config.", player); return true; } if (SkyWars.dbcon == false) { msgmgr.sendMessage(PrefixType.WARNING, "Could not connect to server. Plugin disabled.", player); return true; } if (cmd1.getName().equalsIgnoreCase("skywar")) { if (args == null || args.length < 1) { msgmgr.sendMessage(PrefixType.INFO, "Version " + pdfFile.getVersion() + " by Double0negative", player); msgmgr.sendMessage(PrefixType.INFO, "Type /sw help <player | staff | admin> for command information", player); return true; } if (args[0].equalsIgnoreCase("help")) { if (args.length == 1) { help(player, 1); } else { if (args[1].toLowerCase().startsWith("player")) { help(player, 1); return true; } if (args[1].toLowerCase().startsWith("staff")) { help(player, 2); return true; } if (args[1].toLowerCase().startsWith("admin")) { help(player, 3); return true; } else { msgmgr.sendMessage(PrefixType.WARNING, args[1] + " is not a valid page! Valid pages are Player, Staff, and Admin.", player); } } return true; } String sub = args[0]; Vector < String > l = new Vector < String > (); l.addAll(Arrays.asList(args)); l.remove(0); args = (String[]) l.toArray(new String[0]); if (!commands.containsKey(sub)) { msgmgr.sendMessage(PrefixType.WARNING, "Command doesn't exist.", player); msgmgr.sendMessage(PrefixType.INFO, "Type /sw help for command information", player); return true; } try { commands.get(sub).onCommand(player, args); } catch (Exception e) { e.printStackTrace(); msgmgr.sendFMessage(PrefixType.ERROR, "error.command", player, "command-["+sub+"] "+Arrays.toString(args)); msgmgr.sendMessage(PrefixType.INFO, "Type /sw help for command information", player); } return true; } return false; } public void help (Player p, int page) { if (page == 1) { p.sendMessage(ChatColor.BLUE + "------------ " + msgmgr.pre + ChatColor.DARK_AQUA + " Player Commands" + ChatColor.BLUE + " ------------"); } if (page == 2) { p.sendMessage(ChatColor.BLUE + "------------ " + msgmgr.pre + ChatColor.DARK_AQUA + " Staff Commands" + ChatColor.BLUE + " ------------"); } if (page == 3) { p.sendMessage(ChatColor.BLUE + "------------ " + msgmgr.pre + ChatColor.DARK_AQUA + " Admin Commands" + ChatColor.BLUE + " ------------"); } for (String command : commands.keySet()) { try{ if (helpinfo.get(command) == page) { msgmgr.sendMessage(PrefixType.INFO, commands.get(command).help(p), p); } }catch(Exception e){} } /*for (SubCommand v : commands.values()) { if (v.permission() != null) { if (p.hasPermission(v.permission())) { msgmgr.sendMessage(PrefixType.INFO1, v.help(p), p); } else { msgmgr.sendMessage(PrefixType.WARNING, v.help(p), p); } } else { msgmgr.sendMessage(PrefixType.INFO, v.help(p), p); } }*/ } }
hitech95/SkyWars
src/main/java/it/kytech/skywars/CommandHandler.java
Java
gpl-3.0
7,097
package com.cole.somecraft.proxy; public interface IProxy { }
ClarmonkGaming/SomeCraftReboot
src/main/java/com/cole/somecraft/proxy/IProxy.java
Java
gpl-3.0
63
/* * //****************************************************************** * // * // Copyright 2016 Samsung Electronics All Rights Reserved. * // * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= * // * // Licensed under the Apache License, Version 2.0 (the "License"); * // you may not use this file except in compliance with the License. * // You may obtain a copy of the License at * // * // http://www.apache.org/licenses/LICENSE-2.0 * // * // Unless required by applicable law or agreed to in writing, software * // distributed under the License is distributed on an "AS IS" BASIS, * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * // See the License for the specific language governing permissions and * // limitations under the License. * // * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */ package org.iotivity.cloud.ciserver.resources; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import org.iotivity.cloud.base.device.CoapDevice; import org.iotivity.cloud.base.device.Device; import org.iotivity.cloud.base.device.IRequestChannel; import org.iotivity.cloud.base.device.IResponseEventHandler; import org.iotivity.cloud.base.exception.ServerException; import org.iotivity.cloud.base.exception.ServerException.BadRequestException; import org.iotivity.cloud.base.exception.ServerException.NotFoundException; import org.iotivity.cloud.base.exception.ServerException.PreconditionFailedException; import org.iotivity.cloud.base.protocols.IRequest; import org.iotivity.cloud.base.protocols.IResponse; import org.iotivity.cloud.base.protocols.MessageBuilder; import org.iotivity.cloud.base.protocols.coap.CoapResponse; import org.iotivity.cloud.base.protocols.enums.ContentFormat; import org.iotivity.cloud.base.protocols.enums.ResponseStatus; import org.iotivity.cloud.base.resource.Resource; import org.iotivity.cloud.ciserver.Constants; import org.iotivity.cloud.ciserver.DeviceServerSystem.CoapDevicePool; import org.iotivity.cloud.util.Cbor; /** * * This class provides a set of APIs to send requests about message to another * device * */ public class DiResource extends Resource { private CoapDevicePool mDevicePool = null; public DiResource(CoapDevicePool devicePool) { super(Arrays.asList(Constants.REQ_DEVICE_ID)); mDevicePool = devicePool; addQueryHandler( Arrays.asList(Constants.RS_INTERFACE + "=" + Constants.LINK_INTERFACE), this::onLinkInterfaceRequestReceived); } private IRequestChannel getTargetDeviceChannel(IRequest request) throws ServerException { List<String> uriPathSegment = request.getUriPathSegments(); if (uriPathSegment.size() < 2) { throw new PreconditionFailedException(); } String deviceId = uriPathSegment.get(1); CoapDevice targetDevice = (CoapDevice) mDevicePool .queryDevice(deviceId); if (targetDevice == null) { throw new NotFoundException(); } // Do request and receive response return targetDevice.getRequestChannel(); } private String extractTargetUriPath(IRequest request) { List<String> uriPathSegment = request.getUriPathSegments(); // Remove prefix path uriPathSegment.remove(0); uriPathSegment.remove(0); StringBuilder uriPath = new StringBuilder(); for (String path : uriPathSegment) { uriPath.append("/" + path); } return uriPath.toString(); } private IResponse convertReponseUri(IResponse response, String di) { String convertedUri = new String(); CoapResponse coapResponse = (CoapResponse) response; if (coapResponse.getUriPath().isEmpty() == false) { convertedUri = "/di/" + di + "/" + coapResponse.getUriPath(); } return MessageBuilder.modifyResponse(response, convertedUri, null, null); } /** * * This class provides a set of APIs to handling message contains link * interface. * */ class LinkInterfaceHandler implements IResponseEventHandler { private Cbor<List<HashMap<String, Object>>> mCbor = new Cbor<>(); private String mTargetDI = null; private Device mSrcDevice = null; public LinkInterfaceHandler(String targetDI, Device srcDevice) { mTargetDI = targetDI; mSrcDevice = srcDevice; } private void convertHref(List<HashMap<String, Object>> linkPayload) { for (HashMap<String, Object> link : linkPayload) { link.put("href", "/di/" + mTargetDI + link.get("href")); } } @Override public void onResponseReceived(IResponse response) { List<HashMap<String, Object>> linkPayload = null; if (response.getStatus() == ResponseStatus.CONTENT) { linkPayload = mCbor.parsePayloadFromCbor(response.getPayload(), ArrayList.class); if (linkPayload == null) { throw new BadRequestException("payload is null"); } convertHref(linkPayload); } mSrcDevice.sendResponse(MessageBuilder.modifyResponse( convertReponseUri(response, mTargetDI), ContentFormat.APPLICATION_CBOR, linkPayload != null ? mCbor.encodingPayloadToCbor(linkPayload) : null)); } } /** * API for handling optional method for handling packet contains link * interface. * * @param srcDevice * device information contains response channel * @param request * received request to relay */ public void onLinkInterfaceRequestReceived(Device srcDevice, IRequest request) throws ServerException { IRequestChannel requestChannel = getTargetDeviceChannel(request); if (requestChannel == null) { throw new NotFoundException(); } String deviceId = request.getUriPathSegments().get(1); requestChannel.sendRequest( MessageBuilder.modifyRequest(request, extractTargetUriPath(request), null, null, null), new LinkInterfaceHandler(deviceId, srcDevice)); } class DefaultResponseHandler implements IResponseEventHandler { private String mTargetDI = null; private Device mSrcDevice = null; public DefaultResponseHandler(String targetDI, Device srcDevice) { mTargetDI = targetDI; mSrcDevice = srcDevice; } @Override public void onResponseReceived(IResponse response) { mSrcDevice.sendResponse(convertReponseUri(response, mTargetDI)); } } @Override public void onDefaultRequestReceived(Device srcDevice, IRequest request) throws ServerException { // Find proper request channel using di in URI path field. IRequestChannel requestChannel = getTargetDeviceChannel(request); if (requestChannel == null) { throw new NotFoundException(); } String deviceId = request.getUriPathSegments().get(1); requestChannel.sendRequest( MessageBuilder.modifyRequest(request, extractTargetUriPath(request), null, null, null), new DefaultResponseHandler(deviceId, srcDevice)); } }
kadasaikumar/iotivity-1.2.1
cloud/interface/src/main/java/org/iotivity/cloud/ciserver/resources/DiResource.java
Java
gpl-3.0
7,727
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Repeat event collection tests. * * @package core_calendar * @copyright 2017 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); global $CFG; require_once($CFG->dirroot . '/calendar/lib.php'); use core_calendar\local\event\entities\event; use core_calendar\local\event\entities\repeat_event_collection; use core_calendar\local\event\proxies\coursecat_proxy; use core_calendar\local\event\proxies\std_proxy; use core_calendar\local\event\value_objects\event_description; use core_calendar\local\event\value_objects\event_times; use core_calendar\local\event\factories\event_factory_interface; /** * Repeat event collection tests. * * @copyright 2017 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class core_calendar_repeat_event_collection_testcase extends advanced_testcase { /** * Test that creating a repeat collection for a parent that doesn't * exist throws an exception. */ public function test_no_parent_collection() { $this->resetAfterTest(true); $parentid = 123122131; $factory = new core_calendar_repeat_event_collection_event_test_factory(); $this->expectException('\core_calendar\local\event\exceptions\no_repeat_parent_exception'); $collection = new repeat_event_collection($parentid, null, $factory); } /** * Test that an empty collection is valid. */ public function test_empty_collection() { $this->resetAfterTest(true); $this->setAdminUser(); $event = $this->create_event([ // This causes the code to set the repeat id on this record // but not create any repeat event records. 'repeat' => 1, 'repeats' => 0 ]); $parentid = $event->id; $factory = new core_calendar_repeat_event_collection_event_test_factory(); // Event collection with no repeats. $collection = new repeat_event_collection($parentid, null, $factory); $this->assertEquals($parentid, $collection->get_id()); $this->assertEquals(0, $collection->get_num()); $this->assertNull($collection->getIterator()->next()); } /** * Test that a collection with values behaves correctly. */ public function test_values_collection() { $this->resetAfterTest(true); $this->setAdminUser(); $factory = new core_calendar_repeat_event_collection_event_test_factory(); $event = $this->create_event([ // This causes the code to set the repeat id on this record // but not create any repeat event records. 'repeat' => 1, 'repeats' => 0 ]); $parentid = $event->id; $repeats = []; for ($i = 1; $i < 4; $i++) { $record = $this->create_event([ 'name' => sprintf('repeat %d', $i), 'repeatid' => $parentid ]); // Index by name so that we don't have to rely on sorting // when doing the comparison later. $repeats[$record->name] = $record; } // Event collection with no repeats. $collection = new repeat_event_collection($parentid, null, $factory); $this->assertEquals($parentid, $collection->get_id()); $this->assertEquals(count($repeats), $collection->get_num()); foreach ($collection as $index => $event) { $name = $event->get_name(); $this->assertEquals($repeats[$name]->name, $name); } } /** * Helper function to create calendar events using the old code. * * @param array $properties A list of calendar event properties to set * @return calendar_event */ protected function create_event($properties = []) { $record = new \stdClass(); $record->name = 'event name'; $record->eventtype = 'global'; $record->repeat = 0; $record->repeats = 0; $record->timestart = time(); $record->timeduration = 0; $record->timesort = 0; $record->type = 1; $record->courseid = 0; $record->categoryid = 0; foreach ($properties as $name => $value) { $record->$name = $value; } $event = new calendar_event($record); return $event->create($record, false); } } /** * Test event factory. * * @copyright 2017 Ryan Wyllie <ryan@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class core_calendar_repeat_event_collection_event_test_factory implements event_factory_interface { public function create_instance(\stdClass $dbrow) { $identity = function($id) { return $id; }; return new event( $dbrow->id, $dbrow->name, new event_description($dbrow->description, $dbrow->format), new coursecat_proxy($dbrow->categoryid), new std_proxy($dbrow->courseid, $identity), new std_proxy($dbrow->groupid, $identity), new std_proxy($dbrow->userid, $identity), new repeat_event_collection($dbrow->id, null, $this), new std_proxy($dbrow->instance, $identity), $dbrow->type, new event_times( (new \DateTimeImmutable())->setTimestamp($dbrow->timestart), (new \DateTimeImmutable())->setTimestamp($dbrow->timestart + $dbrow->timeduration), (new \DateTimeImmutable())->setTimestamp($dbrow->timesort ? $dbrow->timesort : $dbrow->timestart), (new \DateTimeImmutable())->setTimestamp($dbrow->timemodified) ), !empty($dbrow->visible), new std_proxy($dbrow->subscriptionid, $identity) ); } }
eSrem/moodle
calendar/tests/repeat_event_collection_test.php
PHP
gpl-3.0
6,590
// // // Generated by StarUML(tm) C++ Add-In // // @ Project : Untitled // @ File Name : StaticData.cpp // @ Date : 2017/9/29 // @ Author : ouo // // #include "StaticData.h" StaticData StaticData::sharedStaticData() { } viod StaticData::purge() { } int StaticData::intValueFormKey(std::string key) { } char StaticData::stringValueFromKey(std::string key) { } float StaticData::floatValueFromKey(std::string key) { } bool StaticData::booleanFromKey(std::string key) { } cocos2d::CCPoint StaticData::pointFromKey(std::string key) { } cocos2d::CCRect StaticData::rectFromKey(std::string key) { } cocos2d::CCSize StaticData::sizeFromKey(std::string key) { } bool StaticData::init() { } StaticData::~StaticData() { } StaticData::StaticData() { }
ouopoi/StaticData
StaticData/StaticData.cpp
C++
gpl-3.0
835
/* * Copyright (C) 2010-2021 JPEXS * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.jpexs.decompiler.flash.gui.abc; import com.jpexs.decompiler.flash.SWF; import com.jpexs.decompiler.flash.abc.ABC; import com.jpexs.decompiler.flash.abc.ScriptPack; import com.jpexs.decompiler.flash.abc.avm2.AVM2Code; import com.jpexs.decompiler.flash.abc.avm2.instructions.AVM2Instruction; import com.jpexs.decompiler.flash.abc.avm2.instructions.construction.ConstructSuperIns; import com.jpexs.decompiler.flash.abc.avm2.instructions.executing.CallSuperIns; import com.jpexs.decompiler.flash.abc.avm2.instructions.executing.CallSuperVoidIns; import com.jpexs.decompiler.flash.abc.types.ClassInfo; import com.jpexs.decompiler.flash.abc.types.InstanceInfo; import com.jpexs.decompiler.flash.abc.types.Multiname; import com.jpexs.decompiler.flash.abc.types.ScriptInfo; import com.jpexs.decompiler.flash.abc.types.traits.Trait; import com.jpexs.decompiler.flash.abc.types.traits.TraitFunction; import com.jpexs.decompiler.flash.abc.types.traits.TraitMethodGetterSetter; import com.jpexs.decompiler.flash.abc.types.traits.TraitSlotConst; import com.jpexs.decompiler.flash.action.deobfuscation.BrokenScriptDetector; import com.jpexs.decompiler.flash.gui.AppStrings; import com.jpexs.decompiler.flash.gui.Main; import com.jpexs.decompiler.flash.gui.View; import com.jpexs.decompiler.flash.gui.editor.DebuggableEditorPane; import com.jpexs.decompiler.flash.helpers.GraphTextWriter; import com.jpexs.decompiler.flash.helpers.HighlightedText; import com.jpexs.decompiler.flash.helpers.hilight.HighlightData; import com.jpexs.decompiler.flash.helpers.hilight.HighlightSpecialType; import com.jpexs.decompiler.flash.helpers.hilight.Highlighting; import com.jpexs.decompiler.flash.tags.ABCContainerTag; import com.jpexs.decompiler.graph.DottedChain; import com.jpexs.helpers.CancellableWorker; import com.jpexs.helpers.Reference; import java.awt.Point; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.event.CaretEvent; import javax.swing.event.CaretListener; import jsyntaxpane.SyntaxDocument; import jsyntaxpane.Token; import jsyntaxpane.TokenType; /** * * @author JPEXS */ public class DecompiledEditorPane extends DebuggableEditorPane implements CaretListener { private static final Logger logger = Logger.getLogger(DecompiledEditorPane.class.getName()); private HighlightedText highlightedText = HighlightedText.EMPTY; private Highlighting currentMethodHighlight; private Highlighting currentTraitHighlight; private ScriptPack script; public int lastTraitIndex = GraphTextWriter.TRAIT_UNKNOWN; public boolean ignoreCarret = false; private boolean reset = false; private final ABCPanel abcPanel; private int classIndex = -1; private boolean isStatic = false; private CancellableWorker setSourceWorker; private final List<Runnable> scriptListeners = new ArrayList<>(); public void addScriptListener(Runnable l) { scriptListeners.add(l); } public ABCPanel getAbcPanel() { return abcPanel; } public void removeScriptListener(Runnable l) { scriptListeners.remove(l); } public void fireScript() { Runnable[] listeners = scriptListeners.toArray(new Runnable[scriptListeners.size()]); for (Runnable scriptListener : listeners) { scriptListener.run(); } } public Trait getCurrentTrait() { if (lastTraitIndex < 0) { return null; } if (classIndex == -1) { return script.abc.script_info.get(script.scriptIndex).traits.traits.get(lastTraitIndex); } return script.abc.findTraitByTraitId(classIndex, lastTraitIndex); } public ScriptPack getScriptLeaf() { return script; } public boolean getIsStatic() { return isStatic; } public void setNoTrait() { abcPanel.detailPanel.showCard(DetailPanel.UNSUPPORTED_TRAIT_CARD, null, 0); } public void hilightSpecial(HighlightSpecialType type, long index) { int startPos; int endPos; if (currentMethodHighlight == null) { if (currentTraitHighlight == null) { return; } startPos = currentTraitHighlight.startPos; endPos = currentTraitHighlight.startPos + currentTraitHighlight.len; } else { startPos = currentMethodHighlight.startPos; endPos = currentMethodHighlight.startPos + currentMethodHighlight.len; } List<Highlighting> allh = new ArrayList<>(); for (Highlighting h : highlightedText.getTraitHighlights()) { if (h.getProperties().index == lastTraitIndex) { for (Highlighting sh : highlightedText.getSpecialHighlights()) { if (sh.startPos >= h.startPos && (sh.startPos + sh.len < h.startPos + h.len)) { allh.add(sh); } } } } if (currentMethodHighlight != null) { for (Highlighting h : highlightedText.getSpecialHighlights()) { if (h.startPos >= startPos && (h.startPos + h.len < endPos)) { allh.add(h); } } } for (Highlighting h : allh) { if (h.getProperties().subtype.equals(type) && (h.getProperties().index == index)) { ignoreCarret = true; if (h.startPos <= getDocument().getLength()) { setCaretPosition(h.startPos); } getCaret().setVisible(true); ignoreCarret = false; break; } } } public void hilightOffset(long offset) { if (currentMethodHighlight == null) { return; } Highlighting h2 = Highlighting.searchOffset(highlightedText.getInstructionHighlights(), offset, currentMethodHighlight.startPos, currentMethodHighlight.startPos + currentMethodHighlight.len); if (h2 != null) { ignoreCarret = true; if (h2.startPos <= getDocument().getLength()) { setCaretPosition(h2.startPos); } getCaret().setVisible(true); ignoreCarret = false; } } public void setClassIndex(int classIndex) { this.classIndex = classIndex; } private boolean displayMethod(int pos, int methodIndex, String name, Trait trait, int traitIndex, boolean isStatic) { ABC abc = getABC(); if (abc == null) { return false; } int bi = abc.findBodyIndex(methodIndex); if (bi == -1) { return false; } //fix for inner functions: if (trait instanceof TraitMethodGetterSetter) { TraitMethodGetterSetter tm = (TraitMethodGetterSetter) trait; if (tm.method_info != methodIndex) { trait = null; } } if (trait instanceof TraitFunction) { TraitFunction tf = (TraitFunction) trait; if (tf.method_info != methodIndex) { trait = null; } } abcPanel.detailPanel.showCard(DetailPanel.METHOD_GETTER_SETTER_TRAIT_CARD, trait, traitIndex); MethodCodePanel methodCodePanel = abcPanel.detailPanel.methodTraitPanel.methodCodePanel; if (reset || (methodCodePanel.getBodyIndex() != bi)) { methodCodePanel.setBodyIndex(scriptName, bi, abc, name, trait, script.scriptIndex); abcPanel.detailPanel.setEditMode(false); this.isStatic = isStatic; } boolean success = false; Highlighting h = Highlighting.searchPos(highlightedText.getInstructionHighlights(), pos); if (h != null) { methodCodePanel.hilighOffset(h.getProperties().offset); success = true; } Highlighting sh = Highlighting.searchPos(highlightedText.getSpecialHighlights(), pos); if (sh != null) { methodCodePanel.hilighSpecial(sh.getProperties().subtype, sh.getProperties().specialValue); success = true; } return success; } public void displayClass(int classIndex, int scriptIndex) { if (abcPanel.navigator.getClassIndex() != classIndex) { abcPanel.navigator.setClassIndex(classIndex, scriptIndex); } } public void resetEditing() { reset = true; caretUpdate(null); reset = false; } public int getMultinameUnderMouseCursor(Point pt, Reference<ABC> abcUsed) { return getMultinameAtPos(viewToModel(pt), abcUsed); } public int getMultinameUnderCaret(Reference<ABC> abcUsed) { return getMultinameAtPos(getCaretPosition(), abcUsed); } public int getLocalDeclarationOfPos(int pos, Reference<DottedChain> type) { Highlighting sh = Highlighting.searchPos(highlightedText.getSpecialHighlights(), pos); Highlighting h = Highlighting.searchPos(highlightedText.getInstructionHighlights(), pos); if (h == null) { return -1; } List<Highlighting> tms = Highlighting.searchAllPos(highlightedText.getMethodHighlights(), pos); if (tms.isEmpty()) { return -1; } for (Highlighting tm : tms) { List<Highlighting> tm_tms = Highlighting.searchAllIndexes(highlightedText.getMethodHighlights(), tm.getProperties().index); //is it already declaration? if (h.getProperties().declaration || (sh != null && sh.getProperties().declaration)) { return -1; //no jump } String lname = h.getProperties().localName; if ("this".equals(lname)) { Highlighting ch = Highlighting.searchPos(highlightedText.getClassHighlights(), pos); int cindex = (int) ch.getProperties().index; ABC abc = getABC(); type.setVal(abc.instance_info.get(cindex).getName(abc.constants).getNameWithNamespace(abc.constants, true)); return ch.startPos; } HighlightData hData = h.getProperties(); HighlightData search = new HighlightData(); search.declaration = hData.declaration; search.declaredType = hData.declaredType; search.localName = hData.localName; search.specialValue = hData.specialValue; if (search.isEmpty()) { return -1; } search.declaration = true; for (Highlighting tm1 : tm_tms) { Highlighting rh = Highlighting.search(highlightedText.getInstructionHighlights(), search, tm1.startPos, tm1.startPos + tm1.len); if (rh == null) { rh = Highlighting.search(highlightedText.getSpecialHighlights(), search, tm1.startPos, tm1.startPos + tm1.len); } if (rh != null) { type.setVal(rh.getProperties().declaredType); return rh.startPos; } } } return -1; } public boolean getPropertyTypeAtPos(int pos, Reference<Integer> abcIndex, Reference<Integer> classIndex, Reference<Integer> traitIndex, Reference<Boolean> classTrait, Reference<Integer> multinameIndex, Reference<ABC> abcUsed) { int m = getMultinameAtPos(pos, true, abcUsed); if (m <= 0) { return false; } SyntaxDocument sd = (SyntaxDocument) getDocument(); Token t = sd.getTokenAt(pos + 1); Token lastToken = t; Token prev; while (t.type == TokenType.IDENTIFIER || t.type == TokenType.KEYWORD || t.type == TokenType.REGEX) { prev = sd.getPrevToken(t); if (prev != null) { if (!".".equals(prev.getString(sd))) { break; } t = sd.getPrevToken(prev); } else { break; } } if (t.type != TokenType.IDENTIFIER && t.type != TokenType.KEYWORD && t.type != TokenType.REGEX) { return false; } Reference<DottedChain> locTypeRef = new Reference<>(DottedChain.EMPTY); getLocalDeclarationOfPos(t.start, locTypeRef); DottedChain currentType = locTypeRef.getVal(); if (currentType.equals(DottedChain.ALL)) { return false; } boolean found; while (!currentType.equals(DottedChain.ALL)) { String ident = t.getString(sd); found = false; List<ABCContainerTag> abcList = abcUsed.getVal().getSwf().getAbcList(); loopi: for (int i = 0; i < abcList.size(); i++) { ABC a = abcList.get(i).getABC(); int cindex = a.findClassByName(currentType); if (cindex > -1) { InstanceInfo ii = a.instance_info.get(cindex); for (int j = 0; j < ii.instance_traits.traits.size(); j++) { Trait tr = ii.instance_traits.traits.get(j); if (ident.equals(tr.getName(a).getName(a.constants, null, false /*NOT RAW!*/, true))) { classIndex.setVal(cindex); abcIndex.setVal(i); traitIndex.setVal(j); classTrait.setVal(false); multinameIndex.setVal(tr.name_index); currentType = ii.getName(a.constants).getNameWithNamespace(a.constants, true); found = true; break loopi; } } ClassInfo ci = a.class_info.get(cindex); for (int j = 0; j < ci.static_traits.traits.size(); j++) { Trait tr = ci.static_traits.traits.get(j); if (ident.equals(tr.getName(a).getName(a.constants, null, false /*NOT RAW!*/, true))) { classIndex.setVal(cindex); abcIndex.setVal(i); traitIndex.setVal(j); classTrait.setVal(true); multinameIndex.setVal(tr.name_index); currentType = ii.getName(a.constants).getNameWithNamespace(a.constants, true); found = true; break loopi; } } } } if (!found) { return false; } if (t == lastToken) { break; } t = sd.getNextToken(t); if (!".".equals(t.getString(sd))) { break; } t = sd.getNextToken(t); } return true; } public int getMultinameAtPos(int pos, Reference<ABC> abcUsed) { return getMultinameAtPos(pos, false, abcUsed); } private int getMultinameAtPos(int pos, boolean codeOnly, Reference<ABC> abcUsed) { int multinameIndex = _getMultinameAtPos(pos, codeOnly, abcUsed); if (multinameIndex > -1) { ABC abc = abcUsed.getVal(); multinameIndex = abc.constants.convertToQname(abc.constants, multinameIndex); } return multinameIndex; } public int _getMultinameAtPos(int pos, boolean codeOnly, Reference<ABC> abcUsed) { Highlighting tm = Highlighting.searchPos(highlightedText.getMethodHighlights(), pos); Trait currentTrait = null; int currentMethod = -1; ABC abc = getABC(); abcUsed.setVal(abc); if (abc == null) { return -1; } if (tm != null) { int mi = (int) tm.getProperties().index; currentMethod = mi; int bi = abc.findBodyIndex(mi); Highlighting h = Highlighting.searchPos(highlightedText.getInstructionHighlights(), pos); if (h != null) { long highlightOffset = h.getProperties().offset; List<AVM2Instruction> list = abc.bodies.get(bi).getCode().code; AVM2Instruction lastIns = null; AVM2Instruction selIns = null; for (AVM2Instruction ins : list) { if (highlightOffset == ins.getAddress()) { selIns = ins; break; } if (ins.getAddress() > highlightOffset) { selIns = lastIns; break; } lastIns = ins; } if (selIns != null) { //long inspos = highlightOffset - selIns.offset; if (!codeOnly && ((selIns.definition instanceof ConstructSuperIns) || (selIns.definition instanceof CallSuperIns) || (selIns.definition instanceof CallSuperVoidIns))) { Highlighting tc = Highlighting.searchPos(highlightedText.getClassHighlights(), pos); if (tc != null) { int cindex = (int) tc.getProperties().index; if (cindex > -1) { return abc.instance_info.get(cindex).super_index; } } } else { for (int i = 0; i < selIns.definition.operands.length; i++) { if (selIns.definition.operands[i] == AVM2Code.DAT_MULTINAME_INDEX) { return selIns.operands[i]; } } } } } } if (codeOnly) { return -1; } Highlighting ch = Highlighting.searchPos(highlightedText.getClassHighlights(), pos); if (ch != null) { Highlighting th = Highlighting.searchPos(highlightedText.getTraitHighlights(), pos); if (th != null) { currentTrait = abc.findTraitByTraitId((int) ch.getProperties().index, (int) th.getProperties().index); } } if (currentTrait instanceof TraitMethodGetterSetter) { currentMethod = ((TraitMethodGetterSetter) currentTrait).method_info; } Highlighting sh = Highlighting.searchPos(highlightedText.getSpecialHighlights(), pos); if (sh != null) { switch (sh.getProperties().subtype) { case TYPE_NAME: String typeName = sh.getProperties().specialValue; for (int i = 1; i < abc.constants.getMultinameCount(); i++) { Multiname m = abc.constants.getMultiname(i); if (m != null) { if (typeName.equals(m.getNameWithNamespace(abc.constants, true).toRawString())) { return i; } } } case TRAIT_TYPE_NAME: if (currentTrait instanceof TraitSlotConst) { TraitSlotConst ts = (TraitSlotConst) currentTrait; return ts.type_index; } break; case TRAIT_NAME: if (currentTrait != null) { //return currentTrait.name_index; } break; case RETURNS: if (currentMethod > -1) { return abc.method_info.get(currentMethod).ret_type; } break; case PARAM: if (currentMethod > -1) { return abc.method_info.get(currentMethod).param_types[(int) sh.getProperties().index]; } break; } } return -1; } @Override public void caretUpdate(final CaretEvent e) { ABC abc = getABC(); if (abc == null) { return; } if (ignoreCarret) { return; } getCaret().setVisible(true); int pos = getCaretPosition(); abcPanel.detailPanel.methodTraitPanel.methodCodePanel.setIgnoreCarret(true); lastTraitIndex = GraphTextWriter.TRAIT_UNKNOWN; try { classIndex = -1; Highlighting cm = Highlighting.searchPos(highlightedText.getClassHighlights(), pos); if (cm != null) { classIndex = (int) cm.getProperties().index; } displayClass(classIndex, script.scriptIndex); Highlighting tm = Highlighting.searchPos(highlightedText.getMethodHighlights(), pos); if (tm != null) { String name = ""; if (classIndex > -1) { name = abc.instance_info.get(classIndex).getName(abc.constants).getNameWithNamespace(abc.constants, true).toPrintableString(true); } Trait currentTrait = null; currentTraitHighlight = Highlighting.searchPos(highlightedText.getTraitHighlights(), pos); if (currentTraitHighlight != null) { lastTraitIndex = (int) currentTraitHighlight.getProperties().index; currentTrait = getCurrentTrait(); isStatic = abc.isStaticTraitId(classIndex, lastTraitIndex); if (currentTrait != null) { name += ":" + currentTrait.getName(abc).getName(abc.constants, null, false, true); } } displayMethod(pos, (int) tm.getProperties().index, name, currentTrait, lastTraitIndex, isStatic); currentMethodHighlight = tm; return; } if (classIndex == -1) { abcPanel.navigator.setClassIndex(-1, script.scriptIndex); //setNoTrait(); //return; } Trait currentTrait; currentTraitHighlight = Highlighting.searchPos(highlightedText.getTraitHighlights(), pos); if (currentTraitHighlight != null) { lastTraitIndex = (int) currentTraitHighlight.getProperties().index; currentTrait = getCurrentTrait(); if (currentTrait != null) { if (currentTrait instanceof TraitSlotConst) { abcPanel.detailPanel.slotConstTraitPanel.load((TraitSlotConst) currentTrait, abc, abc.isStaticTraitId(classIndex, lastTraitIndex)); final Trait ftrait = currentTrait; final int ftraitIndex = lastTraitIndex; View.execInEventDispatch(() -> { abcPanel.detailPanel.showCard(DetailPanel.SLOT_CONST_TRAIT_CARD, ftrait, ftraitIndex); }); abcPanel.detailPanel.setEditMode(false); currentMethodHighlight = null; Highlighting spec = Highlighting.searchPos(highlightedText.getSpecialHighlights(), pos, currentTraitHighlight.startPos, currentTraitHighlight.startPos + currentTraitHighlight.len); if (spec != null) { abcPanel.detailPanel.slotConstTraitPanel.hilightSpecial(spec); } return; } } currentMethodHighlight = null; //currentTrait = null; String name = classIndex == -1 ? "" : abc.instance_info.get(classIndex).getName(abc.constants).getNameWithNamespace(abc.constants, true).toPrintableString(true); currentTrait = getCurrentTrait(); isStatic = abc.isStaticTraitId(classIndex, lastTraitIndex); if (currentTrait != null) { if (!name.isEmpty()) { name += ":"; } name += currentTrait.getName(abc).getName(abc.constants, null, false, true); } int methodId; if (classIndex > -1) { methodId = abc.findMethodIdByTraitId(classIndex, lastTraitIndex); } else { methodId = ((TraitMethodGetterSetter) abc.script_info.get(script.scriptIndex).traits.traits.get(lastTraitIndex)).method_info; } displayMethod(pos, methodId, name, currentTrait, lastTraitIndex, isStatic); return; } setNoTrait(); } finally { abcPanel.detailPanel.methodTraitPanel.methodCodePanel.setIgnoreCarret(false); } } public void gotoLastTrait() { gotoTrait(lastTraitIndex); } public void gotoLastMethod() { if (currentMethodHighlight != null) { final int fpos = currentMethodHighlight.startPos; new Timer().schedule(new TimerTask() { @Override public void run() { if (fpos <= getDocument().getLength()) { setCaretPosition(fpos); } } }, 100); } } public void gotoTrait(int traitId) { boolean isScriptInit = traitId == GraphTextWriter.TRAIT_SCRIPT_INITIALIZER; Highlighting tc = Highlighting.searchIndex(highlightedText.getClassHighlights(), classIndex); if (tc != null || isScriptInit) { Highlighting th = Highlighting.searchIndex(highlightedText.getTraitHighlights(), traitId, isScriptInit ? 0 : tc.startPos, isScriptInit ? -1 : tc.startPos + tc.len); int pos = 0; if (th != null) { if (th.len > 1) { ignoreCarret = true; int startPos = th.startPos + th.len - 1; if (startPos <= getDocument().getLength()) { setCaretPosition(startPos); } ignoreCarret = false; } pos = th.startPos; } else if (tc != null) { pos = tc.startPos; } final int fpos = pos; new Timer().schedule(new TimerTask() { @Override public void run() { if (fpos <= getDocument().getLength()) { setCaretPosition(fpos); } } }, 100); } } public DecompiledEditorPane(ABCPanel abcPanel) { super(); setEditable(false); getCaret().setVisible(true); addCaretListener(this); this.abcPanel = abcPanel; } public void clearScript() { script = null; } public void setScript(ScriptPack scriptLeaf, boolean force) { View.checkAccess(); if (setSourceWorker != null) { setSourceWorker.cancel(true); setSourceWorker = null; } if (!force && this.script == scriptLeaf) { fireScript(); return; } String sn = scriptLeaf.getClassPath().toString(); setScriptName(sn); abcPanel.scriptNameLabel.setText(sn); int scriptIndex = scriptLeaf.scriptIndex; ScriptInfo nscript = null; ABC abc = scriptLeaf.abc; if (scriptIndex > -1) { nscript = abc.script_info.get(scriptIndex); } if (nscript == null) { highlightedText = HighlightedText.EMPTY; return; } HighlightedText decompiledText = SWF.getFromCache(scriptLeaf); boolean decompileNeeded = decompiledText == null; if (decompileNeeded) { CancellableWorker worker = new CancellableWorker() { @Override protected Void doInBackground() throws Exception { if (decompileNeeded) { View.execInEventDispatch(() -> { setText("// " + AppStrings.translate("work.decompiling") + "..."); }); HighlightedText htext = SWF.getCached(scriptLeaf); View.execInEventDispatch(() -> { setSourceCompleted(scriptLeaf, htext); }); } return null; } @Override protected void done() { View.execInEventDispatch(() -> { setSourceWorker = null; if (!Main.isDebugging()) { Main.stopWork(); } try { get(); } catch (CancellationException ex) { setText("// " + AppStrings.translate("work.canceled")); } catch (Exception ex) { Throwable cause = ex; if (ex instanceof ExecutionException) { cause = ex.getCause(); } if (cause instanceof CancellationException) { setText("// " + AppStrings.translate("work.canceled")); } else { logger.log(Level.SEVERE, "Error", cause); setText("// " + AppStrings.translate("decompilationError") + ": " + cause); } } }); } }; worker.execute(); setSourceWorker = worker; if (!Main.isDebugging()) { Main.startWork(AppStrings.translate("work.decompiling") + "...", worker); } } else { setSourceCompleted(scriptLeaf, decompiledText); } } private void setSourceCompleted(ScriptPack scriptLeaf, HighlightedText decompiledText) { View.checkAccess(); if (decompiledText == null) { decompiledText = HighlightedText.EMPTY; } script = scriptLeaf; highlightedText = decompiledText; if (decompiledText != null) { String hilightedCode = decompiledText.text; BrokenScriptDetector det = new BrokenScriptDetector(); if (det.codeIsBroken(hilightedCode)) { abcPanel.brokenHintPanel.setVisible(true); } else { abcPanel.brokenHintPanel.setVisible(false); } setText(hilightedCode); if (highlightedText.getClassHighlights().size() > 0) { try { setCaretPosition(highlightedText.getClassHighlights().get(0).startPos); } catch (Exception ex) { //sometimes happens //ignore } } } fireScript(); } public void reloadClass() { View.checkAccess(); int ci = classIndex; SWF.uncache(script); if (script != null && getABC() != null) { setScript(script, true); } setNoTrait(); setClassIndex(ci); } public int getClassIndex() { return classIndex; } private ABC getABC() { return script == null ? null : script.abc; } @Override public void setText(String t) { super.setText(t); setCaretPosition(0); } @Override public String getToolTipText(MouseEvent e) { // not debugging: so return existing text if (abcPanel.getDebugPanel().localsTable == null) { return super.getToolTipText(); } final Point point = new Point(e.getX(), e.getY()); final int pos = abcPanel.decompiledTextArea.viewToModel(point); final String identifier = abcPanel.getMainPanel().getActionPanel().getStringUnderPosition(pos, abcPanel.decompiledTextArea); if (identifier != null && !identifier.isEmpty()) { String tooltipText = abcPanel.getDebugPanel().localsTable.tryGetDebugHoverToolTipText(identifier); return (tooltipText == null ? super.getToolTipText() : tooltipText); } // not found: so return existing text return super.getToolTipText(); } }
jindrapetrik/jpexs-decompiler
src/com/jpexs/decompiler/flash/gui/abc/DecompiledEditorPane.java
Java
gpl-3.0
33,603
<?php namespace Opifer\QueueIt\Validation; interface ValidateResultRepositoryInterface { public function getValidationResult($queue); public function setValidationResult($queue, $validationResult); }
Opifer/queue-it
src/Validation/ValidateResultRepositoryInterface.php
PHP
gpl-3.0
210
/* Inclusão das bibliotecas requisitadas: */ #include "../Bibliotecas/Diretorios.hpp" /* Definições das funções a serem manipuladas por este arquivo: */ /* Função 'arq_escreve_resize', escreve o aviso de redimensionamento */ void arq_escreve_resize (FILE *arq){ /* 'arq' armazena o arquivo lógico a ser escrito o aviso */ fprintf (arq, "Todas as imagens foram redimensionadas para %d x %d pixels, ", LIN_ALVO, COL_ALVO); fprintf (arq, "as medições abaixo obedecem esta proporção.\n\n"); } /* Função 'dir_ler', realiza a leitura de todos os diretórios a partir de um ** diretório base, escrevendo num arquivo de escolha*/ void dir_ler (FILE *arq, FILE *arq1, char * dirbase, int ramificacao, FMeasure *estatistica){ /* 'arq' armazena o arquivo a ser gravado as informações a medida que vai ** percorrendo os diretórios; 'dirbase' armazena o nome do diretório ** corrente a ser navegado; 'ramificacao' armazena o nivel de ramificacao ** dos diretórios; 'pasta' armazena as informações dos arquivos presentes ** no diretório; 'pdir' armazena o diretório lógico a ser navegado; ** 'extensoes' armazena as extensões de arquivo, classificadas como imagem */ Diretorios *pasta; DIR *pdir = dir_abre (dirbase); string hinweis[] = {"Categoria 1", "Categoria 2"}; int contador = 0; /* Analisando todos os arquivos do diretorio corrente */ while((pasta = readdir(pdir))){ /* Escrita no arquivo desejado */ dir_escreve_geral (arq, pasta, ramificacao); /* Validação do diretório */ if (dir_valido_geral(pasta) == VERDADE){ /* Configuração da classe que está sendo analisada */ if (string_compara_n(pasta->d_name, hinweis[0], 0, 0, static_cast<int>(hinweis[0].size())) == VERDADE){ estatistica->status = VERDADE; }else if (string_compara_n(pasta->d_name, hinweis[1], 0, 0, static_cast<int>(hinweis[1].size())) == VERDADE){ estatistica->status = !VERDADE; } /* Verificação se é outro diretório, caso positivo: */ if(pasta->d_type == DIR_PASTA){ /* Configuração do nome do diretório,'nomedir', a ser lido */ char nomedir[500]; /* Inicialização do nome do diretório */ string_zera (nomedir, 0, 500); /* Construção do nome do diretório filho */ dir_constroi_nome (dirbase, pasta->d_name, nomedir); strcat (nomedir, DIR_DIVISAO); /* Leitura do diretório formado */ dir_ler (arq, arq1, nomedir, ramificacao + 1, estatistica); /* Caso contrario e, além disso, sendo uma imagem */ }else if(dir_valido_imagem(pasta) == VERDADE){ /* Configuração do nome da imagem, 'nomeimg', a ser manipulada */ char nomeimg[500]; /* Inicialização do nome do diretório */ string_zera (nomeimg, 0, 500); /* Construção do nome do diretório filho */ dir_constroi_nome (dirbase, pasta->d_name, nomeimg); /* Abertura da imagem para processamento */ Mat teste = imread (nomeimg, CV_LOAD_IMAGE_COLOR); /* Processamento sobre a imagem encontrada */ if (!teste.empty()){ imagem_processa (arq1, teste, nomeimg, estatistica); if (estatistica->classes.status == VERDADE){ contador++; } } /* Escrita no arquivo saida, o status sobre a imagem */ dir_escreve_imagem (arq, nomeimg, ramificacao + 1, teste.empty()); teste.release (); } } } if (estatistica->classes.status == VERDADE){ /* Levantamento das médias e desvios padrões para as classes */ estatistica->classes.medias[estatistica->classes.classe] /= contador; } /* Liberação de memória */ if (pdir != NULL) closedir (pdir); return; } /* Função 'dir_abre', realiza a abertura de um dado diretório, ** verificando se é um diretorio válido */ DIR * dir_abre (char *nomedir){ /* 'nomedir' armazena o nome do diretório a ser aberto; 'diretorio' ** armazena o diretório lógico a ser manipulado */ DIR *diretorio = opendir (nomedir); /* Validação do diretório lógico */ if (diretorio == NULL){ printf ("Falha ao abrir o diretorio %s!\n", nomedir); } return diretorio; } /* Função 'dir_constroi_nome', realiza a construção do nome do diretorio, ** pela concatenação de duas outras partes */ void dir_constroi_nome (char *parte1, char *parte2, char *destino){ /* 'parte1' e 'parte2' armazenam as respectivas partes a serem concatenadas ** nessa ordem; 'destino' armazena o nome formado */ /* Concatenação das partes */ strcpy (destino, parte1); strcat (destino, parte2); } /* Função 'dir_escreve_geral', realiza a escrita do status de um arquivo do diretório ** num arquivo de saída escolhido */ void dir_escreve_geral (FILE *arq, Diretorios *dir, int ramificacao){ /* 'arq' armazena o arquivo lógico a ser escrito as informações do referente ** arquivo; 'dir' armazena o arquivo corrente; 'ramificacao' armazena o nível ** de ramificação do arquivo corrente */ /* Escrita com as ramificações */ for (int vezes = 0; vezes < ramificacao; vezes++) fprintf (arq, "\t"); /* Escrita das informações */ fprintf (arq, "Tipo =\t%d\t", dir->d_type); fprintf (arq, "Nome =\t%s\n", dir->d_name); } /* Função 'dir_escreve_imagem', realiza a escrita do status de uma imagem do diretório ** num arquivo de saída escolhido */ void dir_escreve_imagem (FILE *arq, char *nomeimg, int ramificacao, bool falha){ /* 'arq' armazena o arquivo lógico a ser escrito as informações do referente ** arquivo; 'dir' armazena o arquivo corrente; 'ramificacao' armazena o nível ** de ramificação do arquivo corrente */ /* Escrita com as ramificações */ for (int vezes = 0; vezes < ramificacao + 1; vezes++) fprintf (arq, "\t"); /* Não conseguindo abrir a imagem */ if (falha == VERDADE){ fprintf (arq, "Erro ao abrir a imagem %s\n\n", nomeimg); /* Caso contrário */ }else{ fprintf (arq, "SUCESSO\n\n"); } } /* Função 'dir_valido_geral', realiza a validação de um diretório, ou seja, se é uma ** pasta de arquivos e se é um nome diferente de '.' e '..' */ bool dir_valido_geral (Diretorios *dir){ /* 'dir' armazena o diretório a ser analisado */ /* Validação do diretório */ if ((strcmp(dir->d_name, ".") != IGUAL) && (strcmp(dir->d_name, "..") != IGUAL)) return VERDADE; return !VERDADE; } /* Função 'dir_valido_imagem', realiza a validação de um arquivo como imagem */ bool dir_valido_imagem (Diretorios *dir){ /* 'dir' armazena o diretorio a ser avaliado como imagem ou não; 'referencia' armazena ** os criterios para que um diretório seja considerado como uma imagem */ string referencia[] = {"jpg", "png"}; /* Valida o formato do diretório quanto um formato de imagem */ /* Busca dentre os formatos possíveis */ for (int turn = 0; turn < QNT_FORMATOS; turn++){ /* Sendo VERDADE */ if (string_compara_n (dir->d_name, referencia[turn], strlen(dir->d_name) - ARQ_EXTENSAO, 0, static_cast<int>(referencia[turn].length())) == VERDADE) return VERDADE; } /* Não sendo uma imagem */ return !VERDADE; }
rodrigofegui/UnB
2015.2/Intro. Proc. Imagem/Trabalhos/Trabalho 1/Codificação_Trab1_rev1/Fontes/Diretorios.cpp
C++
gpl-3.0
7,622
#!/usr/bin/env python """Publish coverage results online via coveralls.io Puts your coverage results on coveralls.io for everyone to see. It makes custom report for data generated by coverage.py package and sends it to `json API`_ of coveralls.io service. All python files in your coverage analysis are posted to this service along with coverage stats, so please make sure you're not ruining your own security! Usage: coveralls [options] coveralls debug [options] Debug mode doesn't send anything, just outputs json to stdout, useful for development. It also forces verbose output. Global options: -h --help Display this help -v --verbose Print extra info, True for debug command Example: $ coveralls Submitting coverage to coveralls.io... Coverage submitted! Job #38.1 https://coveralls.io/jobs/92059 """ import logging from docopt import docopt from coveralls import Coveralls from coveralls.api import CoverallsException log = logging.getLogger('coveralls') def main(argv=None): options = docopt(__doc__, argv=argv) if options['debug']: options['--verbose'] = True level = logging.DEBUG if options['--verbose'] else logging.INFO log.addHandler(logging.StreamHandler()) log.setLevel(level) try: coverallz = Coveralls() if not options['debug']: log.info("Submitting coverage to coveralls.io...") result = coverallz.wear() log.info("Coverage submitted!") log.info(result['message']) log.info(result['url']) log.debug(result) else: log.info("Testing coveralls-python...") coverallz.wear(dry_run=True) except KeyboardInterrupt: # pragma: no cover log.info('Aborted') except CoverallsException as e: log.error(e) except Exception: # pragma: no cover raise
phimpme/generator
Phimpme/site-packages/coveralls/cli.py
Python
gpl-3.0
1,907
/* * Copyright (C) 2016 Matthew Seal * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.mseal.control.server; /** * * @author Matthew Seal */ public interface CommandImpl { /** * Command to shutdown the server * * @throws Exception if an error happens while executing the command */ public void serverShutdown() throws Exception; /** * Command to reboot the server * * @throws Exception if an error happens while executing the command */ public void serverRestart() throws Exception; /** * This method is called for custom events * * @param cmd the command to be executed * @param arguments the arguments included in the command * @throws Exception if an error happens while executing the command */ public void serverCommand(String cmd, String arguments) throws Exception; }
matthewseal/ServerControl
src/org/mseal/control/server/CommandImpl.java
Java
gpl-3.0
1,539
/* Copyright (C) 2014-2017 Wolfger Schramm <wolfger@spearwolf.de> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package kiwotigo type RegionGroup struct { Regions []*Region } func NewRegionGroup(maxRegionCount int) (group *RegionGroup) { group = new(RegionGroup) group.Regions = make([]*Region, 0, maxRegionCount) return group } func (group *RegionGroup) IsInside(region *Region) bool { for _, reg := range group.Regions { if reg == region { return true } } return false } func (group *RegionGroup) IsOverlapping(other *RegionGroup) bool { for _, region := range other.Regions { if group.IsInside(region) { return true } else { for _, neighbor := range region.neighbors { if group.IsInside(neighbor) { return true } } } } return false } func (group *RegionGroup) Merge(other *RegionGroup) { for _, region := range other.Regions { group.Append(region) } } func (group *RegionGroup) Append(region *Region) { if group.IsInside(region) { return } group.Regions = append(group.Regions, region) for _, neighbor := range region.neighbors { group.Append(neighbor) } }
spearwolf/kiwotigo
region_group.go
GO
gpl-3.0
1,706
package net.egyptmagicians.mod; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.init.Blocks; import net.minecraft.item.Item; public class _MCreativeTabs { public static CreativeTabs TabEgyptMagicians; public static void mainRegistry(){ TabEgyptMagicians = new CreativeTabs("TabEgyptMagicians"){ @SideOnly(Side.CLIENT) public Item getTabIconItem(){ return Item.getItemFromBlock(Blocks.sandstone); } }; } }
jasonw930/egyptmagicians
net/egyptmagicians/mod/_MCreativeTabs.java
Java
gpl-3.0
528
import { Empty as _Empty } from 'elementor-document/elements/commands'; import ElementsHelper from '../../elements/helper'; export const Empty = () => { QUnit.module( 'Empty', () => { QUnit.test( 'Single Selection', ( assert ) => { const eColumn = ElementsHelper.createSection( 1, true ); ElementsHelper.createButton( eColumn ); ElementsHelper.createButton( eColumn ); // Ensure editor saver. $e.internal( 'document/save/set-is-modified', { status: false } ); ElementsHelper.empty(); // Check. assert.equal( elementor.getPreviewContainer().view.collection.length, 0, 'all elements were removed.' ); assert.equal( elementor.saver.isEditorChanged(), true, 'Command applied the saver editor is changed.' ); } ); QUnit.test( 'Restore()', ( assert ) => { const random = Math.random(), historyItem = { get: ( key ) => { if ( 'data' === key ) { return random; } }, }; let orig = $e.run, tempCommand = ''; // TODO: Do not override '$e.run', use 'on' method instead. $e.run = ( command ) => { tempCommand = command; }; // redo: `true` _Empty.restore( historyItem, true ); $e.run = orig; assert.equal( tempCommand, 'document/elements/empty' ); const addChildModelOrig = elementor.getPreviewView().addChildModel; // Clear. orig = $e.run; tempCommand = ''; let tempData = ''; elementor.getPreviewView().addChildModel = ( data ) => tempData = data; // TODO: Do not override '$e.run', use 'on' method instead. $e.run = ( command ) => { tempCommand = command; }; // redo: `false` _Empty.restore( historyItem, false ); $e.run = orig; elementor.getPreviewView().addChildModel = addChildModelOrig; assert.equal( tempData, random ); } ); } ); }; export default Empty;
kobizz/elementor
tests/qunit/core/editor/document/elements/commands/empty.spec.js
JavaScript
gpl-3.0
1,829
package task19; public class Car { public int speed; public String name; public String color; public Car(){ this.speed = 0; this.name = "noname"; this.color = "unpainted"; } public Car(int speed, String name, String color) { super(); this.speed = speed; this.name = name; this.color = color; } public int getSpeed() { return speed; } public void setSpeed(int speed) { this.speed = speed; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } }
yulgutlin/eclipsewokspace
task19/src/task19/Car.java
Java
gpl-3.0
650
/* Atmosphere Autopilot, plugin for Kerbal Space Program. Copyright (C) 2015-2016, Baranin Alexander aka Boris-Barboris. Atmosphere Autopilot is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Atmosphere Autopilot is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Atmosphere Autopilot. If not, see <http://www.gnu.org/licenses/>. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; namespace AtmosphereAutopilot { public sealed class MouseDirector : StateController { internal MouseDirector(Vessel v) : base(v, "Mouse Director", 88437227) { } //FlightModel imodel; DirectorController dir_c; ProgradeThrustController thrust_c; public override void InitializeDependencies(Dictionary<Type, AutopilotModule> modules) { //imodel = modules[typeof(FlightModel)] as FlightModel; dir_c = modules[typeof(DirectorController)] as DirectorController; thrust_c = modules[typeof(ProgradeThrustController)] as ProgradeThrustController; } protected override void OnActivate() { dir_c.Activate(); thrust_c.Activate(); MessageManager.post_status_message("Mouse Director enabled"); } protected override void OnDeactivate() { dir_c.Deactivate(); thrust_c.Deactivate(); if (indicator != null) indicator.enabled = false; MessageManager.post_status_message("Mouse Director disabled"); } public override void ApplyControl(FlightCtrlState cntrl) { if (vessel.LandedOrSplashed()) return; // // follow camera direction // dir_c.ApplyControl(cntrl, camera_direction, Vector3d.zero); if (thrust_c.spd_control_enabled) thrust_c.ApplyControl(cntrl, thrust_c.setpoint.mps()); } //bool camera_correct = false; Vector3 camera_direction; static CenterIndicator indicator; static Camera camera_attached; public override void OnUpdate() { if (HighLogic.LoadedSceneIsFlight && CameraManager.Instance.currentCameraMode == CameraManager.CameraMode.Flight) { //camera_correct = true; Camera maincamera = FlightCamera.fetch.mainCamera; camera_direction = maincamera.cameraToWorldMatrix.MultiplyPoint(Vector3.back) - FlightCamera.fetch.mainCamera.transform.position; // let's draw a couple of lines to show direction if (indicator == null || camera_attached != maincamera) { indicator = maincamera.gameObject.GetComponent<CenterIndicator>(); if (indicator == null) indicator = maincamera.gameObject.AddComponent<CenterIndicator>(); camera_attached = maincamera; } indicator.enabled = true; } else { //camera_correct = false; indicator.enabled = false; } } [AutoGuiAttr("Director controller GUI", true)] public bool DirGUI { get { return dir_c.IsShown(); } set { if (value) dir_c.ShowGUI(); else dir_c.UnShowGUI(); } } [AutoGuiAttr("Thrust controller GUI", true)] public bool PTCGUI { get { return thrust_c.IsShown(); } set { if (value) thrust_c.ShowGUI(); else thrust_c.UnShowGUI(); } } protected override void _drawGUI(int id) { close_button(); GUILayout.BeginVertical(); AutoGUI.AutoDrawObject(this); thrust_c.SpeedCtrlGUIBlock(); GUILayout.EndVertical(); GUI.DragWindow(); } public class CenterIndicator : MonoBehaviour { Material mat = new Material(Shader.Find("Sprites/Default")); Vector3 startVector = new Vector3(0.494f, 0.5f, -0.001f); Vector3 endVector = new Vector3(0.506f, 0.5f, -0.001f); //public new bool enabled = false; public void OnPostRender() { if (enabled) { GL.PushMatrix(); mat.SetPass(0); mat.color = Color.red; GL.LoadOrtho(); GL.Begin(GL.LINES); GL.Color(Color.red); GL.Vertex(startVector); GL.Vertex(endVector); GL.End(); GL.PopMatrix(); enabled = false; } } } } }
Boris-Barboris/AtmosphereAutopilot
AtmosphereAutopilot/Modules/MouseDirector.cs
C#
gpl-3.0
5,249
/* * Copyright (c) 2016. * Modified by Neurophobic Animal on 07/06/2016. */ package cm.aptoide.pt.dataprovider.model.v7; import java.util.List; /** * List of various malware reasons http://ws2.aptoide .com/api/7/getApp/apk_md5sum/7de07d96488277d8d76eafa2ef66f5a8 * <p> * <p> * RANK2: http://ws2.aptoide.com/api/7/getApp/apk_md5sum/7de07d96488277d8d76eafa2ef66f5a8 * http://ws2.aptoide.com/api/7/getApp/apk_md5sum/06c9eb56b787b6d3b606d68473a38f47 * <p> * RANK3: http://ws2.aptoide.com/api/7/getApp/apk_md5sum/18f0d5bdb9df1e0e27604890113c3331 * http://ws2.aptoide.com/api/7/getApp/apk_md5sum/74cbfde9dc6da43d3d14f4df9cdb9f2f * <p> * Rank can be: TRUSTED, WARNING, UNKNOWN, CRITICAL */ public class Malware { public static final String PASSED = "passed"; public static final String WARN = "warn"; public static final String GOOGLE_PLAY = "Google Play"; private Rank rank; private Reason reason; private String added; private String modified; public Malware() { } public Rank getRank() { return this.rank; } public void setRank(Rank rank) { this.rank = rank; } public Reason getReason() { return this.reason; } public void setReason(Reason reason) { this.reason = reason; } public String getAdded() { return this.added; } public void setAdded(String added) { this.added = added; } public String getModified() { return this.modified; } public void setModified(String modified) { this.modified = modified; } public int hashCode() { final int PRIME = 59; int result = 1; final Object $rank = this.getRank(); result = result * PRIME + ($rank == null ? 43 : $rank.hashCode()); final Object $reason = this.getReason(); result = result * PRIME + ($reason == null ? 43 : $reason.hashCode()); final Object $added = this.getAdded(); result = result * PRIME + ($added == null ? 43 : $added.hashCode()); final Object $modified = this.getModified(); result = result * PRIME + ($modified == null ? 43 : $modified.hashCode()); return result; } protected boolean canEqual(Object other) { return other instanceof Malware; } public enum Rank { TRUSTED, WARNING, UNKNOWN, CRITICAL } public static class Reason { private Reason.SignatureValidated signatureValidated; private Reason.ThirdPartyValidated thirdpartyValidated; private Reason.Manual manual; private Reason.Scanned scanned; public Reason() { } public SignatureValidated getSignatureValidated() { return this.signatureValidated; } public void setSignatureValidated(SignatureValidated signatureValidated) { this.signatureValidated = signatureValidated; } public ThirdPartyValidated getThirdpartyValidated() { return this.thirdpartyValidated; } public void setThirdpartyValidated(ThirdPartyValidated thirdpartyValidated) { this.thirdpartyValidated = thirdpartyValidated; } public Manual getManual() { return this.manual; } public void setManual(Manual manual) { this.manual = manual; } public Scanned getScanned() { return this.scanned; } public void setScanned(Scanned scanned) { this.scanned = scanned; } protected boolean canEqual(Object other) { return other instanceof Reason; } public enum Status { passed, failed, blacklisted, warn } public static class SignatureValidated { private String date; private Reason.Status status; private String signatureFrom; public SignatureValidated() { } public String getDate() { return this.date; } public void setDate(String date) { this.date = date; } public Status getStatus() { return this.status; } public void setStatus(Status status) { this.status = status; } public String getSignatureFrom() { return this.signatureFrom; } public void setSignatureFrom(String signatureFrom) { this.signatureFrom = signatureFrom; } protected boolean canEqual(Object other) { return other instanceof SignatureValidated; } public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof SignatureValidated)) return false; final SignatureValidated other = (SignatureValidated) o; if (!other.canEqual((Object) this)) return false; final Object this$date = this.getDate(); final Object other$date = other.getDate(); if (this$date == null ? other$date != null : !this$date.equals(other$date)) return false; final Object this$status = this.getStatus(); final Object other$status = other.getStatus(); if (this$status == null ? other$status != null : !this$status.equals(other$status)) { return false; } final Object this$signatureFrom = this.getSignatureFrom(); final Object other$signatureFrom = other.getSignatureFrom(); if (this$signatureFrom == null ? other$signatureFrom != null : !this$signatureFrom.equals(other$signatureFrom)) { return false; } return true; } public int hashCode() { final int PRIME = 59; int result = 1; final Object $date = this.getDate(); result = result * PRIME + ($date == null ? 43 : $date.hashCode()); final Object $status = this.getStatus(); result = result * PRIME + ($status == null ? 43 : $status.hashCode()); final Object $signatureFrom = this.getSignatureFrom(); result = result * PRIME + ($signatureFrom == null ? 43 : $signatureFrom.hashCode()); return result; } public String toString() { return "Malware.Reason.SignatureValidated(date=" + this.getDate() + ", status=" + this.getStatus() + ", signatureFrom=" + this.getSignatureFrom() + ")"; } } public static class ThirdPartyValidated { private String date; private String store; public ThirdPartyValidated() { } public String getDate() { return this.date; } public void setDate(String date) { this.date = date; } public String getStore() { return this.store; } public void setStore(String store) { this.store = store; } protected boolean canEqual(Object other) { return other instanceof ThirdPartyValidated; } public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof ThirdPartyValidated)) return false; final ThirdPartyValidated other = (ThirdPartyValidated) o; if (!other.canEqual((Object) this)) return false; final Object this$date = this.getDate(); final Object other$date = other.getDate(); if (this$date == null ? other$date != null : !this$date.equals(other$date)) return false; final Object this$store = this.getStore(); final Object other$store = other.getStore(); if (this$store == null ? other$store != null : !this$store.equals(other$store)) { return false; } return true; } public int hashCode() { final int PRIME = 59; int result = 1; final Object $date = this.getDate(); result = result * PRIME + ($date == null ? 43 : $date.hashCode()); final Object $store = this.getStore(); result = result * PRIME + ($store == null ? 43 : $store.hashCode()); return result; } public String toString() { return "Malware.Reason.ThirdPartyValidated(date=" + this.getDate() + ", store=" + this.getStore() + ")"; } } public static class Manual { private String date; private Reason.Status status; private List<String> av; public Manual() { } public String getDate() { return this.date; } public void setDate(String date) { this.date = date; } public Status getStatus() { return this.status; } public void setStatus(Status status) { this.status = status; } public List<String> getAv() { return this.av; } public void setAv(List<String> av) { this.av = av; } protected boolean canEqual(Object other) { return other instanceof Manual; } public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Manual)) return false; final Manual other = (Manual) o; if (!other.canEqual((Object) this)) return false; final Object this$date = this.getDate(); final Object other$date = other.getDate(); if (this$date == null ? other$date != null : !this$date.equals(other$date)) return false; final Object this$status = this.getStatus(); final Object other$status = other.getStatus(); if (this$status == null ? other$status != null : !this$status.equals(other$status)) { return false; } final Object this$av = this.getAv(); final Object other$av = other.getAv(); if (this$av == null ? other$av != null : !this$av.equals(other$av)) return false; return true; } public int hashCode() { final int PRIME = 59; int result = 1; final Object $date = this.getDate(); result = result * PRIME + ($date == null ? 43 : $date.hashCode()); final Object $status = this.getStatus(); result = result * PRIME + ($status == null ? 43 : $status.hashCode()); final Object $av = this.getAv(); result = result * PRIME + ($av == null ? 43 : $av.hashCode()); return result; } public String toString() { return "Malware.Reason.Manual(date=" + this.getDate() + ", status=" + this.getStatus() + ", av=" + this.getAv() + ")"; } } public static class Scanned { private Reason.Status status; private String date; private List<Reason.Scanned.AvInfo> avInfo; public Scanned() { } public Status getStatus() { return this.status; } public void setStatus(Status status) { this.status = status; } public String getDate() { return this.date; } public void setDate(String date) { this.date = date; } public List<AvInfo> getAvInfo() { return this.avInfo; } public void setAvInfo(List<AvInfo> avInfo) { this.avInfo = avInfo; } protected boolean canEqual(Object other) { return other instanceof Scanned; } public static class AvInfo { private List<Reason.Scanned.AvInfo.Infection> infections; private String name; public AvInfo() { } public List<Infection> getInfections() { return this.infections; } public void setInfections(List<Infection> infections) { this.infections = infections; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } protected boolean canEqual(Object other) { return other instanceof AvInfo; } public static class Infection { private String name; private String description; public Infection() { } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public String getDescription() { return this.description; } public void setDescription(String description) { this.description = description; } protected boolean canEqual(Object other) { return other instanceof Infection; } public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Infection)) return false; final Infection other = (Infection) o; if (!other.canEqual((Object) this)) return false; final Object this$name = this.getName(); final Object other$name = other.getName(); if (this$name == null ? other$name != null : !this$name.equals(other$name)) { return false; } final Object this$description = this.getDescription(); final Object other$description = other.getDescription(); if (this$description == null ? other$description != null : !this$description.equals(other$description)) { return false; } return true; } public int hashCode() { final int PRIME = 59; int result = 1; final Object $name = this.getName(); result = result * PRIME + ($name == null ? 43 : $name.hashCode()); final Object $description = this.getDescription(); result = result * PRIME + ($description == null ? 43 : $description.hashCode()); return result; } public String toString() { return "Malware.Reason.Scanned.AvInfo.Infection(name=" + this.getName() + ", description=" + this.getDescription() + ")"; } } public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof AvInfo)) return false; final AvInfo other = (AvInfo) o; if (!other.canEqual((Object) this)) return false; final Object this$infections = this.getInfections(); final Object other$infections = other.getInfections(); if (this$infections == null ? other$infections != null : !this$infections.equals(other$infections)) { return false; } final Object this$name = this.getName(); final Object other$name = other.getName(); if (this$name == null ? other$name != null : !this$name.equals(other$name)) return false; return true; } public int hashCode() { final int PRIME = 59; int result = 1; final Object $infections = this.getInfections(); result = result * PRIME + ($infections == null ? 43 : $infections.hashCode()); final Object $name = this.getName(); result = result * PRIME + ($name == null ? 43 : $name.hashCode()); return result; } public String toString() { return "Malware.Reason.Scanned.AvInfo(infections=" + this.getInfections() + ", name=" + this.getName() + ")"; } } public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Scanned)) return false; final Scanned other = (Scanned) o; if (!other.canEqual((Object) this)) return false; final Object this$status = this.getStatus(); final Object other$status = other.getStatus(); if (this$status == null ? other$status != null : !this$status.equals(other$status)) { return false; } final Object this$date = this.getDate(); final Object other$date = other.getDate(); if (this$date == null ? other$date != null : !this$date.equals(other$date)) return false; final Object this$avInfo = this.getAvInfo(); final Object other$avInfo = other.getAvInfo(); if (this$avInfo == null ? other$avInfo != null : !this$avInfo.equals(other$avInfo)) { return false; } return true; } public int hashCode() { final int PRIME = 59; int result = 1; final Object $status = this.getStatus(); result = result * PRIME + ($status == null ? 43 : $status.hashCode()); final Object $date = this.getDate(); result = result * PRIME + ($date == null ? 43 : $date.hashCode()); final Object $avInfo = this.getAvInfo(); result = result * PRIME + ($avInfo == null ? 43 : $avInfo.hashCode()); return result; } public String toString() { return "Malware.Reason.Scanned(status=" + this.getStatus() + ", date=" + this.getDate() + ", avInfo=" + this.getAvInfo() + ")"; } } public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Reason)) return false; final Reason other = (Reason) o; if (!other.canEqual((Object) this)) return false; final Object this$signatureValidated = this.getSignatureValidated(); final Object other$signatureValidated = other.getSignatureValidated(); if (this$signatureValidated == null ? other$signatureValidated != null : !this$signatureValidated.equals(other$signatureValidated)) { return false; } final Object this$thirdpartyValidated = this.getThirdpartyValidated(); final Object other$thirdpartyValidated = other.getThirdpartyValidated(); if (this$thirdpartyValidated == null ? other$thirdpartyValidated != null : !this$thirdpartyValidated.equals(other$thirdpartyValidated)) { return false; } final Object this$manual = this.getManual(); final Object other$manual = other.getManual(); if (this$manual == null ? other$manual != null : !this$manual.equals(other$manual)) { return false; } final Object this$scanned = this.getScanned(); final Object other$scanned = other.getScanned(); if (this$scanned == null ? other$scanned != null : !this$scanned.equals(other$scanned)) { return false; } return true; } public int hashCode() { final int PRIME = 59; int result = 1; final Object $signatureValidated = this.getSignatureValidated(); result = result * PRIME + ($signatureValidated == null ? 43 : $signatureValidated.hashCode()); final Object $thirdpartyValidated = this.getThirdpartyValidated(); result = result * PRIME + ($thirdpartyValidated == null ? 43 : $thirdpartyValidated.hashCode()); final Object $manual = this.getManual(); result = result * PRIME + ($manual == null ? 43 : $manual.hashCode()); final Object $scanned = this.getScanned(); result = result * PRIME + ($scanned == null ? 43 : $scanned.hashCode()); return result; } public String toString() { return "Malware.Reason(signatureValidated=" + this.getSignatureValidated() + ", thirdpartyValidated=" + this.getThirdpartyValidated() + ", manual=" + this.getManual() + ", scanned=" + this.getScanned() + ")"; } } public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Malware)) return false; final Malware other = (Malware) o; if (!other.canEqual((Object) this)) return false; final Object this$rank = this.getRank(); final Object other$rank = other.getRank(); if (this$rank == null ? other$rank != null : !this$rank.equals(other$rank)) return false; final Object this$reason = this.getReason(); final Object other$reason = other.getReason(); if (this$reason == null ? other$reason != null : !this$reason.equals(other$reason)) { return false; } final Object this$added = this.getAdded(); final Object other$added = other.getAdded(); if (this$added == null ? other$added != null : !this$added.equals(other$added)) return false; final Object this$modified = this.getModified(); final Object other$modified = other.getModified(); if (this$modified == null ? other$modified != null : !this$modified.equals(other$modified)) { return false; } return true; } public String toString() { return "Malware(rank=" + this.getRank() + ", reason=" + this.getReason() + ", added=" + this.getAdded() + ", modified=" + this.getModified() + ")"; } }
Aptoide/aptoide-client-v8
dataprovider/src/main/java/cm/aptoide/pt/dataprovider/model/v7/Malware.java
Java
gpl-3.0
20,548
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("About")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("About")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから // 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、 // その型の ComVisible 属性を true に設定してください。 [assembly: ComVisible(false)] //ローカライズ可能なアプリケーションのビルドを開始するには、 //.csproj ファイルの <UICulture>CultureYouAreCodingWith</UICulture> を //<PropertyGroup> 内部で設定します。たとえば、 //ソース ファイルで英語を使用している場合、<UICulture> を en-US に設定します。次に、 //下の NeutralResourceLanguage 属性のコメントを解除します。下の行の "en-US" を //プロジェクト ファイルの UICulture 設定と一致するよう更新します。 //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //テーマ固有のリソース ディクショナリが置かれている場所 //(リソースがページ、 //またはアプリケーション リソース ディクショナリに見つからない場合に使用されます) ResourceDictionaryLocation.SourceAssembly //汎用リソース ディクショナリが置かれている場所 //(リソースがページ、 //アプリケーション、またはいずれのテーマ固有のリソース ディクショナリにも見つからない場合に使用されます) )] // アセンブリのバージョン情報は次の 4 つの値で構成されています: // // メジャー バージョン // マイナー バージョン // ビルド番号 // Revision // // すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を // 既定値にすることができます: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
tor4kichi/ReactiveFolder
Module/About/Properties/AssemblyInfo.cs
C#
gpl-3.0
2,785
/** * This file is part of veraPDF Parser, a module of the veraPDF project. * Copyright (c) 2015, veraPDF Consortium <info@verapdf.org> * All rights reserved. * * veraPDF Parser is free software: you can redistribute it and/or modify * it under the terms of either: * * The GNU General public license GPLv3+. * You should have received a copy of the GNU General Public License * along with veraPDF Parser as the LICENSE.GPL file in the root of the source * tree. If not, see http://www.gnu.org/licenses/ or * https://www.gnu.org/licenses/gpl-3.0.en.html. * * The Mozilla Public License MPLv2+. * You should have received a copy of the Mozilla Public License along with * veraPDF Parser as the LICENSE.MPL file in the root of the source tree. * If a copy of the MPL was not distributed with this file, you can obtain one at * http://mozilla.org/MPL/2.0/. */ package org.verapdf.cos.filters; import org.verapdf.as.filters.io.ASBufferingInFilter; import org.verapdf.as.io.ASInputStream; import org.verapdf.cos.COSKey; import org.verapdf.tools.EncryptionTools; import org.verapdf.tools.RC4Encryption; import java.io.IOException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; /** * Filter that decrypts data using RC4 cipher decryption. * * @author Sergey Shemyakov */ public class COSFilterRC4DecryptionDefault extends ASBufferingInFilter { public static final int MAXIMAL_KEY_LENGTH = 16; private RC4Encryption rc4; /** * Constructor. * * @param stream is stream with encrypted data. * @param objectKey contains object and generation numbers from object * identifier for object that is being decrypted. If it is * direct object, objectKey is taken from indirect object * that contains it. * @param encryptionKey is encryption key that is calculated from user * password and encryption dictionary. */ public COSFilterRC4DecryptionDefault(ASInputStream stream, COSKey objectKey, byte[] encryptionKey) throws IOException, NoSuchAlgorithmException { super(stream); initRC4(objectKey, encryptionKey); } @Override public int read(byte[] buffer, int size) throws IOException { if(this.bufferSize() == 0) { int bytesFed = (int) this.feedBuffer(getBufferCapacity()); if (bytesFed == -1) { return -1; } } byte[] encData = new byte[BF_BUFFER_SIZE]; int encDataLength = this.bufferPopArray(encData, size); if (encDataLength >= 0) { byte[] res = rc4.process(encData, 0, encDataLength); System.arraycopy(res, 0, buffer, 0, encDataLength); } return encDataLength; } @Override public int read(byte[] buffer, int off, int size) throws IOException { if(this.bufferSize() == 0) { int bytesFed = (int) this.feedBuffer(getBufferCapacity()); if (bytesFed == -1) { return -1; } } byte[] encData = new byte[BF_BUFFER_SIZE]; int encDataLength = this.bufferPopArray(encData, size); if (encDataLength >= 0) { byte[] res = rc4.process(encData, 0, encDataLength); System.arraycopy(res, 0, buffer, off, encDataLength); } return encDataLength; } @Override public void reset() throws IOException { super.reset(); this.rc4.reset(); } private void initRC4(COSKey objectKey, byte[] encryptionKey) throws NoSuchAlgorithmException { byte[] objectKeyDigest = getObjectKeyDigest(objectKey); MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(ASBufferingInFilter.concatenate(encryptionKey, encryptionKey.length, objectKeyDigest, objectKeyDigest.length)); byte[] resultEncryptionKey = md5.digest(); int keyLength = Math.min(MAXIMAL_KEY_LENGTH, encryptionKey.length + objectKeyDigest.length); rc4 = new RC4Encryption(Arrays.copyOf(resultEncryptionKey, keyLength)); } public static byte[] getObjectKeyDigest(COSKey objectKey) { byte[] res = new byte[5]; System.arraycopy(EncryptionTools.intToBytesLowOrderFirst( objectKey.getNumber()), 0, res, 0, 3); System.arraycopy(EncryptionTools.intToBytesLowOrderFirst( objectKey.getGeneration()), 0, res, 3, 2); return res; } }
shem-sergey/veraPDF-pdflib
src/main/java/org/verapdf/cos/filters/COSFilterRC4DecryptionDefault.java
Java
gpl-3.0
4,631
/*! \file DetectorDriver.cpp * \brief Main driver for event processing * \author S. N. Liddick * \date July 2, 2007 */ #include <algorithm> #include <fstream> #include <iomanip> #include <iostream> #include <iterator> #include <limits> #include <sstream> //This header is for decoding the XML ///@TODO The XML decoding should be moved out of this file and into a /// dedicated class. #include "pugixml.hpp" //These headers are core headers and are needed for basic functionality #include "DammPlotIds.hpp" #include "DetectorDriver.hpp" #include "DetectorLibrary.hpp" #include "Display.h" #include "Exceptions.hpp" #include "HighResTimingData.hpp" #include "RandomPool.hpp" #include "RawEvent.hpp" #include "TreeCorrelator.hpp" //These headers handle trace analysis #include "CfdAnalyzer.hpp" #include "FittingAnalyzer.hpp" #include "TauAnalyzer.hpp" #include "TraceAnalyzer.hpp" #include "TraceExtractor.hpp" #include "TraceFilterAnalyzer.hpp" #include "WaaAnalyzer.hpp" #include "WaveformAnalyzer.hpp" //These headers handle processing of specific detector types #include "BetaScintProcessor.hpp" #include "DoubleBetaProcessor.hpp" #include "Hen3Processor.hpp" #include "GeProcessor.hpp" #include "GeCalibProcessor.hpp" #include "IonChamberProcessor.hpp" #include "LiquidScintProcessor.hpp" #include "LogicProcessor.hpp" #include "McpProcessor.hpp" #include "NeutronScintProcessor.hpp" #include "PositionProcessor.hpp" #include "PspmtProcessor.hpp" #include "SsdProcessor.hpp" #include "TeenyVandleProcessor.hpp" #include "TemplateProcessor.hpp" #include "VandleProcessor.hpp" #include "ValidProcessor.hpp" //These headers are for handling experiment specific processing. #include "TemplateExpProcessor.hpp" #include "VandleOrnl2012Processor.hpp" #ifdef useroot //Some processors REQURE ROOT to function #include "Anl1471Processor.hpp" #include "IS600Processor.hpp" #include "RootProcessor.hpp" #include "TwoChanTimingProcessor.hpp" #endif using namespace std; using namespace dammIds::raw; DetectorDriver* DetectorDriver::instance = NULL; DetectorDriver* DetectorDriver::get() { if (!instance) instance = new DetectorDriver(); return instance; } DetectorDriver::DetectorDriver() : histo(OFFSET, RANGE, "DetectorDriver") { cfg_ = Globals::get()->configfile(); Messenger m; try { m.start("Loading Processors"); LoadProcessors(m); } catch (GeneralException &e) { /// Any exception in registering plots in Processors /// and possible other exceptions in creating Processors /// will be intercepted here m.fail(); cout << "Exception caught at DetectorDriver::DetectorDriver" << endl; cout << "\t" << e.what() << endl; throw; } catch (GeneralWarning &w) { cout << "Warning found at DetectorDriver::DetectorDriver" << endl; cout << "\t" << w.what() << endl; } m.done(); } DetectorDriver::~DetectorDriver() { for (vector<EventProcessor *>::iterator it = vecProcess.begin(); it != vecProcess.end(); it++) delete(*it); vecProcess.clear(); for (vector<TraceAnalyzer *>::iterator it = vecAnalyzer.begin(); it != vecAnalyzer.end(); it++) delete(*it); vecAnalyzer.clear(); instance = NULL; } void DetectorDriver::LoadProcessors(Messenger& m) { pugi::xml_document doc; pugi::xml_parse_result result = doc.load_file(cfg_.c_str()); if (!result) { stringstream ss; ss << "DetectorDriver: error parsing file " << cfg_; ss << " : " << result.description(); throw IOException(ss.str()); } DetectorLibrary::get(); pugi::xml_node driver = doc.child("Configuration").child("DetectorDriver"); for (pugi::xml_node processor = driver.child("Processor"); processor; processor = processor.next_sibling("Processor")) { string name = processor.attribute("name").value(); m.detail("Loading " + name); if (name == "BetaScintProcessor") { double gamma_beta_limit = processor.attribute("gamma_beta_limit").as_double(200.e-9); if (gamma_beta_limit == 200.e-9) m.warning("Using default gamme_beta_limit = 200e-9", 1); double energy_contraction = processor.attribute("energy_contraction").as_double(1.0); if (energy_contraction == 1) m.warning("Using default energy contraction = 1", 1); vecProcess.push_back(new BetaScintProcessor(gamma_beta_limit, energy_contraction)); } else if (name == "GeProcessor") { double gamma_threshold = processor.attribute("gamma_threshold").as_double(1.0); if (gamma_threshold == 1.0) m.warning("Using default gamma_threshold = 1.0", 1); double low_ratio = processor.attribute("low_ratio").as_double(1.0); if (low_ratio == 1.0) m.warning("Using default low_ratio = 1.0", 1); double high_ratio = processor.attribute("high_ratio").as_double(3.0); if (high_ratio == 3.0) m.warning("Using default high_ratio = 3.0", 1); double sub_event = processor.attribute("sub_event").as_double(100.e-9); if (sub_event == 100.e-9) m.warning("Using default sub_event = 100e-9", 1); double gamma_beta_limit = processor.attribute("gamma_beta_limit").as_double(200.e-9); if (gamma_beta_limit == 200.e-9) m.warning("Using default gamme_beta_limit = 200e-9", 1); double gamma_gamma_limit = processor.attribute("gamma_gamma_limit").as_double(200.e-9); if (gamma_gamma_limit == 200.e-9) m.warning("Using default gamma_gamma_limit = 200e-9", 1); double cycle_gate1_min = processor.attribute("cycle_gate1_min").as_double(0.0); if (cycle_gate1_min == 0.0) m.warning("Using default cycle_gate1_min = 0.0", 1); double cycle_gate1_max = processor.attribute("cycle_gate1_max").as_double(0.0); if (cycle_gate1_max == 0.0) m.warning("Using default cycle_gate1_max = 0.0", 1); double cycle_gate2_min = processor.attribute("cycle_gate2_min").as_double(0.0); if (cycle_gate2_min == 0.0) m.warning("Using default cycle_gate2_min = 0.0", 1); double cycle_gate2_max = processor.attribute("cycle_gate2_max").as_double(0.0); if (cycle_gate2_max == 0.0) m.warning("Using default cycle_gate2_max = 0.0", 1); vecProcess.push_back(new GeProcessor(gamma_threshold, low_ratio, high_ratio, sub_event, gamma_beta_limit, gamma_gamma_limit, cycle_gate1_min, cycle_gate1_max, cycle_gate2_min, cycle_gate2_max)); } else if (name == "GeCalibProcessor") { double gamma_threshold = processor.attribute("gamma_threshold").as_double(1); double low_ratio = processor.attribute("low_ratio").as_double(1); double high_ratio = processor.attribute("high_ratio").as_double(3); vecProcess.push_back(new GeCalibProcessor(gamma_threshold, low_ratio, high_ratio)); } else if (name == "Hen3Processor") { vecProcess.push_back(new Hen3Processor()); } else if (name == "IonChamberProcessor") { vecProcess.push_back(new IonChamberProcessor()); } else if (name == "LiquidScintProcessor") { vecProcess.push_back(new LiquidScintProcessor()); } else if (name == "LogicProcessor") { vecProcess.push_back(new LogicProcessor()); } else if (name == "NeutronScintProcessor") { vecProcess.push_back(new NeutronScintProcessor()); } else if (name == "PositionProcessor") { vecProcess.push_back(new PositionProcessor()); } else if (name == "SsdProcessor") { vecProcess.push_back(new SsdProcessor()); } else if (name == "VandleProcessor") { double res = processor.attribute("res").as_double(2.0); double offset = processor.attribute("offset").as_double(200.0); unsigned int numStarts = processor.attribute("NumStarts").as_int(2); vector<string> types = strings::tokenize(processor.attribute("types").as_string(),","); vecProcess.push_back(new VandleProcessor(types, res, offset, numStarts)); } else if (name == "TeenyVandleProcessor") { vecProcess.push_back(new TeenyVandleProcessor()); } else if (name == "DoubleBetaProcessor") { vecProcess.push_back(new DoubleBetaProcessor()); } else if (name == "PspmtProcessor") { vecProcess.push_back(new PspmtProcessor()); } else if (name == "TemplateProcessor") { vecProcess.push_back(new TemplateProcessor()); } else if (name == "TemplateExpProcessor") { vecProcess.push_back(new TemplateExpProcessor()); } #ifdef useroot //Certain process REQURE root to actually work else if (name == "Anl1471Processor") { vecProcess.push_back(new Anl1471Processor()); } else if (name == "TwoChanTimingProcessor") { vecProcess.push_back(new TwoChanTimingProcessor()); } else if (name == "IS600Processor") { vecProcess.push_back(new IS600Processor()); } else if (name == "VandleOrnl2012Processor") { vecProcess.push_back(new VandleOrnl2012Processor()); } else if (name == "RootProcessor") { vecProcess.push_back(new RootProcessor("tree.root", "tree")); } #endif else { stringstream ss; ss << "DetectorDriver: unknown processor type : " << name; throw GeneralException(ss.str()); } stringstream ss; for (pugi::xml_attribute_iterator ait = processor.attributes_begin(); ait != processor.attributes_end(); ++ait) { ss.str(""); ss << ait->name(); if (ss.str().compare("name") != 0) { ss << " = " << ait->value(); m.detail(ss.str(), 1); } } } for (pugi::xml_node analyzer = driver.child("Analyzer"); analyzer; analyzer = analyzer.next_sibling("Analyzer")) { string name = analyzer.attribute("name").value(); m.detail("Loading " + name); if(name == "TraceFilterAnalyzer") { bool findPileups = analyzer.attribute("FindPileup").as_bool(false); vecAnalyzer.push_back(new TraceFilterAnalyzer(findPileups)); } else if(name == "TauAnalyzer") { vecAnalyzer.push_back(new TauAnalyzer()); } else if (name == "TraceExtractor") { string type = analyzer.attribute("type").as_string(); string subtype = analyzer.attribute("subtype").as_string(); string tag = analyzer.attribute("tag").as_string(); vecAnalyzer.push_back(new TraceExtractor(type, subtype,tag)); } else if (name == "WaveformAnalyzer") { vecAnalyzer.push_back(new WaveformAnalyzer()); } else if (name == "CfdAnalyzer") { string type = analyzer.attribute("type").as_string(); vecAnalyzer.push_back(new CfdAnalyzer(type)); } else if (name == "WaaAnalyzer") { vecAnalyzer.push_back(new WaaAnalyzer()); } else if (name == "FittingAnalyzer") { string type = analyzer.attribute("type").as_string(); vecAnalyzer.push_back(new FittingAnalyzer(type)); } else { stringstream ss; ss << "DetectorDriver: unknown analyzer type" << name; throw GeneralException(ss.str()); } for (pugi::xml_attribute_iterator ait = analyzer.attributes_begin(); ait != analyzer.attributes_end(); ++ait) { stringstream ss; ss << ait->name(); if (ss.str().compare("name") != 0) { ss << " = " << ait->value(); m.detail(ss.str(), 1); } } } } void DetectorDriver::Init(RawEvent& rawev) { for (vector<TraceAnalyzer *>::iterator it = vecAnalyzer.begin(); it != vecAnalyzer.end(); it++) { (*it)->Init(); (*it)->SetLevel(20); } for (vector<EventProcessor *>::iterator it = vecProcess.begin(); it != vecProcess.end(); it++) { (*it)->Init(rawev); } try { ReadCalXml(); ReadWalkXml(); } catch (GeneralException &e) { //! Any exception in reading calibration and walk correction //! will be intercepted here cout << endl; cout << "Exception caught at DetectorDriver::Init" << endl; cout << "\t" << e.what() << endl; Messenger m; m.fail(); exit(EXIT_FAILURE); } catch (GeneralWarning &w) { cout << "Warning caught at DetectorDriver::Init" << endl; cout << "\t" << w.what() << endl; } } void DetectorDriver::ProcessEvent(RawEvent& rawev) { plot(dammIds::raw::D_NUMBER_OF_EVENTS, dammIds::GENERIC_CHANNEL); try { for (vector<ChanEvent*>::const_iterator it = rawev.GetEventList().begin(); it != rawev.GetEventList().end(); ++it) { PlotRaw((*it)); ThreshAndCal((*it), rawev); PlotCal((*it)); string place = (*it)->GetChanID().GetPlaceName(); if (place == "__9999") continue; if ( (*it)->IsSaturated() || (*it)->IsPileup() ) continue; double time = (*it)->GetTime(); double energy = (*it)->GetCalEnergy(); int location = (*it)->GetChanID().GetLocation(); EventData data(time, energy, location); TreeCorrelator::get()->place(place)->activate(data); } //!First round is preprocessing, where process result must be guaranteed //!to not to be dependent on results of other Processors. for (vector<EventProcessor*>::iterator iProc = vecProcess.begin(); iProc != vecProcess.end(); iProc++) if ( (*iProc)->HasEvent() ) (*iProc)->PreProcess(rawev); ///In the second round the Process is called, which may depend on other ///Processors. for (vector<EventProcessor *>::iterator iProc = vecProcess.begin(); iProc != vecProcess.end(); iProc++) if ( (*iProc)->HasEvent() ) (*iProc)->Process(rawev); // Clear all places in correlator (if of resetable type) for (map<string, Place*>::iterator it = TreeCorrelator::get()->places_.begin(); it != TreeCorrelator::get()->places_.end(); ++it) if ((*it).second->resetable()) (*it).second->reset(); } catch (GeneralException &e) { /// Any exception in activation of basic places, PreProcess and Process /// will be intercepted here cout << endl << Display::ErrorStr("Exception caught at DetectorDriver::ProcessEvent") << endl; throw; } catch (GeneralWarning &w) { cout << Display::WarningStr("Warning caught at " "DetectorDriver::ProcessEvent") << endl; cout << "\t" << Display::WarningStr(w.what()) << endl; } } /// Declare some of the raw and basic plots that are going to be used in the /// analysis of the data. These include raw and calibrated energy spectra, /// information about the run time, and count rates on the detectors. This /// also calls the DeclarePlots method that is present in all of the /// Analyzers and Processors. void DetectorDriver::DeclarePlots() { try { DeclareHistogram1D(D_HIT_SPECTRUM, S7, "channel hit spectrum"); DeclareHistogram2D(DD_RUNTIME_SEC, SE, S6, "run time - s"); DeclareHistogram2D(DD_RUNTIME_MSEC, SE, S7, "run time - ms"); if(Globals::get()->hasRaw()) { DetectorLibrary* modChan = DetectorLibrary::get(); DeclareHistogram1D(D_NUMBER_OF_EVENTS, S4, "event counter"); DeclareHistogram1D(D_HAS_TRACE, S8, "channels with traces"); DeclareHistogram1D(D_SUBEVENT_GAP, SE, "Time Between Channels in 10 ns / bin"); DeclareHistogram1D(D_EVENT_LENGTH, SE, "Event Length in ns"); DeclareHistogram1D(D_EVENT_GAP, SE, "Time Between Events in ns"); DeclareHistogram1D(D_EVENT_MULTIPLICITY, S7, "Number of Channels Event"); DeclareHistogram1D(D_BUFFER_END_TIME, SE, "Buffer Length in ns"); DetectorLibrary::size_type maxChan = modChan->size(); for (DetectorLibrary::size_type i = 0; i < maxChan; i++) { if (!modChan->HasValue(i)) { continue; } stringstream idstr; const Identifier &id = modChan->at(i); idstr << "M" << modChan->ModuleFromIndex(i) << " C" << modChan->ChannelFromIndex(i) << " - " << id.GetType() << ":" << id.GetSubtype() << " L" << id.GetLocation(); DeclareHistogram1D(D_RAW_ENERGY + i, SE, ("RawE " + idstr.str()).c_str() ); DeclareHistogram1D(D_FILTER_ENERGY + i, SE, ("FilterE " + idstr.str()).c_str() ); DeclareHistogram1D(D_SCALAR + i, SE, ("Scalar " + idstr.str()).c_str() ); if (Globals::get()->revision() == "A") DeclareHistogram1D(D_TIME + i, SE, ("Time " + idstr.str()).c_str() ); DeclareHistogram1D(D_CAL_ENERGY + i, SE, ("CalE " + idstr.str()).c_str() ); } } for (vector<TraceAnalyzer *>::const_iterator it = vecAnalyzer.begin(); it != vecAnalyzer.end(); it++) { (*it)->DeclarePlots(); } for (vector<EventProcessor *>::const_iterator it = vecProcess.begin(); it != vecProcess.end(); it++) { (*it)->DeclarePlots(); } } catch (exception &e) { cout << Display::ErrorStr("Exception caught at " "DetectorDriver::DeclarePlots") << endl; throw; } } int DetectorDriver::ThreshAndCal(ChanEvent *chan, RawEvent& rawev) { Identifier chanId = chan->GetChanID(); int id = chan->GetID(); string type = chanId.GetType(); string subtype = chanId.GetSubtype(); map<string, int> tags = chanId.GetTagMap(); bool hasStartTag = chanId.HasTag("start"); Trace &trace = chan->GetTrace(); RandomPool* randoms = RandomPool::get(); double energy = 0.0; if (type == "ignore" || type == "") return(0); if ( !trace.empty() ) { plot(D_HAS_TRACE, id); for (vector<TraceAnalyzer *>::iterator it = vecAnalyzer.begin(); it != vecAnalyzer.end(); it++) { (*it)->Analyze(trace, type, subtype, tags); } if (trace.HasValue("filterEnergy") ) { if (trace.GetValue("filterEnergy") > 0) { energy = trace.GetValue("filterEnergy"); plot(D_FILTER_ENERGY + id, energy); trace.SetValue("filterEnergyCal", cali.GetCalEnergy(chanId, trace.GetValue("filterEnergy"))); } else { energy = 0.0; } /** Calibrate pulses numbered 2 and forth, * add filterEnergyXCal to the trace */ int pulses = trace.GetValue("numPulses"); for (int i = 1; i < pulses; ++i) { stringstream energyName; energyName << "filterEnergy" << i + 1; stringstream energyCalName; energyCalName << "filterEnergy" << i + 1 << "Cal"; trace.SetValue(energyCalName.str(), cali.GetCalEnergy(chanId, trace.GetValue(energyName.str()))); } } if (trace.HasValue("calcEnergy") ) { energy = trace.GetValue("calcEnergy"); chan->SetEnergy(energy); } else if (!trace.HasValue("filterEnergy")) { energy = chan->GetEnergy() + randoms->Get(); } if (trace.HasValue("phase") ) { //Saves the time in nanoseconds chan->SetHighResTime((trace.GetValue("phase") * Globals::get()->adcClockInSeconds() + (double)chan->GetTrigTime() * Globals::get()->filterClockInSeconds()) * 1e9); } } else { /// otherwise, use the Pixie on-board calculated energy /// add a random number to convert an integer value to a /// uniformly distributed floating point energy = chan->GetEnergy() + randoms->Get(); chan->SetHighResTime(0.0); } /** Calibrate energy and apply the walk correction. */ double time, walk_correction; if(chan->GetHighResTime() == 0.0) { time = chan->GetTime(); //time is in clock ticks walk_correction = walk.GetCorrection(chanId, energy); } else { time = chan->GetHighResTime(); //time here is in ns walk_correction = walk.GetCorrection(chanId, trace.GetValue("tqdc")); } chan->SetCalEnergy(cali.GetCalEnergy(chanId, energy)); chan->SetCorrectedTime(time - walk_correction); rawev.GetSummary(type)->AddEvent(chan); DetectorSummary *summary; summary = rawev.GetSummary(type + ':' + subtype, false); if (summary != NULL) summary->AddEvent(chan); if(hasStartTag && type != "logic") { summary = rawev.GetSummary(type + ':' + subtype + ':' + "start", false); if (summary != NULL) summary->AddEvent(chan); } return(1); } int DetectorDriver::PlotRaw(const ChanEvent *chan) { plot(D_RAW_ENERGY + chan->GetID(), chan->GetEnergy()); return(0); } int DetectorDriver::PlotCal(const ChanEvent *chan) { plot(D_CAL_ENERGY + chan->GetID(), chan->GetCalEnergy()); return(0); } EventProcessor* DetectorDriver::GetProcessor(const std::string& name) const { for (vector<EventProcessor *>::const_iterator it = vecProcess.begin(); it != vecProcess.end(); it++) { if ( (*it)->GetName() == name ) return(*it); } return(NULL); } void DetectorDriver::ReadCalXml() { pugi::xml_document doc; pugi::xml_parse_result result = doc.load_file(cfg_.c_str()); if (!result) { stringstream ss; ss << "DetectorDriver: error parsing file" << cfg_; ss << " : " << result.description(); throw GeneralException(ss.str()); } Messenger m; m.start("Loading Calibration"); pugi::xml_node map = doc.child("Configuration").child("Map"); /** Note that before this reading in of the xml file, it was already * processed for the purpose of creating the channels map. * Some sanity checks (module and channel number) were done there * so they are not repeated here/ */ bool verbose = map.attribute("verbose_calibration").as_bool(); for (pugi::xml_node module = map.child("Module"); module; module = module.next_sibling("Module")) { int module_number = module.attribute("number").as_int(-1); for (pugi::xml_node channel = module.child("Channel"); channel; channel = channel.next_sibling("Channel")) { int ch_number = channel.attribute("number").as_int(-1); Identifier chanID = DetectorLibrary::get()->at(module_number, ch_number); bool calibrated = false; for (pugi::xml_node cal = channel.child("Calibration"); cal; cal = cal.next_sibling("Calibration")) { string model = cal.attribute("model").as_string("None"); double min = cal.attribute("min").as_double(0); double max = cal.attribute("max").as_double(numeric_limits<double>::max()); stringstream pars(cal.text().as_string()); vector<double> parameters; while (true) { double p; pars >> p; if (pars) parameters.push_back(p); else break; } if (verbose) { stringstream ss; ss << "Module " << module_number << ", channel " << ch_number << ": "; ss << " model-" << model; for (vector<double>::iterator it = parameters.begin(); it != parameters.end(); ++it) ss << " " << (*it); m.detail(ss.str(), 1); } cali.AddChannel(chanID, model, min, max, parameters); calibrated = true; } if (!calibrated && verbose) { stringstream ss; ss << "Module " << module_number << ", channel " << ch_number << ": "; ss << " non-calibrated"; m.detail(ss.str(), 1); } } } m.done(); } void DetectorDriver::ReadWalkXml() { pugi::xml_document doc; pugi::xml_parse_result result = doc.load_file(cfg_.c_str()); if (!result) { stringstream ss; ss << "DetectorDriver: error parsing file " << cfg_; ss << " : " << result.description(); throw GeneralException(ss.str()); } Messenger m; m.start("Loading Walk Corrections"); pugi::xml_node map = doc.child("Configuration").child("Map"); /** See comment in the similiar place at ReadCalXml() */ bool verbose = map.attribute("verbose_walk").as_bool(); for (pugi::xml_node module = map.child("Module"); module; module = module.next_sibling("Module")) { int module_number = module.attribute("number").as_int(-1); for (pugi::xml_node channel = module.child("Channel"); channel; channel = channel.next_sibling("Channel")) { int ch_number = channel.attribute("number").as_int(-1); Identifier chanID = DetectorLibrary::get()->at(module_number, ch_number); bool corrected = false; for (pugi::xml_node walkcorr = channel.child("WalkCorrection"); walkcorr; walkcorr = walkcorr.next_sibling("WalkCorrection")) { string model = walkcorr.attribute("model").as_string("None"); double min = walkcorr.attribute("min").as_double(0); double max = walkcorr.attribute("max").as_double( numeric_limits<double>::max()); stringstream pars(walkcorr.text().as_string()); vector<double> parameters; while (true) { double p; pars >> p; if (pars) parameters.push_back(p); else break; } if (verbose) { stringstream ss; ss << "Module " << module_number << ", channel " << ch_number << ": "; ss << " model: " << model; for (vector<double>::iterator it = parameters.begin(); it != parameters.end(); ++it) ss << " " << (*it); m.detail(ss.str(), 1); } walk.AddChannel(chanID, model, min, max, parameters); corrected = true; } if (!corrected && verbose) { stringstream ss; ss << "Module " << module_number << ", channel " << ch_number << ": "; ss << " not corrected for walk"; m.detail(ss.str(), 1); } } } m.done(); }
pixie16/paassdoc
Analysis/Utkscan/core/source/DetectorDriver.cpp
C++
gpl-3.0
28,756
/** * Copyright (C) 2005-2015, Stefan Strömberg <stestr@nethome.nu> * * This file is part of OpenNetHome. * * OpenNetHome is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenNetHome is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package nu.nethome.zwave.messages.commandclasses; import nu.nethome.zwave.messages.commandclasses.framework.CommandAdapter; import nu.nethome.zwave.messages.commandclasses.framework.CommandClass; import nu.nethome.zwave.messages.commandclasses.framework.CommandCode; import nu.nethome.zwave.messages.commandclasses.framework.CommandProcessorAdapter; import nu.nethome.zwave.messages.framework.DecoderException; import java.io.ByteArrayOutputStream; public class MultiLevelSwitchCommandClass implements CommandClass { public static final int SWITCH_MULTILEVEL_SET = 0x01; public static final int SWITCH_MULTILEVEL_GET = 0x02; public static final int SWITCH_MULTILEVEL_REPORT = 0x03; public static final int SWITCH_MULTILEVEL_START_LEVEL_CHANGE = 0x04; public static final int SWITCH_MULTILEVEL_STOP_LEVEL_CHANGE = 0x05; public static final int SWITCH_MULTILEVEL_SUPPORTED_GET = 0x06; public static final int SWITCH_MULTILEVEL_SUPPORTED_REPORT = 0x07; public static final int COMMAND_CLASS = 0x26; public static class Set extends CommandAdapter { public final int level; public Set(int level) { super(COMMAND_CLASS, SWITCH_MULTILEVEL_SET); this.level = level; } public Set(byte[] data) throws DecoderException { super(data, COMMAND_CLASS, SWITCH_MULTILEVEL_SET); level = in.read(); } public static class Processor extends CommandProcessorAdapter<Set> { @Override public CommandCode getCommandCode() { return new CommandCode(COMMAND_CLASS, SWITCH_MULTILEVEL_SET); } @Override public Set process(byte[] command, CommandArgument argument) throws DecoderException { return process(new Set(command), argument); } } @Override protected void addCommandData(ByteArrayOutputStream result) { super.addCommandData(result); result.write(level); } } public static class Get extends CommandAdapter { public Get() { super(COMMAND_CLASS, SWITCH_MULTILEVEL_GET); } } public static class Report extends CommandAdapter { public final int level; public Report(int level) { super(COMMAND_CLASS, SWITCH_MULTILEVEL_REPORT); this.level = level; } public Report(byte[] data) throws DecoderException { super(data, COMMAND_CLASS, SWITCH_MULTILEVEL_REPORT); level = in.read(); } @Override protected void addCommandData(ByteArrayOutputStream result) { super.addCommandData(result); result.write(level); } public static class Processor extends CommandProcessorAdapter<Report> { @Override public CommandCode getCommandCode() { return new CommandCode(COMMAND_CLASS, SWITCH_MULTILEVEL_REPORT); } @Override public Report process(byte[] command, CommandArgument argument) throws DecoderException { return process(new Report(command), argument); } } @Override public String toString() { return String.format("{\"MultiLevelSwitch.Report\":{\"level\": %d}}", level); } } public static class StartLevelChange extends CommandAdapter { private static final int DIRECTION_BIT = 1<<6; private static final int IGNORE_START_POSITION_BIT = 1<<5; public enum Direction {UP, DOWN} public final Direction direction; public final Integer startLevel; public final int duration; public StartLevelChange(int startLevel, Direction direction) { super(COMMAND_CLASS, SWITCH_MULTILEVEL_START_LEVEL_CHANGE); this.direction = direction; this.startLevel = startLevel; duration = 0xFF; } public StartLevelChange(Direction direction) { super(COMMAND_CLASS, SWITCH_MULTILEVEL_START_LEVEL_CHANGE); this.direction = direction; this.startLevel = null; duration = 0xFF; } public StartLevelChange(Direction direction, int duration) { super(COMMAND_CLASS, SWITCH_MULTILEVEL_START_LEVEL_CHANGE); this.direction = direction; this.startLevel = null; this.duration = duration; } public StartLevelChange(byte[] data) throws DecoderException { super(data, COMMAND_CLASS, SWITCH_MULTILEVEL_START_LEVEL_CHANGE); int mode = in.read(); int startLevel = in.read(); direction = ((mode & DIRECTION_BIT) != 0) ? Direction.DOWN : Direction.UP; this.startLevel = ((mode & IGNORE_START_POSITION_BIT) != 0) ? null : startLevel; if (in.available() > 0) { duration = in.read(); } else { duration = 0xFF; } } public static class Processor extends CommandProcessorAdapter<Set> { @Override public CommandCode getCommandCode() { return new CommandCode(COMMAND_CLASS, SWITCH_MULTILEVEL_START_LEVEL_CHANGE); } @Override public Set process(byte[] command, CommandArgument argument) throws DecoderException { return process(new Set(command), argument); } } @Override protected void addCommandData(ByteArrayOutputStream result) { super.addCommandData(result); int mode = (direction == Direction.DOWN) ? DIRECTION_BIT : 0; int tempStartLevel = 0; if (startLevel == null) { mode |= IGNORE_START_POSITION_BIT; } else { tempStartLevel = startLevel; } result.write(mode); result.write(tempStartLevel); result.write(duration); } } public static class StopLevelChange extends CommandAdapter { public StopLevelChange() { super(COMMAND_CLASS, SWITCH_MULTILEVEL_STOP_LEVEL_CHANGE); } public StopLevelChange(byte[] data) throws DecoderException { super(data, COMMAND_CLASS, SWITCH_MULTILEVEL_STOP_LEVEL_CHANGE); } public static class Processor extends CommandProcessorAdapter<Set> { @Override public CommandCode getCommandCode() { return new CommandCode(COMMAND_CLASS, SWITCH_MULTILEVEL_STOP_LEVEL_CHANGE); } @Override public Set process(byte[] command, CommandArgument argument) throws DecoderException { return process(new Set(command), argument); } } @Override protected void addCommandData(ByteArrayOutputStream result) { super.addCommandData(result); } } }
NetHome/ZWave
src/main/java/nu/nethome/zwave/messages/commandclasses/MultiLevelSwitchCommandClass.java
Java
gpl-3.0
7,780
package com.bryanrm.ftptransfer.network; import android.content.Context; import android.os.AsyncTask; import android.widget.Toast; import com.bryanrm.ftptransfer.R; import com.bryanrm.ftptransfer.ftp.WrapFTP; import java.io.InputStream; /** * Created by Bryan R Martinez on 1/3/2017. */ public class Upload extends AsyncTask<Void, Void, Boolean> { private Context context; private String fileName; private InputStream inputStream; public Upload(Context context, String fileName, InputStream inputStream) { this.context = context; this.fileName = fileName; this.inputStream = inputStream; } @Override protected Boolean doInBackground(Void... params) { publishProgress(); return WrapFTP.getInstance().uploadFile(fileName, inputStream); } @Override protected void onProgressUpdate(Void... values) { Toast.makeText(context, context.getString(R.string.message_file_ul_start), Toast.LENGTH_SHORT).show(); } @Override protected void onPostExecute(Boolean result) { if (result) { Toast.makeText(context, context.getString(R.string.message_file_uploaded), Toast.LENGTH_LONG).show(); } else { Toast.makeText(context, context.getString(R.string.message_file_not_uploaded), Toast.LENGTH_LONG).show(); } } }
bryanrm/android-ftp-transfer
app/src/main/java/com/bryanrm/ftptransfer/network/Upload.java
Java
gpl-3.0
1,453
package org.flowerplatform.util.diff_update; import java.io.Serializable; import java.util.Objects; /** * * @author Claudiu Matei * */ public class DiffUpdate implements Serializable { private static final long serialVersionUID = -7517448831349466230L; private long id; private long timestamp = System.currentTimeMillis(); private String type; private String entityUid; /** * Non-conventional getter/setter so that it's not serialized to client */ private Object entity; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getEntityUid() { return entityUid; } public void setEntityUid(String entityUid) { this.entityUid = entityUid; } /** * @see #entity */ public Object entity() { return entity; } /** * @see #entity */ public void entity(Object entity) { this.entity = entity; } @Override public String toString() { return "DiffUpdate[type=" + type + ", id=" + id + ", entityUid=" + entityUid + "]"; } public long getTimestamp() { return timestamp; } @Override public boolean equals(Object obj) { DiffUpdate otherUpdate = (DiffUpdate) obj; return Objects.equals(type, otherUpdate.type) && Objects.equals(entityUid, otherUpdate.entityUid); } @Override public int hashCode() { return type.hashCode() + 3 * entityUid.hashCode(); } }
flower-platform/flower-platform-4
org.flowerplatform.util/src/org/flowerplatform/util/diff_update/DiffUpdate.java
Java
gpl-3.0
1,571
# Load the Rails application. require_relative 'application' # Initialize the Rails application. Rails.application.initialize! if ActiveRecord::Base.connection.pool.connected? then puts "connection size is #{ActiveRecord::Base.connection.pool.size}" puts "new connection size is #{ActiveRecord::Base.connection.pool.size}" if System.table_exists? then System.instance # load system and set new connection pools Rails.application.wakeup_or_start_observer_thread Rails.application.wakeup_or_start_epgdump_thread end else puts "no connection now" end
shinjiro-itagaki/shinjirecs
shinjirecs-rails-server/config/environment.rb
Ruby
gpl-3.0
573
/** * Balero CMS Project: Proyecto 100% Mexicano de código libre. * Página Oficial: http://www.balerocms.com * * @author Anibal Gomez <anibalgomez@icloud.com> * @copyright Copyright (C) 2015 Neblina Software. Derechos reservados. * @license Licencia BSD; vea LICENSE.txt */ package com.neblina.balero; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; @Configuration @EnableAutoConfiguration @EnableScheduling @ComponentScan @EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true) public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
neblina-software/balerocms-v2
src/main/java/com/neblina/balero/Application.java
Java
gpl-3.0
1,024
/* * gVirtuS -- A GPGPU transparent virtualization component. * * Copyright (C) 2009-2010 The University of Napoli Parthenope at Naples. * * This file is part of gVirtuS. * * gVirtuS is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * gVirtuS is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU General Public License * along with gVirtuS; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * Written by: Giuseppe Coviello <giuseppe.coviello@uniparthenope.it>, * Department of Applied Science */ #include "CudaRtHandler.h" CUDA_ROUTINE_HANDLER(DeviceSetCacheConfig) { try { cudaFuncCache cacheConfig = input_buffer->Get<cudaFuncCache>(); cudaError_t exit_code = cudaDeviceSetCacheConfig(cacheConfig); return new Result(exit_code); } catch (string e) { cerr << e << endl; return new Result(cudaErrorMemoryAllocation); //??? } } CUDA_ROUTINE_HANDLER(DeviceSetLimit) { try { cudaLimit limit = input_buffer->Get<cudaLimit>(); size_t value = input_buffer->Get<size_t>(); cudaError_t exit_code = cudaDeviceSetLimit(limit, value); return new Result(exit_code); } catch (string e) { cerr << e << endl; return new Result(cudaErrorMemoryAllocation); //??? } } CUDA_ROUTINE_HANDLER(IpcOpenMemHandle) { void *devPtr = NULL; try { cudaIpcMemHandle_t handle = input_buffer->Get<cudaIpcMemHandle_t>(); unsigned int flags = input_buffer->Get<unsigned int>(); cudaError_t exit_code = cudaIpcOpenMemHandle(&devPtr, handle, flags); Buffer *out = new Buffer(); out->AddMarshal(devPtr); return new Result(exit_code, out); } catch (string e) { cerr << e << endl; return new Result(cudaErrorMemoryAllocation); } } CUDA_ROUTINE_HANDLER(DeviceEnablePeerAccess) { int peerDevice = input_buffer->Get<int>(); unsigned int flags = input_buffer->Get<unsigned int>(); cudaError_t exit_code = cudaDeviceEnablePeerAccess(peerDevice, flags); return new Result(exit_code); } CUDA_ROUTINE_HANDLER(DeviceDisablePeerAccess) { int peerDevice = input_buffer->Get<int>(); cudaError_t exit_code = cudaDeviceDisablePeerAccess(peerDevice); return new Result(exit_code); } CUDA_ROUTINE_HANDLER(DeviceCanAccessPeer) { int *canAccessPeer = input_buffer->Assign<int>(); int device = input_buffer->Get<int>(); int peerDevice = input_buffer->Get<int>(); cudaError_t exit_code = cudaDeviceCanAccessPeer(canAccessPeer, device, peerDevice); Buffer *out = new Buffer(); try { out->Add(canAccessPeer); } catch (string e) { cerr << e << endl; return new Result(cudaErrorMemoryAllocation); } return new Result(exit_code, out); } CUDA_ROUTINE_HANDLER(DeviceGetStreamPriorityRange) { int *leastPriority = input_buffer->Assign<int>(); int *greatestPriority = input_buffer->Assign<int>(); cudaError_t exit_code = cudaDeviceGetStreamPriorityRange(leastPriority, greatestPriority); Buffer *out = new Buffer(); try { out->Add(leastPriority); out->Add(greatestPriority); } catch (string e) { cerr << e << endl; return new Result(cudaErrorMemoryAllocation); } return new Result(exit_code, out); } CUDA_ROUTINE_HANDLER(OccupancyMaxActiveBlocksPerMultiprocessor) { int *numBlocks = input_buffer->Assign<int>(); const char *func = (const char*) (input_buffer->Get<pointer_t> ()); int blockSize = input_buffer->Get<int>(); size_t dynamicSMemSize = input_buffer->Get<size_t>(); cudaError_t exit_code = cudaOccupancyMaxActiveBlocksPerMultiprocessor(numBlocks, func, blockSize, dynamicSMemSize); Buffer *out = new Buffer(); try { out->Add(numBlocks); } catch (string e) { cerr << e << endl; return new Result(cudaErrorMemoryAllocation); } return new Result(exit_code, out); } CUDA_ROUTINE_HANDLER(DeviceGetAttribute) { int *value = input_buffer->Assign<int>(); cudaDeviceAttr attr = input_buffer->Get<cudaDeviceAttr>(); int device = input_buffer->Get<int>(); cudaError_t exit_code = cudaDeviceGetAttribute(value, attr, device); Buffer *out = new Buffer(); try { out->Add(value); } catch (string e) { cerr << e << endl; return new Result(cudaErrorMemoryAllocation); } return new Result(exit_code, out); } CUDA_ROUTINE_HANDLER(IpcGetMemHandle) { cudaIpcMemHandle_t *handle = input_buffer->Assign<cudaIpcMemHandle_t>(); void *devPtr = input_buffer->GetFromMarshal<void *>(); cudaError_t exit_code = cudaIpcGetMemHandle(handle, devPtr); Buffer *out = new Buffer(); try { out->Add(handle); } catch (string e) { cerr << e << endl; return new Result(cudaErrorMemoryAllocation); } return new Result(exit_code, out); } CUDA_ROUTINE_HANDLER(IpcGetEventHandle) { cudaIpcEventHandle_t *handle = input_buffer->Assign<cudaIpcEventHandle_t>(); cudaEvent_t event = input_buffer->Get<cudaEvent_t>(); cudaError_t exit_code = cudaIpcGetEventHandle(handle, event); Buffer *out = new Buffer(); try { out->Add(handle); } catch (string e) { cerr << e << endl; return new Result(cudaErrorMemoryAllocation); } return new Result(exit_code, out); } CUDA_ROUTINE_HANDLER(ChooseDevice) { int *device = input_buffer->Assign<int>(); const cudaDeviceProp *prop = input_buffer->Assign<cudaDeviceProp>(); cudaError_t exit_code = cudaChooseDevice(device, prop); Buffer *out = new Buffer(); try { out->Add(device); } catch (string e) { cerr << e << endl; return new Result(cudaErrorMemoryAllocation); } return new Result(exit_code, out); } CUDA_ROUTINE_HANDLER(GetDevice) { try { int *device = input_buffer->Assign<int>(); cudaError_t exit_code = cudaGetDevice(device); Buffer *out = new Buffer(); out->Add(device); return new Result(exit_code, out); } catch (string e) { cerr << e << endl; return new Result(cudaErrorMemoryAllocation); } } CUDA_ROUTINE_HANDLER(DeviceReset) { cudaError_t exit_code = cudaDeviceReset(); Buffer *out = new Buffer(); return new Result(exit_code, out); } CUDA_ROUTINE_HANDLER(DeviceSynchronize) { cudaError_t exit_code = cudaDeviceSynchronize(); try { Buffer *out = new Buffer(); return new Result(exit_code, out); } catch (string e) { cerr << e << endl; return new Result(cudaErrorMemoryAllocation); } } CUDA_ROUTINE_HANDLER(GetDeviceCount) { try { int *count = input_buffer->Assign<int>(); cudaError_t exit_code = cudaGetDeviceCount(count); Buffer *out = new Buffer(); out->Add(count); return new Result(exit_code, out); } catch (string e) { cerr << e << endl; return new Result(cudaErrorMemoryAllocation); } } CUDA_ROUTINE_HANDLER(GetDeviceProperties) { try { struct cudaDeviceProp *prop = input_buffer->Assign<struct cudaDeviceProp>(); int device = input_buffer->Get<int>(); cudaError_t exit_code = cudaGetDeviceProperties(prop, device); #ifndef CUDART_VERSION #error CUDART_VERSION not defined #endif #if CUDART_VERSION >= 2030 prop->canMapHostMemory = 0; #endif Buffer *out = new Buffer(); out->Add(prop, 1); return new Result(exit_code, out); } catch (string e) { cerr << e << endl; return new Result(cudaErrorMemoryAllocation); } } CUDA_ROUTINE_HANDLER(SetDevice) { try { int device = input_buffer->Get<int>(); cudaError_t exit_code = cudaSetDevice(device); return new Result(exit_code); } catch (string e) { cerr << e << endl; return new Result(cudaErrorMemoryAllocation); } } #ifndef CUDART_VERSION #error CUDART_VERSION not defined #endif #if CUDART_VERSION >= 2030 CUDA_ROUTINE_HANDLER(SetDeviceFlags) { try { int flags = input_buffer->Get<int>(); cudaError_t exit_code = cudaSetDeviceFlags(flags); return new Result(exit_code); } catch (string e) { cerr << e << endl; return new Result(cudaErrorMemoryAllocation); } } CUDA_ROUTINE_HANDLER(IpcOpenEventHandle) { Buffer *out = new Buffer(); try { cudaEvent_t *event = input_buffer->Assign<cudaEvent_t>(); cudaIpcEventHandle_t handle = input_buffer->Get<cudaIpcEventHandle_t>(); cudaError_t exit_code = cudaIpcOpenEventHandle(event, handle); out->Add(event); } catch (string e) { cerr << e << endl; return new Result(cudaErrorMemoryAllocation); } } CUDA_ROUTINE_HANDLER(SetValidDevices) { try { int len = input_buffer->BackGet<int>(); int *device_arr = input_buffer->Assign<int>(len); cudaError_t exit_code = cudaSetValidDevices(device_arr, len); Buffer *out = new Buffer(); out->Add(device_arr, len); return new Result(exit_code, out); } catch (string e) { cerr << e << endl; return new Result(cudaErrorMemoryAllocation); } } #endif
Donkey-Sand/gvirtus-multiGPU
gvirtus.cudart/backend/CudaRtHandler_device.cpp
C++
gpl-3.0
9,738
# -*- coding: utf8 -*- from yanntricks import * def UQZooGFLNEq(): pspict,fig = SinglePicture("UQZooGFLNEq") pspict.dilatation_X(1) pspict.dilatation_Y(1) mx=-5 Mx=5 x=var('x') f=phyFunction( arctan(x) ).graph(mx,Mx) seg1=Segment( Point(mx,pi/2),Point(Mx,pi/2) ) seg2=Segment( Point(mx,-pi/2),Point(Mx,-pi/2) ) seg1.parameters.color="red" seg2.parameters.color="red" seg1.parameters.style="dashed" seg2.parameters.style="dashed" pspict.DrawGraphs(f,seg1,seg2) pspict.axes.single_axeY.axes_unit=AxesUnit(pi/2,'') pspict.DrawDefaultAxes() fig.no_figure() fig.conclude() fig.write_the_file()
LaurentClaessens/mazhe
src_yanntricks/yanntricksUQZooGFLNEq.py
Python
gpl-3.0
671
'use strict'; module.exports = { minVersion: "5.0.0", currentVersion: "5.2.0", activeDelegates: 101, addressLength: 208, blockHeaderLength: 248, confirmationLength: 77, epochTime: new Date(Date.UTC(2016, 4, 24, 17, 0, 0, 0)), fees:{ send: 10000000, vote: 100000000, secondsignature: 500000000, delegate: 6000000000, multisignature: 500000000, dapp: 2500000000 }, feeStart: 1, feeStartVolume: 10000 * 100000000, fixedPoint : Math.pow(10, 8), forgingTimeOut: 500, // 50 blocks maxAddressesLength: 208 * 128, maxAmount: 100000000, maxClientConnections: 100, maxConfirmations : 77 * 100, maxPayloadLength: 1024 * 1024, maxRequests: 10000 * 12, maxSignaturesLength: 196 * 256, maxTxsPerBlock: 25, numberLength: 100000000, requestLength: 104, rewards: { milestones: [ 100000000, // Initial reward 70000000, // Milestone 1 50000000, // Milestone 2 30000000, // Milestone 3 20000000 // Milestone 4 ], offset: 10, // Start rewards at block (n) distance: 3000000, // Distance between each milestone }, signatureLength: 196, totalAmount: 1009000000000000, unconfirmedTransactionTimeOut: 10800 // 1080 blocks };
shiftcurrency/shift
helpers/constants.js
JavaScript
gpl-3.0
1,217
<?php /** * @package GPL Cart core * @author Iurii Makukh <gplcart.software@gmail.com> * @copyright Copyright (c) 2015, Iurii Makukh * @license https://www.gnu.org/licenses/gpl.html GNU/GPLv3 */ namespace gplcart\core\models; use gplcart\core\Hook; use gplcart\core\models\Translation as TranslationModel; /** * Manages basic behaviors and data related to payment methods */ class Payment { /** * Hook class instance * @var \gplcart\core\Hook $hook */ protected $hook; /** * Translation UI model instance * @var \gplcart\core\models\Translation $translation */ protected $translation; /** * @param Hook $hook * @param Translation $translation */ public function __construct(Hook $hook, TranslationModel $translation) { $this->hook = $hook; $this->translation = $translation; } /** * Returns an array of payment methods * @param array $options * @return array */ public function getList(array $options = array()) { $methods = &gplcart_static(gplcart_array_hash(array('payment.methods' => $options))); if (isset($methods)) { return $methods; } $methods = $this->getDefaultList(); $this->hook->attach('payment.methods', $methods, $this); $weights = array(); foreach ($methods as $id => &$method) { $method['id'] = $id; if (!isset($method['weight'])) { $method['weight'] = 0; } if (!empty($options['status']) && empty($method['status'])) { unset($methods[$id]); continue; } if (!empty($options['module']) && (empty($method['module']) || !in_array($method['module'], (array) $options['module']))) { unset($methods[$id]); continue; } $weights[] = $method['weight']; } if (empty($methods)) { return array(); } // Sort by weight then by key array_multisort($weights, SORT_ASC, array_keys($methods), SORT_ASC, $methods); return $methods; } /** * Returns a payment method * @param string $method_id * @return array */ public function get($method_id) { $methods = $this->getList(); return empty($methods[$method_id]) ? array() : $methods[$method_id]; } /** * Returns an array of default payment methods * @return array */ protected function getDefaultList() { return array( 'cod' => array( 'title' => $this->translation->text('Cash on delivery'), 'description' => $this->translation->text('Payment for an order is made at the time of delivery'), 'template' => array('complete' => ''), 'image' => '', 'module' => 'core', 'status' => true, 'weight' => 0 ) ); } }
gplcart/gplcart
system/core/models/Payment.php
PHP
gpl-3.0
3,062
const path = require('path'); const webpack = require('webpack'); var HtmlWebpackPlugin = require('html-webpack-plugin'); var ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin'); var CopyWebpackPlugin = require('copy-webpack-plugin'); module.exports = { // 页面入口文件配置 entry: { app: [ path.normalize(process.argv[process.argv.length // - 1]) // 默认规则,最后一个参数是entry ] }, 入口文件输出配置 output: { //publicPath: '/dist', path: __dirname + '/www/dist/', filename: '[name].[chunkhash:5].js' }, module: { //加载器配置 rules: [ { test: /\.js|\.jsx$/, // exclude: // /node_modules[\\|\/](?!react-native|@shoutem\\theme|@remobile\\react-native)/, loader: 'babel-loader', options: { //retainLines: true, 'compact':false, 'presets': [ 'react', 'es2015', 'es2017', 'stage-0', 'stage-1', // 'stage-2', 'stage-3' ], 'plugins': [//'transform-runtime', 'transform-decorators-legacy'] }, include: path.resolve(__dirname, (process.cwd() !== path.dirname(__dirname) ? '../../' : '') + "../node_modules") }, { test: /\.ttf$/, loader: "url-loader", // or directly file-loader include: path.resolve(__dirname, (process.cwd() !== path.dirname(__dirname) ? '../../' : '') + "../node_modules/react-native-vector-icons") } ] }, //其它解决方案配置 resolve: { extensions: [ '', '.web.js', '.js' ], alias: { 'react-native': 'react-native-web' } }, plugins: [ new CopyWebpackPlugin([ { from: path.join(__dirname, (process.cwd() !== path.dirname(__dirname) ? '../../' : '') + '../node_modules/babel-polyfill/dist/polyfill.min.js'), to: path.join(__dirname, 'www', 'dist') }, { from: path.join(__dirname, 'viewport.js'), to: path.join(__dirname, 'www', 'dist', 'viewport.min.js') }]), new HtmlWebpackPlugin({ template: __dirname + '/index.temp.html', filename: __dirname + '/www/index.html', minify: { removeComments: true, collapseWhitespace: true, collapseInlineTagWhitespace: true, //conservativeCollapse: true, preserveLineBreaks: true, minifyCSS: true, removeScriptTypeAttributes: true, removeStyleLinkTypeAttributes: true } }), new ScriptExtHtmlWebpackPlugin({defaultAttribute: 'async'}), // new webpack.optimize.DedupePlugin(), new ChunkModuleIDPlugin(), new // webpack.NoErrorsPlugin(), new webpack.DefinePlugin({'__DEV__': false, 'process.env.NODE_ENV': '"production"'}), // new webpack.ProvidePlugin({ '__DEV__': false }), new webpack.SourceMapDevToolPlugin({ test: [ /\.js$/, /\.jsx$/ ], exclude: 'vendor', filename: "[name].[hash:5].js.map", append: "//# sourceMappingURL=[url]", moduleFilenameTemplate: '[resource-path]', fallbackModuleFilenameTemplate: '[resource-path]' }), new webpack.optimize.UglifyJsPlugin({ compress: { //supresses warnings, usually from module minification warnings: false }, //sourceMap: true, mangle: true }) ] };
saas-plat/saas-plat-native
web/webpack.config.js
JavaScript
gpl-3.0
3,434
package org.saintandreas.serket.scpd; import java.io.IOException; import javax.servlet.ServletException; import javax.xml.namespace.QName; import javax.xml.soap.SOAPBodyElement; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import org.saintandreas.serket.service.BaseService; import org.saintandreas.util.SOAPSerializable; import org.saintandreas.util.XmlUtil; import org.w3c.dom.Element; public abstract class ConnectionManager2 extends BaseService { public final static String URI = "urn:schemas-upnp-org:service:ConnectionManager:2"; public ConnectionManager2(String id, String controlURL, String eventURL) { super(id, controlURL, eventURL); } public String getURI() { return URI; } public abstract ConnectionManager2 .GetProtocolInfoResponse getProtocolInfo(ConnectionManager2 .GetProtocolInfoRequest input) throws IOException, ServletException ; public abstract ConnectionManager2 .PrepareForConnectionResponse prepareForConnection(ConnectionManager2 .PrepareForConnectionRequest input) throws IOException, ServletException ; public abstract ConnectionManager2 .ConnectionCompleteResponse connectionComplete(ConnectionManager2 .ConnectionCompleteRequest input) throws IOException, ServletException ; public abstract ConnectionManager2 .GetCurrentConnectionIDsResponse getCurrentConnectionIDs(ConnectionManager2 .GetCurrentConnectionIDsRequest input) throws IOException, ServletException ; public abstract ConnectionManager2 .GetCurrentConnectionInfoResponse getCurrentConnectionInfo(ConnectionManager2 .GetCurrentConnectionInfoRequest input) throws IOException, ServletException ; public static class ConnectionCompleteRequest extends SOAPSerializable { public int connectionID; public void parse(SOAPMessage soapMessage) throws SOAPException { for (Element e: XmlUtil.getChildElements(XmlUtil.getChildElements(soapMessage.getSOAPBody()).get(0))) { String name = e.getNodeName(); if ("ConnectionID".equals(name)) { connectionID = Integer.valueOf(e.getTextContent()); continue; } } } public SOAPMessage format() throws SOAPException { SOAPMessage retVal = ConnectionManager2 .ConnectionCompleteRequest.createMessage(); SOAPBodyElement soapBodyElement = retVal.getSOAPBody().addBodyElement(new QName(URI, "ConnectionCompleteRequest", "u")); soapBodyElement.addChildElement("ConnectionID").setTextContent(Integer.toString(connectionID)); return retVal; } } public static class ConnectionCompleteResponse extends SOAPSerializable { public void parse(SOAPMessage soapMessage) { } public SOAPMessage format() throws SOAPException { SOAPMessage retVal = ConnectionManager2 .ConnectionCompleteResponse.createMessage(); retVal.getSOAPBody().addBodyElement(new QName(URI, "ConnectionCompleteResponse", "u")); return retVal; } } public enum ConnectionStatus { OK, ContentFormatMismatch, InsufficientBandwidth, UnreliableChannel, Unknown; } public enum Direction { Input, Output; } public static class GetCurrentConnectionIDsRequest extends SOAPSerializable { public void parse(SOAPMessage soapMessage) { } public SOAPMessage format() throws SOAPException { SOAPMessage retVal = ConnectionManager2 .GetCurrentConnectionIDsRequest.createMessage(); retVal.getSOAPBody().addBodyElement(new QName(URI, "GetCurrentConnectionIDsRequest", "u")); return retVal; } } public static class GetCurrentConnectionIDsResponse extends SOAPSerializable { public String connectionIDs; public void parse(SOAPMessage soapMessage) throws SOAPException { for (Element e: XmlUtil.getChildElements(XmlUtil.getChildElements(soapMessage.getSOAPBody()).get(0))) { String name = e.getNodeName(); if ("ConnectionIDs".equals(name)) { connectionIDs = e.getTextContent(); continue; } } } public SOAPMessage format() throws SOAPException { SOAPMessage retVal = ConnectionManager2 .GetCurrentConnectionIDsResponse.createMessage(); SOAPBodyElement soapBodyElement = retVal.getSOAPBody().addBodyElement(new QName(URI, "GetCurrentConnectionIDsResponse", "u")); soapBodyElement.addChildElement("ConnectionIDs").setTextContent(connectionIDs.toString()); return retVal; } } public static class GetCurrentConnectionInfoRequest extends SOAPSerializable { public int connectionID; public void parse(SOAPMessage soapMessage) throws SOAPException { for (Element e: XmlUtil.getChildElements(XmlUtil.getChildElements(soapMessage.getSOAPBody()).get(0))) { String name = e.getNodeName(); if ("ConnectionID".equals(name)) { connectionID = Integer.valueOf(e.getTextContent()); continue; } } } public SOAPMessage format() throws SOAPException { SOAPMessage retVal = ConnectionManager2 .GetCurrentConnectionInfoRequest.createMessage(); SOAPBodyElement soapBodyElement = retVal.getSOAPBody().addBodyElement(new QName(URI, "GetCurrentConnectionInfoRequest", "u")); soapBodyElement.addChildElement("ConnectionID").setTextContent(Integer.toString(connectionID)); return retVal; } } public static class GetCurrentConnectionInfoResponse extends SOAPSerializable { public int rcsID; public int aVTransportID; public String protocolInfo; public String peerConnectionManager; public int peerConnectionID; public org.saintandreas.serket.scpd.ConnectionManager2.Direction direction; public ConnectionManager2 .ConnectionStatus status; public void parse(SOAPMessage soapMessage) throws SOAPException { for (Element e: XmlUtil.getChildElements(XmlUtil.getChildElements(soapMessage.getSOAPBody()).get(0))) { String name = e.getNodeName(); if ("RcsID".equals(name)) { rcsID = Integer.valueOf(e.getTextContent()); continue; } if ("AVTransportID".equals(name)) { aVTransportID = Integer.valueOf(e.getTextContent()); continue; } if ("ProtocolInfo".equals(name)) { protocolInfo = e.getTextContent(); continue; } if ("PeerConnectionManager".equals(name)) { peerConnectionManager = e.getTextContent(); continue; } if ("PeerConnectionID".equals(name)) { peerConnectionID = Integer.valueOf(e.getTextContent()); continue; } if ("Direction".equals(name)) { direction = org.saintandreas.serket.scpd.ConnectionManager2.Direction.valueOf(e.getTextContent()); continue; } if ("Status".equals(name)) { status = ConnectionManager2 .ConnectionStatus.valueOf(e.getTextContent()); continue; } } } public SOAPMessage format() throws SOAPException { SOAPMessage retVal = ConnectionManager2 .GetCurrentConnectionInfoResponse.createMessage(); SOAPBodyElement soapBodyElement = retVal.getSOAPBody().addBodyElement(new QName(URI, "GetCurrentConnectionInfoResponse", "u")); soapBodyElement.addChildElement("RcsID").setTextContent(Integer.toString(rcsID)); soapBodyElement.addChildElement("AVTransportID").setTextContent(Integer.toString(aVTransportID)); soapBodyElement.addChildElement("ProtocolInfo").setTextContent(protocolInfo.toString()); soapBodyElement.addChildElement("PeerConnectionManager").setTextContent(peerConnectionManager.toString()); soapBodyElement.addChildElement("PeerConnectionID").setTextContent(Integer.toString(peerConnectionID)); soapBodyElement.addChildElement("Direction").setTextContent(direction.toString()); soapBodyElement.addChildElement("Status").setTextContent(status.toString()); return retVal; } } public static class GetProtocolInfoRequest extends SOAPSerializable { public void parse(SOAPMessage soapMessage) { } public SOAPMessage format() throws SOAPException { SOAPMessage retVal = ConnectionManager2 .GetProtocolInfoRequest.createMessage(); retVal.getSOAPBody().addBodyElement(new QName(URI, "GetProtocolInfoRequest", "u")); return retVal; } } public static class GetProtocolInfoResponse extends SOAPSerializable { public String source; public String sink; public void parse(SOAPMessage soapMessage) throws SOAPException { for (Element e: XmlUtil.getChildElements(XmlUtil.getChildElements(soapMessage.getSOAPBody()).get(0))) { String name = e.getNodeName(); if ("Source".equals(name)) { source = e.getTextContent(); continue; } if ("Sink".equals(name)) { sink = e.getTextContent(); continue; } } } public SOAPMessage format() throws SOAPException { SOAPMessage retVal = ConnectionManager2 .GetProtocolInfoResponse.createMessage(); SOAPBodyElement soapBodyElement = retVal.getSOAPBody().addBodyElement(new QName(URI, "GetProtocolInfoResponse", "u")); soapBodyElement.addChildElement("Source").setTextContent(source.toString()); soapBodyElement.addChildElement("Sink").setTextContent(sink.toString()); return retVal; } } public static class PrepareForConnectionRequest extends SOAPSerializable { public String remoteProtocolInfo; public String peerConnectionManager; public int peerConnectionID; public ConnectionManager2 .Direction direction; public void parse(SOAPMessage soapMessage) throws SOAPException { for (Element e: XmlUtil.getChildElements(XmlUtil.getChildElements(soapMessage.getSOAPBody()).get(0))) { String name = e.getNodeName(); if ("RemoteProtocolInfo".equals(name)) { remoteProtocolInfo = e.getTextContent(); continue; } if ("PeerConnectionManager".equals(name)) { peerConnectionManager = e.getTextContent(); continue; } if ("PeerConnectionID".equals(name)) { peerConnectionID = Integer.valueOf(e.getTextContent()); continue; } if ("Direction".equals(name)) { direction = ConnectionManager2 .Direction.valueOf(e.getTextContent()); continue; } } } public SOAPMessage format() throws SOAPException { SOAPMessage retVal = ConnectionManager2 .PrepareForConnectionRequest.createMessage(); SOAPBodyElement soapBodyElement = retVal.getSOAPBody().addBodyElement(new QName(URI, "PrepareForConnectionRequest", "u")); soapBodyElement.addChildElement("RemoteProtocolInfo").setTextContent(remoteProtocolInfo.toString()); soapBodyElement.addChildElement("PeerConnectionManager").setTextContent(peerConnectionManager.toString()); soapBodyElement.addChildElement("PeerConnectionID").setTextContent(Integer.toString(peerConnectionID)); soapBodyElement.addChildElement("Direction").setTextContent(direction.toString()); return retVal; } } public static class PrepareForConnectionResponse extends SOAPSerializable { public int connectionID; public int aVTransportID; public int rcsID; public void parse(SOAPMessage soapMessage) throws SOAPException { for (Element e: XmlUtil.getChildElements(XmlUtil.getChildElements(soapMessage.getSOAPBody()).get(0))) { String name = e.getNodeName(); if ("ConnectionID".equals(name)) { connectionID = Integer.valueOf(e.getTextContent()); continue; } if ("AVTransportID".equals(name)) { aVTransportID = Integer.valueOf(e.getTextContent()); continue; } if ("RcsID".equals(name)) { rcsID = Integer.valueOf(e.getTextContent()); continue; } } } public SOAPMessage format() throws SOAPException { SOAPMessage retVal = ConnectionManager2 .PrepareForConnectionResponse.createMessage(); SOAPBodyElement soapBodyElement = retVal.getSOAPBody().addBodyElement(new QName(URI, "PrepareForConnectionResponse", "u")); soapBodyElement.addChildElement("ConnectionID").setTextContent(Integer.toString(connectionID)); soapBodyElement.addChildElement("AVTransportID").setTextContent(Integer.toString(aVTransportID)); soapBodyElement.addChildElement("RcsID").setTextContent(Integer.toString(rcsID)); return retVal; } } }
jherico/serket
serket-scpd/src/main/java/org/saintandreas/serket/scpd/ConnectionManager2.java
Java
gpl-3.0
14,975
<?php /** *@package pXP *@file gen-MODGrupoEp.php *@author (admin) *@date 22-04-2013 14:49:40 *@description Clase que envia los parametros requeridos a la Base de datos para la ejecucion de las funciones, y que recibe la respuesta del resultado de la ejecucion de las mismas */ class MODGrupoEp extends MODbase{ function __construct(CTParametro $pParam){ parent::__construct($pParam); } function listarGrupoEp(){ //Definicion de variables para ejecucion del procedimientp $this->procedimiento='param.ft_grupo_ep_sel'; $this->transaccion='PM_GQP_SEL'; $this->tipo_procedimiento='SEL';//tipo de transaccion //Definicion de la lista del resultado del query $this->captura('id_grupo_ep','int4'); $this->captura('estado_reg','varchar'); $this->captura('id_grupo','int4'); $this->captura('id_ep','int4'); $this->captura('fecha_reg','timestamp'); $this->captura('id_usuario_reg','int4'); $this->captura('fecha_mod','timestamp'); $this->captura('id_usuario_mod','int4'); $this->captura('usr_reg','varchar'); $this->captura('usr_mod','varchar'); $this->captura('ep','text'); $this->captura('id_uo','int4'); $this->captura('desc_uo','text'); $this->captura('estado_reg_uo','varchar'); //Ejecuta la instruccion $this->armarConsulta(); $this->ejecutarConsulta(); //Devuelve la respuesta return $this->respuesta; } function insertarGrupoEp(){ //Definicion de variables para ejecucion del procedimiento $this->procedimiento='param.ft_grupo_ep_ime'; $this->transaccion='PM_GQP_INS'; $this->tipo_procedimiento='IME'; //Define los parametros para la funcion $this->setParametro('estado_reg','estado_reg','varchar'); $this->setParametro('id_grupo','id_grupo','int4'); $this->setParametro('id_ep','id_ep','int4'); $this->setParametro('id_uo','id_uo','int4'); //Ejecuta la instruccion $this->armarConsulta(); $this->ejecutarConsulta(); //Devuelve la respuesta return $this->respuesta; } function modificarGrupoEp(){ //Definicion de variables para ejecucion del procedimiento $this->procedimiento='param.ft_grupo_ep_ime'; $this->transaccion='PM_GQP_MOD'; $this->tipo_procedimiento='IME'; //Define los parametros para la funcion $this->setParametro('id_grupo_ep','id_grupo_ep','int4'); $this->setParametro('estado_reg','estado_reg','varchar'); $this->setParametro('id_grupo','id_grupo','int4'); $this->setParametro('id_ep','id_ep','int4'); $this->setParametro('id_uo','id_uo','int4'); //Ejecuta la instruccion $this->armarConsulta(); $this->ejecutarConsulta(); //Devuelve la respuesta return $this->respuesta; } function eliminarGrupoEp(){ //Definicion de variables para ejecucion del procedimiento $this->procedimiento='param.ft_grupo_ep_ime'; $this->transaccion='PM_GQP_ELI'; $this->tipo_procedimiento='IME'; //Define los parametros para la funcion $this->setParametro('id_grupo_ep','id_grupo_ep','int4'); //Ejecuta la instruccion $this->armarConsulta(); $this->ejecutarConsulta(); //Devuelve la respuesta return $this->respuesta; } function sincUoEp(){ //Definicion de variables para ejecucion del procedimiento $this->procedimiento='param.ft_grupo_ep_ime'; $this->transaccion='PM_SINCGREPUO_IME'; $this->tipo_procedimiento='IME'; //Define los parametros para la funcion $this->setParametro('config','config','varchar'); $this->setParametro('id_grupo','id_grupo','int4'); //Ejecuta la instruccion $this->armarConsulta(); $this->ejecutarConsulta(); //Devuelve la respuesta return $this->respuesta; } } ?>
boabo/pxp
sis_parametros/modelo/MODGrupoEp.php
PHP
gpl-3.0
3,739
<?php /** * Translation Manager for Android Apps * * PHP version 7 * * @category PHP * @package TranslationManagerForAndroidApps * @author Andrej Sinicyn <rarogit@gmail.com> * @copyright 2017 Andrej Sinicyn * @license https://www.gnu.org/licenses/gpl-3.0.html GNU General Public License version 3 or later * @link https://github.com/rarog/TranslationManagerForAndroidApps */ /** * List of enabled modules for this application. * * This should be an array of module namespaces used in the application. */ return [ 'Zend\Navigation', 'Zend\Mvc\Plugin\FlashMessenger', 'Zend\Mvc\Plugin\Prg', 'Zend\Serializer', 'Zend\InputFilter', 'Zend\Filter', 'Zend\Hydrator', 'Zend\I18n', 'Zend\Session', 'Zend\Mvc\I18n', 'Zend\Log', 'Zend\Form', 'Zend\Db', 'Zend\Cache', 'Zend\Router', 'Zend\Validator', 'ConfigHelper', 'TwbBundle', 'ZfcUser', 'Setup', 'Common', 'Translations', 'Application', 'ZfcRbac', 'UserRbac', ];
rarog/TranslationManagerForAndroidApps
config/modules.config.php
PHP
gpl-3.0
1,034
// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*- /* * FinderPatternFinder.cpp * zxing * * Created by Christian Brunschen on 13/05/2008. * Copyright 2008 ZXing authors All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <algorithm> #include <zxing/qrcode/detector/FinderPatternFinder.h> #include <zxing/ReaderException.h> #include <zxing/DecodeHints.h> #include <cstring> using std::sort; using std::max; using std::abs; using std::vector; using zxing::Ref; using zxing::qrcode::FinderPatternFinder; using zxing::qrcode::FinderPattern; using zxing::qrcode::FinderPatternInfo; // VC++ using zxing::BitMatrix; using zxing::ResultPointCallback; using zxing::ResultPoint; using zxing::DecodeHints; namespace { class FurthestFromAverageComparator { private: const float averageModuleSize_; public: FurthestFromAverageComparator(float averageModuleSize) : averageModuleSize_(averageModuleSize) { } bool operator()(Ref<FinderPattern> a, Ref<FinderPattern> b) { float dA = abs(a->getEstimatedModuleSize() - averageModuleSize_); float dB = abs(b->getEstimatedModuleSize() - averageModuleSize_); return dA > dB; } }; class CenterComparator { const float averageModuleSize_; public: CenterComparator(float averageModuleSize) : averageModuleSize_(averageModuleSize) { } bool operator()(Ref<FinderPattern> a, Ref<FinderPattern> b) { // N.B.: we want the result in descending order ... if (a->getCount() != b->getCount()) { return a->getCount() > b->getCount(); } else { float dA = abs(a->getEstimatedModuleSize() - averageModuleSize_); float dB = abs(b->getEstimatedModuleSize() - averageModuleSize_); return dA < dB; } } }; } int FinderPatternFinder::CENTER_QUORUM = 2; int FinderPatternFinder::MIN_SKIP = 3; int FinderPatternFinder::MAX_MODULES = 57; float FinderPatternFinder::centerFromEnd(int* stateCount, int end) { return (float)(end - stateCount[4] - stateCount[3]) - stateCount[2] / 2.0f; } bool FinderPatternFinder::foundPatternCross(int* stateCount) { int totalModuleSize = 0; for (int i = 0; i < 5; i++) { if (stateCount[i] == 0) { return false; } totalModuleSize += stateCount[i]; } if (totalModuleSize < 7) { return false; } float moduleSize = (float)totalModuleSize / 7.0f; float maxVariance = moduleSize / 2.0f; // Allow less than 50% variance from 1-1-3-1-1 proportions return abs(moduleSize - stateCount[0]) < maxVariance && abs(moduleSize - stateCount[1]) < maxVariance && abs(3.0f * moduleSize - stateCount[2]) < 3.0f * maxVariance && abs(moduleSize - stateCount[3]) < maxVariance && abs( moduleSize - stateCount[4]) < maxVariance; } float FinderPatternFinder::crossCheckVertical(size_t startI, size_t centerJ, int maxCount, int originalStateCountTotal) { int maxI = image_->getHeight(); int stateCount[5] = {0}; // for (int i = 0; i < 5; i++) // stateCount[i] = 0; // Start counting up from center int i = startI; while (i >= 0 && image_->get(centerJ, i)) { stateCount[2]++; i--; } if (i < 0) { return nan(); } while (i >= 0 && !image_->get(centerJ, i) && stateCount[1] <= maxCount) { stateCount[1]++; i--; } // If already too many modules in this state or ran off the edge: if (i < 0 || stateCount[1] > maxCount) { return nan(); } while (i >= 0 && image_->get(centerJ, i) && stateCount[0] <= maxCount) { stateCount[0]++; i--; } if (stateCount[0] > maxCount) { return nan(); } // Now also count down from center i = startI + 1; while (i < maxI && image_->get(centerJ, i)) { stateCount[2]++; i++; } if (i == maxI) { return nan(); } while (i < maxI && !image_->get(centerJ, i) && stateCount[3] < maxCount) { stateCount[3]++; i++; } if (i == maxI || stateCount[3] >= maxCount) { return nan(); } while (i < maxI && image_->get(centerJ, i) && stateCount[4] < maxCount) { stateCount[4]++; i++; } if (stateCount[4] >= maxCount) { return nan(); } // If we found a finder-pattern-like section, but its size is more than 40% different than // the original, assume it's a false positive int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4]; if (5 * abs(stateCountTotal - originalStateCountTotal) >= 2 * originalStateCountTotal) { return nan(); } return foundPatternCross(stateCount) ? centerFromEnd(stateCount, i) : nan(); } float FinderPatternFinder::crossCheckHorizontal(size_t startJ, size_t centerI, int maxCount, int originalStateCountTotal) { int maxJ = image_->getWidth(); int stateCount[5] = {0}; // for (int i = 0; i < 5; i++) // stateCount[i] = 0; int j = startJ; while (j >= 0 && image_->get(j, centerI)) { stateCount[2]++; j--; } if (j < 0) { return nan(); } while (j >= 0 && !image_->get(j, centerI) && stateCount[1] <= maxCount) { stateCount[1]++; j--; } if (j < 0 || stateCount[1] > maxCount) { return nan(); } while (j >= 0 && image_->get(j, centerI) && stateCount[0] <= maxCount) { stateCount[0]++; j--; } if (stateCount[0] > maxCount) { return nan(); } j = startJ + 1; while (j < maxJ && image_->get(j, centerI)) { stateCount[2]++; j++; } if (j == maxJ) { return nan(); } while (j < maxJ && !image_->get(j, centerI) && stateCount[3] < maxCount) { stateCount[3]++; j++; } if (j == maxJ || stateCount[3] >= maxCount) { return nan(); } while (j < maxJ && image_->get(j, centerI) && stateCount[4] < maxCount) { stateCount[4]++; j++; } if (stateCount[4] >= maxCount) { return nan(); } // If we found a finder-pattern-like section, but its size is significantly different than // the original, assume it's a false positive int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4]; if (5 * abs(stateCountTotal - originalStateCountTotal) >= originalStateCountTotal) { return nan(); } return foundPatternCross(stateCount) ? centerFromEnd(stateCount, j) : nan(); } bool FinderPatternFinder::handlePossibleCenter(int* stateCount, size_t i, size_t j) { int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4]; float centerJ = centerFromEnd(stateCount, j); float centerI = crossCheckVertical(i, (size_t)centerJ, stateCount[2], stateCountTotal); if (!isnan_z(centerI)) { // Re-cross check centerJ = crossCheckHorizontal((size_t)centerJ, (size_t)centerI, stateCount[2], stateCountTotal); if (!isnan_z(centerJ) && crossCheckDiagonal((int)centerI, (int)centerJ, stateCount[2], stateCountTotal)) { float estimatedModuleSize = (float)stateCountTotal / 7.0f; bool found = false; size_t max = possibleCenters_.size(); for (size_t index = 0; index < max; index++) { Ref<FinderPattern> center = possibleCenters_[index]; // Look for about the same center and module size: if (center->aboutEquals(estimatedModuleSize, centerI, centerJ)) { possibleCenters_[index] = center->combineEstimate(centerI, centerJ, estimatedModuleSize); found = true; break; } } if (!found) { Ref<FinderPattern> newPattern(new FinderPattern(centerJ, centerI, estimatedModuleSize)); possibleCenters_.push_back(newPattern); if (callback_ != 0) { callback_->foundPossibleResultPoint(*newPattern); } } return true; } } return false; } int FinderPatternFinder::findRowSkip() { size_t max = possibleCenters_.size(); if (max <= 1) { return 0; } Ref<FinderPattern> firstConfirmedCenter; for (size_t i = 0; i < max; i++) { Ref<FinderPattern> center = possibleCenters_[i]; if (center->getCount() >= CENTER_QUORUM) { if (firstConfirmedCenter == 0) { firstConfirmedCenter = center; } else { // We have two confirmed centers // How far down can we skip before resuming looking for the next // pattern? In the worst case, only the difference between the // difference in the x / y coordinates of the two centers. // This is the case where you find top left first. Draw it out. hasSkipped_ = true; return (int)(abs(firstConfirmedCenter->getX() - center->getX()) - abs(firstConfirmedCenter->getY() - center->getY()))/2; } } } return 0; } bool FinderPatternFinder::haveMultiplyConfirmedCenters() { int confirmedCount = 0; float totalModuleSize = 0.0f; size_t max = possibleCenters_.size(); for (size_t i = 0; i < max; i++) { Ref<FinderPattern> pattern = possibleCenters_[i]; if (pattern->getCount() >= CENTER_QUORUM) { confirmedCount++; totalModuleSize += pattern->getEstimatedModuleSize(); } } if (confirmedCount < 3) { return false; } // OK, we have at least 3 confirmed centers, but, it's possible that one is a "false positive" // and that we need to keep looking. We detect this by asking if the estimated module sizes // vary too much. We arbitrarily say that when the total deviation from average exceeds // 5% of the total module size estimates, it's too much. float average = totalModuleSize / max; float totalDeviation = 0.0f; for (size_t i = 0; i < max; i++) { Ref<FinderPattern> pattern = possibleCenters_[i]; totalDeviation += abs(pattern->getEstimatedModuleSize() - average); } return totalDeviation <= 0.05f * totalModuleSize; } vector< Ref<FinderPattern> > FinderPatternFinder::selectBestPatterns() { size_t startSize = possibleCenters_.size(); if (startSize < 3) { // Couldn't find enough finder patterns throw zxing::ReaderException("Could not find three finder patterns"); } // Filter outlier possibilities whose module size is too different if (startSize > 3) { // But we can only afford to do so if we have at least 4 possibilities to choose from float totalModuleSize = 0.0f; float square = 0.0f; for (size_t i = 0; i < startSize; i++) { float size = possibleCenters_[i]->getEstimatedModuleSize(); totalModuleSize += size; square += size * size; } float average = totalModuleSize / (float) startSize; float stdDev = (float)sqrt(square / startSize - average * average); sort(possibleCenters_.begin(), possibleCenters_.end(), FurthestFromAverageComparator(average)); float limit = max(0.2f * average, stdDev); for (size_t i = 0; i < possibleCenters_.size() && possibleCenters_.size() > 3; i++) { if (abs(possibleCenters_[i]->getEstimatedModuleSize() - average) > limit) { possibleCenters_.erase(possibleCenters_.begin()+i); i--; } } } if ( possibleCenters_.size() > 3) { // Throw away all but those first size candidate points we found. float totalModuleSize = 0.0f; for (size_t i = 0; i < possibleCenters_.size(); i++) { float size = possibleCenters_[i]->getEstimatedModuleSize(); totalModuleSize += size; } float average = totalModuleSize / (float) possibleCenters_.size(); sort(possibleCenters_.begin(), possibleCenters_.end(), CenterComparator(average)); } vector<Ref<FinderPattern> > result(3); possibleCenters_.erase(possibleCenters_.begin()+3,possibleCenters_.end()); result[0] = possibleCenters_[0]; result[1] = possibleCenters_[1]; result[2] = possibleCenters_[2]; return result; } vector<Ref<FinderPattern> > FinderPatternFinder::orderBestPatterns(vector<Ref<FinderPattern> > patterns) { // Find distances between pattern centers float abDistance = distance(patterns[0], patterns[1]); float bcDistance = distance(patterns[1], patterns[2]); float acDistance = distance(patterns[0], patterns[2]); Ref<FinderPattern> topLeft; Ref<FinderPattern> topRight; Ref<FinderPattern> bottomLeft; // Assume one closest to other two is top left; // topRight and bottomLeft will just be guesses below at first if (bcDistance >= abDistance && bcDistance >= acDistance) { topLeft = patterns[0]; topRight = patterns[1]; bottomLeft = patterns[2]; } else if (acDistance >= bcDistance && acDistance >= abDistance) { topLeft = patterns[1]; topRight = patterns[0]; bottomLeft = patterns[2]; } else { topLeft = patterns[2]; topRight = patterns[0]; bottomLeft = patterns[1]; } // Use cross product to figure out which of other1/2 is the bottom left // pattern. The vector "top-left -> bottom-left" x "top-left -> top-right" // should yield a vector with positive z component if ((bottomLeft->getY() - topLeft->getY()) * (topRight->getX() - topLeft->getX()) < (bottomLeft->getX() - topLeft->getX()) * (topRight->getY() - topLeft->getY())) { Ref<FinderPattern> temp = topRight; topRight = bottomLeft; bottomLeft = temp; } vector<Ref<FinderPattern> > results(3); results[0] = bottomLeft; results[1] = topLeft; results[2] = topRight; return results; } float FinderPatternFinder::distance(Ref<ResultPoint> p1, Ref<ResultPoint> p2) { float dx = p1->getX() - p2->getX(); float dy = p1->getY() - p2->getY(); return (float)sqrt(dx * dx + dy * dy); } FinderPatternFinder::FinderPatternFinder(Ref<BitMatrix> image, Ref<ResultPointCallback>const& callback) : image_(image), possibleCenters_(), hasSkipped_(false), callback_(callback) { } Ref<FinderPatternInfo> FinderPatternFinder::find(DecodeHints const& hints) { bool tryHarder = hints.getTryHarder(); size_t maxI = image_->getHeight(); size_t maxJ = image_->getWidth(); // We are looking for black/white/black/white/black modules in // 1:1:3:1:1 ratio; this tracks the number of such modules seen so far // As this is used often, we use an integer array instead of vector int stateCount[5]; bool done = false; // Let's assume that the maximum version QR Code we support takes up 1/4 // the height of the image, and then account for the center being 3 // modules in size. This gives the smallest number of pixels the center // could be, so skip this often. When trying harder, look for all // QR versions regardless of how dense they are. int iSkip = (3 * maxI) / (4 * MAX_MODULES); if (iSkip < MIN_SKIP || tryHarder) { iSkip = MIN_SKIP; } // This is slightly faster than using the Ref. Efficiency is important here BitMatrix& matrix = *image_; for (size_t i = iSkip - 1; i < maxI && !done; i += iSkip) { // Get a row of black/white values memset(stateCount, 0, sizeof(stateCount)); int currentState = 0; for (size_t j = 0; j < maxJ; j++) { if (matrix.get(j, i)) { // Black pixel if ((currentState & 1) == 1) { // Counting white pixels currentState++; } stateCount[currentState]++; } else { // White pixel if ((currentState & 1) == 0) { // Counting black pixels if (currentState == 4) { // A winner? if (foundPatternCross(stateCount)) { // Yes bool confirmed = handlePossibleCenter(stateCount, i, j); if (confirmed) { // Start examining every other line. Checking each line turned out to be too // expensive and didn't improve performance. iSkip = 2; if (hasSkipped_) { done = haveMultiplyConfirmedCenters(); } else { int rowSkip = findRowSkip(); if (rowSkip > stateCount[2]) { // Skip rows between row of lower confirmed center // and top of presumed third confirmed center // but back up a bit to get a full chance of detecting // it, entire width of center of finder pattern // Skip by rowSkip, but back off by stateCount[2] (size // of last center of pattern we saw) to be conservative, // and also back off by iSkip which is about to be // re-added i += rowSkip - stateCount[2] - iSkip; j = maxJ - 1; } } } else { stateCount[0] = stateCount[2]; stateCount[1] = stateCount[3]; stateCount[2] = stateCount[4]; stateCount[3] = 1; stateCount[4] = 0; currentState = 3; continue; } // Clear state to start looking again currentState = 0; memset(stateCount, 0, sizeof(stateCount)); } else { // No, shift counts back by two stateCount[0] = stateCount[2]; stateCount[1] = stateCount[3]; stateCount[2] = stateCount[4]; stateCount[3] = 1; stateCount[4] = 0; currentState = 3; } } else { stateCount[++currentState]++; } } else { // Counting white pixels stateCount[currentState]++; } } } if (foundPatternCross(stateCount)) { bool confirmed = handlePossibleCenter(stateCount, i, maxJ); if (confirmed) { iSkip = stateCount[0]; if (hasSkipped_) { // Found a third one done = haveMultiplyConfirmedCenters(); } } } } vector<Ref<FinderPattern> > patternInfo = selectBestPatterns(); patternInfo = orderBestPatterns(patternInfo); Ref<FinderPatternInfo> result(new FinderPatternInfo(patternInfo)); return result; } Ref<BitMatrix> FinderPatternFinder::getImage() { return image_; } vector<Ref<FinderPattern> >& FinderPatternFinder::getPossibleCenters() { return possibleCenters_; } bool FinderPatternFinder::crossCheckDiagonal(int startI, int centerJ, int maxCount, int originalStateCountTotal) const { int *stateCount = getCrossCheckStateCount(); // Start counting up, left from center finding black center mass int i = 0; while (startI >= i && centerJ >= i && image_->get(centerJ - i, startI - i)) { stateCount[2]++; i++; } if (startI < i || centerJ < i) { return false; } // Continue up, left finding white space while (startI >= i && centerJ >= i && !image_->get(centerJ - i, startI - i) && stateCount[1] <= maxCount) { stateCount[1]++; i++; } // If already too many modules in this state or ran off the edge: if (startI < i || centerJ < i || stateCount[1] > maxCount) { return false; } // Continue up, left finding black border while (startI >= i && centerJ >= i && image_->get(centerJ - i, startI - i) && stateCount[0] <= maxCount) { stateCount[0]++; i++; } if (stateCount[0] > maxCount) { return false; } int maxI = image_->getHeight(); int maxJ = image_->getWidth(); // Now also count down, right from center i = 1; while (startI + i < maxI && centerJ + i < maxJ && image_->get(centerJ + i, startI + i)) { stateCount[2]++; i++; } // Ran off the edge? if (startI + i >= maxI || centerJ + i >= maxJ) { return false; } while (startI + i < maxI && centerJ + i < maxJ && !image_->get(centerJ + i, startI + i) && stateCount[3] < maxCount) { stateCount[3]++; i++; } if (startI + i >= maxI || centerJ + i >= maxJ || stateCount[3] >= maxCount) { return false; } while (startI + i < maxI && centerJ + i < maxJ && image_->get(centerJ + i, startI + i) && stateCount[4] < maxCount) { stateCount[4]++; i++; } if (stateCount[4] >= maxCount) { return false; } // If we found a finder-pattern-like section, but its size is more than 100% different than // the original, assume it's a false positive int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4]; return abs(stateCountTotal - originalStateCountTotal) < 2 * originalStateCountTotal && foundPatternCross(stateCount); } int *FinderPatternFinder::getCrossCheckStateCount() const { memset(crossCheckStateCount, 0, sizeof(crossCheckStateCount)); return crossCheckStateCount; }
fogelton/fraqtive
qzxing/zxing/zxing/qrcode/detector/QRFinderPatternFinder.cpp
C++
gpl-3.0
23,368
int lire_driver (char *nom); int select_driver (void);
DrCoolzic/BIG2
BIG2_DOC/SRCS/BDOC_IMP.H
C++
gpl-3.0
55
<?php /** * General Debugger-Class, implementing a FirePHP-Debugger, * for usage see http://www.firephp.org/HQ/Use.htm * * Usage for Classees implementing Config.php: * if ($this->debugger) $this->debugger->log($data, "Label"); * * @package moosique.net * @author Steffen Becker */ class Debugger { private $fb; // instance of the FirePHP-Class /** * Initializes the Debugger by inlcuding and instanciating FirePHP * * @author Steffen Becker */ function __construct() { require_once('FirePHP.class.php'); $this->fb = FirePHP::getInstance(true); } /** * Logs an Object using FirePHP * * @param mixed $var Any object, array, string etc. to log * @param string $label The label for the object to log * @author Steffen Becker */ public function log($var, $label = '') { $this->fb->log($var, $label); } } ?>
daftano/dl-learner
moosique.net/moosique/classes/Debugger.php
PHP
gpl-3.0
892
## import argparse from plotWheels.helical_wheel import helical_wheel if __name__ == "__main__": parser = argparse.ArgumentParser(description="Generate Helical Wheel") parser.add_argument("--sequence",dest="sequence",type=str) parser.add_argument("--seqRange",dest="seqRange",type=int,default=1) parser.add_argument("--t_size",dest="t_size",type=int,default=32) parser.add_argument("--rotation",dest="rotation",type=int,default=90) parser.add_argument("--numbering",action="store_true",help="numbering for helical wheel") parser.add_argument("--output",dest="output",type=argparse.FileType("wb"), default="_helicalwheel.png")#dest="output",default="_helicalwheel.png") #### circle colors parser.add_argument("--f_A",dest="f_A", default="#ffcc33") parser.add_argument("--f_C",dest="f_C",default="#b5b5b5") parser.add_argument("--f_D",dest="f_D",default="#db270f") parser.add_argument("--f_E",dest="f_E",default="#db270f") parser.add_argument("--f_F",dest="f_F",default="#ffcc33") parser.add_argument("--f_G",dest="f_G",default="#b5b5b5") parser.add_argument("--f_H",dest="f_H",default="#12d5fc") parser.add_argument("--f_I",dest="f_I",default="#ffcc33") parser.add_argument("--f_K",dest="f_K",default="#12d5fc") parser.add_argument("--f_L",dest="f_L",default="#ffcc33") parser.add_argument("--f_M",dest="f_M",default="#ffcc33") parser.add_argument("--f_N",dest="f_N",default="#b5b5b5") parser.add_argument("--f_P",dest="f_P",default="#ffcc33") parser.add_argument("--f_Q",dest="f_Q",default="#b5b5b5") parser.add_argument("--f_R",dest="f_R",default="#12d5fc") parser.add_argument("--f_S",dest="f_S",default="#b5b5b5") parser.add_argument("--f_T",dest="f_T",default="#b5b5b5") parser.add_argument("--f_V",dest="f_V",default="#ffcc33") parser.add_argument("--f_W",dest="f_W",default="#ffcc33") parser.add_argument("--f_Y",dest="f_Y",default="#b5b5b5") ### text colors parser.add_argument("--t_A",dest="t_A",default="k") parser.add_argument("--t_C",dest="t_C",default="k") parser.add_argument("--t_D",dest="t_D",default="w") parser.add_argument("--t_E",dest="t_E",default="w") parser.add_argument("--t_F",dest="t_F",default="k") parser.add_argument("--t_G",dest="t_G",default="k") parser.add_argument("--t_H",dest="t_H",default="k") parser.add_argument("--t_I",dest="t_I",default="k") parser.add_argument("--t_K",dest="t_K",default="k") parser.add_argument("--t_L",dest="t_L",default="k") parser.add_argument("--t_M",dest="t_M",default="k") parser.add_argument("--t_N",dest="t_N",default="k") parser.add_argument("--t_P",dest="t_P",default="k") parser.add_argument("--t_Q",dest="t_Q",default="k") parser.add_argument("--t_R",dest="t_R",default="k") parser.add_argument("--t_S",dest="t_S",default="k") parser.add_argument("--t_T",dest="t_T",default="k") parser.add_argument("--t_V",dest="t_V",default="k") parser.add_argument("--t_W",dest="t_W",default="k") parser.add_argument("--t_Y",dest="t_Y",default="k") args = parser.parse_args() #print(type(args.output)) f_colors = [args.f_A,args.f_C,args.f_D,args.f_E,args.f_F,args.f_G,args.f_H,args.f_I,args.f_K, args.f_L,args.f_M,args.f_N,args.f_P,args.f_Q,args.f_R,args.f_S,args.f_T,args.f_V, args.f_W,args.f_Y] t_colors = [args.t_A,args.t_C,args.t_D,args.t_E,args.t_F,args.t_G,args.t_H,args.t_I,args.t_K, args.t_L,args.t_M,args.t_N,args.t_P,args.t_Q,args.t_R,args.t_S,args.t_T,args.t_V, args.t_W,args.t_Y] colors = [f_colors, t_colors] tmp_file = "./tmp.png" helical_wheel(sequence=args.sequence, colorcoding=colors[0], text_color=colors[1], seqRange=args.seqRange, t_size=args.t_size, rot=args.rotation, numbering=args.numbering, filename=tmp_file ) with open("tmp.png", "rb") as f: for line in f: args.output.write(line)
TAMU-CPT/galaxy-tools
tools/helicalWheel/generateHelicalWheel.py
Python
gpl-3.0
4,144
# SKIP(Social Knowledge & Innovation Platform) # Copyright (C) 2008-2010 TIS Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. require File.dirname(__FILE__) + '/../spec_helper' describe User, '#groups' do before do @user = create_user @group = create_group group_participation = GroupParticipation.create!(:user_id => @user.id, :group_id => @group.id) end it '一件のグループが取得できること' do @user.groups.size.should == 1 end describe 'グループを論理削除された場合' do before do @group.logical_destroy end it 'グループが取得できないこと' do @user.groups.size.should == 0 end end end describe User," is a_user" do fixtures :users, :user_accesses, :user_uids before(:each) do @user = users(:a_user) end it "get uid and name by to_s" do @user.to_s.should == "uid:#{@user.uid}, name:#{@user.name}" end it "get symbol_id" do @user.symbol_id.should == "a_user" end it "get symbol" do @user.symbol.should == "uid:a_user" end it "get before_access" do @user.before_access.should == "Within 1 day" end it "set mark_track" do lambda { @user.mark_track(users(:a_group_joined_user).id) }.should change(Track, :count).by(1) end end describe User, 'validation' do describe 'email' do before do @user = new_user(:email => 'skip@example.org') @user.save! end it 'ユニークであること' do new_user(:email => 'skip@example.org').valid?.should be_false # 大文字小文字が異なる場合もNG new_user(:email => 'Skip@example.org').valid?.should be_false end it 'ドメイン名に大文字を含むアドレスを許容すること' do new_user(:email => 'foo@Example.org').valid?.should be_true end it 'アカウント名とドメイン名に大文字を含むアドレスを許容すること' do new_user(:email => 'Foo@Example.org').valid?.should be_true end end describe 'pssword' do before do @user = create_user @user.stub!(:password_required?).and_return(true) end it '必須であること' do @user.password = '' @user.valid?.should be_false @user.errors['password'].include?('Password can\'t be blank').should be_true end it '確認用パスワードと一致すること' do @user.password = 'valid_password' @user.password_confirmation = 'invalid_password' @user.valid?.should be_false @user.errors['password'].include?('Password doesn\'t match confirmation').should be_true end it '6文字以上であること' do @user.password = 'abcd' @user.valid?.should be_false @user.errors['password'].include?('Password is too short (minimum is 6 characters)').should be_true end it '40文字以内であること' do @user.password = SkipFaker.rand_char(41) @user.valid?.should be_false @user.errors['password'].include?('Password is too long (maximum is 40 characters)').should be_true end it 'ログインIDと異なること' do @user.stub!(:uid).and_return('yamada') @user.password = 'yamada' @user.valid?.should be_false @user.errors['password'].should be_include('shall not be the same with login ID.') end it '現在のパスワードと異なること' do @user.password = 'Password2' @user.password_confirmation = 'Password2' @user.save! @user.password = 'Password2' @user.valid?.should be_false @user.errors['password'].should be_include('shall not be the same with the previous one.') end describe 'パスワード強度が弱の場合' do before do Admin::Setting.stub!(:password_strength).and_return('low') end it '6文字以上の英数字記号であること' do @user.password = 'abcde' @user.password_confirmation = 'abcde' @user.valid? [@user.errors['password']].flatten.size.should == 2 @user.password = 'abcdef' @user.password_confirmation = 'abcdef' @user.valid? @user.errors['password'].should be_nil end end describe 'パスワード強度が中の場合' do before do Admin::Setting.stub!(:password_strength).and_return('middle') end it '7文字の場合エラー' do @user.password = 'abcdeF0' @user.valid? [@user.errors['password']].flatten.size.should == 1 end describe '8文字以上の場合' do it '小文字のみの場合エラー' do @user.password = 'abcdefgh' @user.valid? [@user.errors['password']].flatten.size.should == 1 end it '大文字のみの場合エラー' do @user.password = 'ABCDEFGH' @user.valid? [@user.errors['password']].flatten.size.should == 1 end it '数字のみの場合エラー' do @user.password = '12345678' @user.valid? [@user.errors['password']].flatten.size.should == 1 end it '記号のみの場合エラー' do @user.password = '####&&&&' @user.valid? [@user.errors['password']].flatten.size.should == 1 end it '小文字、大文字のみの場合エラー' do @user.password = 'abcdEFGH' @user.valid? [@user.errors['password']].flatten.size.should == 1 end it '小文字、大文字、数字の場合エラーにならないこと' do @user.password = 'abcdEF012' @user.password_confirmation = 'abcdEF012' @user.valid? @user.errors['password'].should be_nil end end end describe 'パスワード強度が強の場合' do before do Admin::Setting.stub!(:password_strength).and_return('high') end it '7文字の場合エラー' do @user.password = 'abcdeF0' @user.valid? [@user.errors['password']].flatten.size.should == 1 end describe '8文字以上の場合' do it '小文字のみの場合エラー' do @user.password = 'abcdefgh' @user.valid? [@user.errors['password']].flatten.size.should == 1 end it '大文字のみの場合エラー' do @user.password = 'ABCDEFGH' @user.valid? [@user.errors['password']].flatten.size.should == 1 end it '数字のみの場合エラー' do @user.password = '12345678' @user.valid? [@user.errors['password']].flatten.size.should == 1 end it '記号のみの場合エラー' do @user.password = '####&&&&' @user.valid? [@user.errors['password']].flatten.size.should == 1 end it '小文字、大文字のみの場合エラー' do @user.password = 'abcdEFGH' @user.valid? [@user.errors['password']].flatten.size.should == 1 end it '小文字、大文字、数字の場合エラー' do @user.password = 'abcdEF01' @user.valid? [@user.errors['password']].flatten.size.should == 1 end it '小文字、大文字、数字, 記号の場合エラーとならないこと' do @user.password = 'abcdeF0@#' @user.password_confirmation = 'abcdeF0@#' @user.errors['password'].should be_nil end end end end end describe User, "#before_save" do before do SkipEmbedded::InitialSettings['login_mode'] = 'password' SkipEmbedded::InitialSettings['sha1_digest_key'] = "digest_key" end describe '新規の場合' do before do @user = new_user Admin::Setting.password_change_interval = 90 end it 'パスワードが保存されること' do lambda do @user.save end.should change(@user, :crypted_password).from(nil) end it 'パスワード有効期限が設定されること' do time = Time.now Time.stub!(:now).and_return(time) lambda do @user.save end.should change(@user, :password_expires_at).to(Time.now.since(90.day)) end end describe '更新の場合' do before do @user = new_user @user.save @user.reset_auth_token = 'reset_auth_token' @user.reset_auth_token_expires_at = Time.now @user.locked = true @user.trial_num = 1 @user.save Admin::Setting.password_change_interval = 90 end describe 'パスワードの変更の場合' do before do @user.password = 'Password99' @user.password_confirmation = 'Password99' end it 'パスワードが保存される' do lambda do @user.save end.should change(@user, :crypted_password).from(nil) end it 'パスワード有効期限が設定される' do time = Time.now Time.stub!(:now).and_return(time) lambda do @user.save end.should change(@user, :password_expires_at).to(Time.now.since(90.day)) end it 'reset_auth_tokenがクリアされること' do lambda do @user.save end.should change(@user, :reset_auth_token).to(nil) end it 'reset_auth_token_expires_atがクリアされること' do lambda do @user.save end.should change(@user, :reset_auth_token_expires_at).to(nil) end it 'lockedがクリアされること' do lambda do @user.save end.should change(@user, :locked).to(false) end it 'trial_numがクリアされること' do lambda do @user.save end.should change(@user, :trial_num).to(0) end end describe 'パスワード以外の変更の場合' do before do @user.name = 'fuga' end it 'パスワードは変更されないこと' do lambda do @user.save end.should_not change(@user, :crypted_password) end it 'パスワード有効期限は設定されないこと' do lambda do @user.save end.should_not change(@user, :password_expires_at) end it 'reset_auth_tokenが変わらないこと' do lambda do @user.save end.should_not change(@user, :reset_auth_token) end it 'reset_auth_token_expires_atが変わらないこと' do lambda do @user.save end.should_not change(@user, :reset_auth_token_expires_at) end it 'lockedが変わらないこと' do lambda do @user.save end.should_not change(@user, :locked) end it 'trial_numが変わらないこと' do lambda do @user.save end.should_not change(@user, :trial_num) end end end describe 'ロックする場合' do before do @user = create_user(:user_options => { :auth_session_token => 'auth_session_token', :remember_token => 'remember_token', :remember_token_expires_at => Time.now }) @user.locked = true end it 'セッション認証用のtokenが破棄されること' do lambda do @user.save end.should change(@user, :auth_session_token).to(nil) end it 'クッキー認証用のtokenが破棄されること' do lambda do @user.save end.should change(@user, :remember_token).to(nil) end it 'クッキー認証用のtokenの有効期限が破棄されること' do lambda do @user.save end.should change(@user, :remember_token_expires_at).to(nil) end end describe 'ロック状態が変化しない場合' do before do @user = create_user(:user_options => { :auth_session_token => 'auth_session_token', :remember_token => 'remember_token', :remember_token_expires_at => Time.now }) end it 'セッション認証用のtokenが破棄されないこと' do lambda do @user.save end.should_not change(@user, :auth_session_token) end it 'クッキー認証用のtokenが破棄されないこと' do lambda do @user.save end.should_not change(@user, :remember_token) end it 'クッキー認証用のtokenの有効期限が破棄されないこと' do lambda do @user.save end.should_not change(@user, :remember_token_expires_at) end end end describe User, '#before_create' do before do @user = new_user end it '新規作成の際にはissued_atに現在日時が設定される' do time = Time.now Time.stub!(:now).and_return(time) lambda do @user.save end.should change(@user, :issued_at).to(nil) end end describe User, '#after_save' do describe '退職になったユーザの場合' do before do @user = create_user do |u| u.user_oauth_accesses.create(:app_name => 'wiki', :token => 'token', :secret => 'secret') end end it '対象ユーザのOAuthアクセストークンが削除されること' do lambda do @user.status = 'RETIRED' @user.save end.should change(@user.user_oauth_accesses, :size).by(-1) end end describe '利用中のユーザの場合' do before do @user = create_user do |u| u.user_oauth_accesses.create(:app_name => 'wiki', :token => 'token', :secret => 'secret') end end it '対象ユーザのOAuthアクセストークンが変化しないこと' do lambda do @user.name = 'new_name' @user.save end.should_not change(@user.user_oauth_accesses, :size) end end end describe User, '#change_password' do before do SkipEmbedded::InitialSettings['login_mode'] = 'password' SkipEmbedded::InitialSettings['sha1_digest_key'] = 'digest_key' @user = create_user(:user_options => {:password => 'Password1'}) @old_password = 'Password1' @new_password = 'Hogehoge1' @params = { :old_password => @old_password, :password => @new_password, :password_confirmation => @new_password } end describe "前のパスワードが正しい場合" do describe '新しいパスワードが入力されている場合' do it 'パスワードが変更されること' do lambda do @user.change_password @params end.should change(@user, :crypted_password) end end describe '新しいパスワードが入力されていない場合' do before do @params[:password] = '' @user.change_password @params end it { @user.errors.full_messages.size.should == 1 } end end describe "前のパスワードが間違っている場合" do before do @params[:old_password] = 'fugafuga' @user.change_password @params end it { @user.errors.full_messages.size.should == 1 } end end describe User, ".new_with_identity_url" do before do @identity_url = "http://test.com/identity" @params = { :code => 'hoge', :name => "ほげ ふが", :email => 'hoge@hoge.com' } @user = User.new_with_identity_url(@identity_url, @params) @user.stub!(:password_required?).and_return(false) end describe "正しく保存される場合" do it { @user.should be_valid } it { @user.should be_is_a(User) } it { @user.openid_identifiers.should_not be_nil } it { @user.openid_identifiers.map{|i| i.url}.should be_include(@identity_url) } end describe "バリデーションエラーの場合" do before do @user.name = '' @user.email = '' end it { @user.should_not be_valid } it "userにエラーが設定されていること" do @user.valid? @user.errors.full_messages.size.should == 3 end end end describe User, ".create_with_identity_url" do before do @identity_url = "http://test.com/identity" @params = { :code => 'hoge', :name => "ほげ ふが", :email => 'hoge@hoge.com' } @user = mock_model(User) User.should_receive(:new_with_identity_url).and_return(@user) @user.should_receive(:save) end it { User.create_with_identity_url(@identity_url, @params).should be_is_a(User) } end describe User, ".auth" do subject { User.auth('code_or_email', "valid_password") { |result, user| @result = result; @authed_user = user } } describe "指定したログインID又はメールアドレスに対応するユーザが存在する場合" do before do @user = create_user @user.stub!(:crypted_password).and_return(User.encrypt("valid_password")) User.stub!(:find_by_code_or_email_with_key_phrase).and_return(@user) end describe "未使用ユーザの場合" do before do @user.stub!(:unused?).and_return(true) end it { should be_false } end describe "使用中ユーザの場合" do before do @user.stub!(:unused?).and_return(false) User.stub(:auth_successed).and_return(@user) User.stub(:auth_failed) end describe "パスワードが正しい場合" do it '認証成功処理が行われること' do User.should_receive(:auth_successed).with(@user) User.auth('code_or_email', "valid_password") end it "ユーザが返ること" do should be_true @authed_user.should == @user end end describe "パスワードは正しくない場合" do it '認証失敗処理が行われること' do User.should_receive(:auth_failed).with(@user) User.auth('code_or_email', 'invalid_password') end it "エラーメッセージが返ること" do User.auth('code_or_email', 'invalid_password').should be_false end end describe "パスワードの有効期限が切れている場合" do before do @user.stub!(:within_time_limit_of_password?).and_return(false) end it "エラーメッセージが返ること" do should be_false @authed_user.should == @user end end describe "アカウントがロックされている場合" do before do @user.stub!(:locked?).and_return(true) end it "エラーメッセージが返ること" do should be_false @authed_user.should == @user end end end end describe "指定したログインID又はメールアドレスに対応するユーザが存在しない場合" do before do User.should_receive(:find_by_code_or_email_with_key_phrase).at_least(:once).and_return(nil) end it { should be_false } end end describe User, "#delete_auth_tokens" do before do @user = create_user @user.remember_token = "remember_token" @user.remember_token_expires_at = Time.now @user.auth_session_token = "auth_session_token" @user.save @user.delete_auth_tokens! end it "すべてのトークンが削除されていること" do @user.remember_token.should be_nil @user.remember_token_expires_at.should be_nil @user.auth_session_token.should be_nil end end describe User, "#update_auth_session_token" do before do @user = create_user @auth_session_token = User.make_token User.stub!(:make_token).and_return(@auth_session_token) end describe 'シングルセッション機能が有効な場合' do before do Admin::Setting.should_receive(:enable_single_session).and_return(true) end it "トークンが保存されること" do @user.update_auth_session_token! @user.auth_session_token.should == @auth_session_token end it "トークンが返されること" do @user.update_auth_session_token!.should == @auth_session_token end end describe 'シングルセッション機能が無効な場合' do before do Admin::Setting.should_receive(:enable_single_session).and_return(false) end describe '新規ログインの場合(auth_session_tokenに値が入っていない)' do before do @user.auth_session_token = nil end it "トークンが保存されること" do @user.update_auth_session_token! @user.auth_session_token.should == @auth_session_token end it "トークンが返されること" do @user.update_auth_session_token!.should == @auth_session_token end end describe 'ログイン済みの場合(auth_session_tokenに値が入っている)' do before do @user.auth_session_token = 'auth_session_token' end it 'トークンが変化しないこと' do lambda do @user.update_auth_session_token! end.should_not change(@user, :auth_session_token) end it 'トークンが返されること' do @user.update_auth_session_token!.should == 'auth_session_token' end end end end describe User, '#issue_reset_auth_token' do before do @user = create_user @now = Time.local(2008, 11, 1) Time.stub!(:now).and_return(@now) end it 'reset_auth_tokenに値が入ること' do lambda do @user.issue_reset_auth_token end.should change(@user, :reset_auth_token) end it 'reset_auth_token_expires_atが24時間後となること' do lambda do @user.issue_reset_auth_token end.should change(@user, :reset_auth_token_expires_at).from(nil).to(@now.since(24.hour)) end end describe User, '#determination_reset_auth_token' do before do @user = create_user end it 'reset_auth_tokenの値が更新されること' do prc = '6df711a1a42d110261cfe759838213143ca3c2ad' @user.reset_auth_token = prc lambda do @user.determination_reset_auth_token end.should change(@user, :reset_auth_token).from(prc).to(nil) end it 'reset_auth_token_expires_atの値が更新されること' do time = Time.now @user.reset_auth_token_expires_at = time lambda do @user.determination_reset_auth_token end.should change(@user, :reset_auth_token_expires_at).from(time).to(nil) end end describe User, '#issue_activation_code' do before do @user = create_user @now = Time.local(2008, 11, 1) User.stub!(:activation_lifetime).and_return(2) Time.stub!(:now).and_return(@now) end it 'activation_tokenに値が入ること' do lambda do @user.issue_activation_code end.should change(@user, :activation_token) end it 'activation_token_expires_atが48時間後となること' do lambda do @user.issue_activation_code end.should change(@user, :activation_token_expires_at).from(nil).to(@now.since(48.hour)) end end describe User, '.issue_activation_codes' do before do @now = Time.local(2008, 11, 1) User.stub!(:activation_lifetime).and_return(2) Time.stub!(:now).and_return(@now) end describe '指定したIDのユーザが存在する場合' do before do @user = create_user(:status => 'UNUSED') end it '未使用ユーザのactivation_tokenに値が入ること' do unused_users, active_users = User.issue_activation_codes([@user.id]) unused_users.first.activation_token.should_not be_nil end it '未使用ユーザのactivation_token_expires_atが48時間後となること' do unused_users, active_users = User.issue_activation_codes([@user.id]) unused_users.first.activation_token_expires_at.should == @now.since(48.hour) end end end describe User, '#activate!' do it 'activation_tokenの値が更新されること' do activation_token = '6df711a1a42d110261cfe759838213143ca3c2ad' u = create_user(:user_options => {:activation_token=> activation_token}, :status => 'UNUSED') u.password = '' lambda do u.activate! end.should change(u, :activation_token).from(activation_token).to(nil) end it 'activation_token_expires_atの値が更新されること' do time = Time.now u = create_user(:user_options => {:activation_token_expires_at => time}, :status => 'UNUSED') u.password = '' lambda do u.activate! end.should change(u, :activation_token_expires_at).from(time).to(nil) end end describe User, '.activation_lifetime' do describe 'activation_lifetimeの設定が3(日)の場合' do before do Admin::Setting.stub!(:activation_lifetime).and_return(3) end it { User.activation_lifetime.should == 3 } end end describe User, '#within_time_limit_of_activation_token' do before do @activation_token_expires_at = Time.local(2008, 11, 1, 0, 0, 0) @activation_token = 'activation_token' end describe 'activation_token_expires_atが期限切れの場合' do before do @user = create_user(:user_options => {:activation_token => @activation_token, :activation_token_expires_at => @activation_token_expires_at }) now = @activation_token_expires_at.since(1.second) Time.stub!(:now).and_return(now) end it 'falseが返ること' do @user.within_time_limit_of_activation_token?.should be_false end end describe 'activation_token_expires_atが期限切れではない場合' do before do @user = create_user(:user_options => {:activation_token => @activation_token, :activation_token_expires_at => @activation_token_expires_at }) now = @activation_token_expires_at.ago(1.second) Time.stub!(:now).and_return(now) end it 'trueが返ること' do @user.within_time_limit_of_activation_token?.should be_true end end end describe User, '.grouped_sections' do before do User.delete_all create_user :user_options => {:email => SkipFaker.email, :section => 'Programmer'}, :user_uid_options => {:uid => SkipFaker.rand_num(6)} create_user :user_options => {:email => SkipFaker.email, :section => 'Programmer'}, :user_uid_options => {:uid => SkipFaker.rand_num(6)} create_user :user_options => {:email => SkipFaker.email, :section => 'Tester'}, :user_uid_options => {:uid => SkipFaker.rand_num(6)} end it {User.grouped_sections.size.should == 2} end describe User, "#find_or_initialize_profiles" do before do @user = new_user @user.save! @masters = (1..3).map{|i| create_user_profile_master(:name => "master#{i}")} @master_1_id = @masters[0].id @master_2_id = @masters[1].id end describe "設定されていないプロフィールがわたってきた場合" do it "新規に作成される" do @user.find_or_initialize_profiles(@master_1_id.to_s => "ほげ").should_not be_empty end it "新規の値が設定される" do @user.find_or_initialize_profiles(@master_1_id.to_s => "ほげ") @user.user_profile_values.each do |values| values.value.should == "ほげ" if values.user_profile_master_id == @master_1_id end end it "保存されていないprofile_valueが返される" do profiles = @user.find_or_initialize_profiles(@master_1_id.to_s => "ほげ") profiles.first.should be_is_a(UserProfileValue) profiles.first.value.should == "ほげ" profiles.first.should be_new_record end end describe "既に存在するプロフィールがわたってきた場合" do before do @user.user_profile_values.create(:user_profile_master_id => @master_1_id, :value => "ふが") end it "上書きされたものが返される" do profiles = @user.find_or_initialize_profiles(@master_1_id.to_s => "ほげ") profiles.first.should be_is_a(UserProfileValue) profiles.first.value.should == "ほげ" profiles.first.should be_changed end end describe "新規の値と保存された値が渡された場合" do before do @user.user_profile_values.create(:user_profile_master_id => @master_1_id, :value => "ふが") @profiles = @user.find_or_initialize_profiles(@master_1_id.to_s => "ほげ", @master_2_id.to_s => "ほげほげ") end it "保存されていたmaster_idが1のvalueは上書きされていること" do @profiles.each do |profile| if profile.user_profile_master_id == @master_1_id profile.value.should == "ほげ" end end end it "新規のmaster_idが2のvalueは新しく作られていること" do @profiles.each do |profile| if profile.user_profile_master_id == @master_2_id profile.value.should == "ほげほげ" end end end end describe "マスタに存在する値がパラメータで送られてこない場合" do before do @user.user_profile_values.create(:user_profile_master_id => @master_1_id, :value => "ほげ") @profiles = @user.find_or_initialize_profiles({}) @profile_hash = @profiles.index_by(&:user_profile_master_id) end it "空が登録されること" do @profile_hash[@master_1_id].value.should == "" end it "マスタの数だけprofile_valuesが返ってくること" do @profiles.size.should == @masters.size end end end describe User, '#group_symbols' do before do @user = create_user @group = create_group(:gid => 'skip_dev') do |g| g.group_participations.build(:user_id => @user.id, :owned => true) end @group_symbols = ['gid:skip_dev'] end describe '1度だけ呼ぶ場合' do it 'ユーザの所属するグループのシンボル配列を返すこと' do @user.group_symbols.should == @group_symbols end end describe '2度呼ぶ場合' do it 'ユーザの所属するグループのシンボル配列を返すこと(2回目はキャッシュされた結果になること)' do @user.group_symbols @user.group_symbols.should == @group_symbols end end end describe User, '#belong_symbols' do before do @user = stub_model(User, :symbol => 'uid:skipuser') @user.should_receive(:group_symbols).once.and_return(['gid:skip_dev']) end describe '1度だけ呼ぶ場合' do it 'ユーザ自身のシンボルとユーザの所属するグループのシンボルを配列で返すこと' do @user.belong_symbols.should == ['uid:skipuser', 'gid:skip_dev'] end end describe '2度呼ぶ場合' do it 'ユーザ自身のシンボルとユーザの所属するグループのシンボルを配列で返すこと(2回目はキャッシュされた結果になること' do @user.belong_symbols @user.belong_symbols.should == ['uid:skipuser', 'gid:skip_dev'] end end end describe User, "#belong_symbols_with_collaboration_apps" do before do SkipEmbedded::InitialSettings['host_and_port'] = 'test.host' SkipEmbedded::InitialSettings['protocol'] = 'http://' @user = stub_model(User, :belong_symbols => ["uid:a_user", "gid:a_group"], :code => "a_user") end describe "SkipEmbedded::InitialSettingsが設定されている場合" do before do SkipEmbedded::InitialSettings["belong_info_apps"] = { 'app' => { "url" => "http://localhost:3100/notes.js", "ca_file" => "hoge/fuga" } } end describe "情報が返ってくる場合" do before do SkipEmbedded::WebServiceUtil.stub!(:open_service_with_url).and_return([{"publication_symbols" => "note:1"}, { "publication_symbols" => "note:4"}]) end it "SKIP内の所属情報を返すこと" do ["uid:a_user", "gid:a_group", Symbol::SYSTEM_ALL_USER].each do |symbol| @user.belong_symbols_with_collaboration_apps.should be_include(symbol) end end it "SkipEmbedded::WebServiceUtilから他のアプリにアクセスすること" do SkipEmbedded::WebServiceUtil.should_receive(:open_service_with_url).with("http://localhost:3100/notes.js", { :user => "http://test.host/id/a_user" }, "hoge/fuga") @user.belong_symbols_with_collaboration_apps end it "連携アプリ内の所属情報を返すこと" do ["note:1"].each do |symbol| @user.belong_symbols_with_collaboration_apps.should be_include(symbol) end end end describe "情報が取得できない場合" do before do SkipEmbedded::WebServiceUtil.stub!(:open_service_with_url) end it "publicが追加されること" do ["uid:a_user", "gid:a_group", Symbol::SYSTEM_ALL_USER, "public"].each do |symbol| @user.belong_symbols_with_collaboration_apps.should be_include(symbol) end end end end describe "SkipEmbedded::InitialSettingsが設定されていない場合" do before do SkipEmbedded::InitialSettings["belong_info_apps"] = {} end it "SKIP内の所属情報を返すこと" do ["uid:a_user", "gid:a_group", Symbol::SYSTEM_ALL_USER, "public"].each do |symbol| @user.belong_symbols_with_collaboration_apps.should be_include(symbol) end end end end describe User, "#openid_identifier" do before do SkipEmbedded::InitialSettings['host_and_port'] = 'test.host' SkipEmbedded::InitialSettings['protocol'] = 'http://' @user = stub_model(User, :code => "a_user") end it "OPとして発行する OpenID identifier を返すこと" do @user.openid_identifier.should == "http://test.host/id/a_user" end it "relative_url_rootが設定されている場合 反映されること" do ActionController::Base.relative_url_root = "/skip" @user.openid_identifier.should == "http://test.host/skip/id/a_user" end after do ActionController::Base.relative_url_root = nil end end describe User, '#to_s_log' do before do @user = stub_model(User, :id => "99", :uid => '999999') end it 'ログに出力する形式に整えられた文字列を返すこと' do @user.to_s_log('message').should == "message: {\"user_id\" => \"#{@user.id}\", \"uid\" => \"#{@user.uid}\"}" end end describe User, '#locked?' do before do @user = stub_model(User) end describe 'ユーザロック機能が有効な場合' do before do Admin::Setting.enable_user_lock = 'true' end describe 'ユーザがロックされている場合' do before do @user.locked = true end it 'ロックされていると判定されること' do @user.locked?.should be_true end end describe 'ユーザがロックされていない場合' do before do @user.locked = false end it 'ロックされていないと判定されること' do @user.locked?.should be_false end end end describe 'ユーザロック機能が無効な場合' do before do Admin::Setting.enable_user_lock = 'false' end describe 'ユーザがロックされている場合' do before do @user.locked = true end it 'ロックされていると判定されること' do @user.locked?.should be_true end end describe 'ユーザがロックされていない場合' do before do @user.locked = false end it 'ロックされていないと判定されること' do @user.locked?.should be_false end end end end describe User, '#within_time_limit_of_password?' do before do @user = stub_model(User) end describe 'パスワード変更強制機能が有効な場合' do before do Admin::Setting.enable_password_periodic_change = 'true' end describe 'パスワードの有効期限切れ日が設定されている場合' do before do @user.password_expires_at = Time.local(2009, 3, 1, 0, 0, 0) end describe 'パスワード有効期限切れの場合' do before do now = Time.local(2009, 3, 1, 0, 0, 1) Time.stub!(:now).and_return(now) end it 'パスワード有効期限切れと判定されること' do @user.within_time_limit_of_password?.should be_false end end describe 'パスワード有効期限内の場合' do before do now = Time.local(2009, 3, 1, 0, 0, 0) Time.stub!(:now).and_return(now) end it 'パスワード有効期限内と判定されること' do @user.within_time_limit_of_password?.should be_true end end end describe 'パスワードの有効期限切れ日が設定されていない場合' do before do @user.password_expires_at = nil end it 'パスワード有効期限切れと判定されること' do @user.within_time_limit_of_password?.should be_nil end end end describe 'パスワード変更強制機能が無効な場合' do before do Admin::Setting.enable_password_periodic_change = 'false' end it 'パスワード有効期限内と判定されること' do @user.within_time_limit_of_password?.should be_true end end end describe User, '.synchronize_users' do describe '二人の利用中のユーザと一人の退職ユーザと一人の未使用ユーザが存在する場合' do before do User.delete_all SkipEmbedded::InitialSettings['host_and_port'] = 'localhost:3000' SkipEmbedded::InitialSettings['protocol'] = 'http://' @bob = create_user :user_options => {:name => 'ボブ', :admin => false}, :user_uid_options => {:uid => 'boob'} @alice = create_user :user_options => {:name => 'アリス', :admin => true}, :user_uid_options => {:uid => 'alice'} @carol = create_user :user_options => {:name => 'キャロル', :admin => false}, :user_uid_options => {:uid => 'carol'}, :status => 'RETIRED' @michael = create_user :user_options => { :name => "マイケル", :admin => false }, :user_uid_options => { :uid => 'michael' }, :status => "UNUSED" @users = User.synchronize_users @bob_attr, @alice_attr, @carol_attr, @michael_attr = @users end it '4件のユーザ同期情報を取得できること' do @users.size.should == 4 end it 'ボブの情報が正しく設定されていること' do @bob_attr.should == ['http://localhost:3000/id/boob', 'boob', 'ボブ', false, false] end it 'アリスの情報が正しく設定されていること' do @alice_attr.should == ['http://localhost:3000/id/alice', 'alice', 'アリス', true, false] end it 'キャロルの情報が正しく設定されていること' do @carol_attr.should == ['http://localhost:3000/id/carol', 'carol', 'キャロル', false, true] end it "マイケルの情報が正しく設定されていること" do @michael_attr.should == ["http://localhost:3000/id/michael", 'michael', "マイケル", false, false] end describe 'ボブが4分59秒前に更新、アリスが5分前に更新、キャロル, マイケルが5分1秒前に更新されており、5分以内に更新があったユーザのみ取得する場合' do before do Time.stub!(:now).and_return(Time.local(2009, 6, 2, 0, 0, 0)) User.record_timestamps = false @bob.update_attribute(:updated_on, Time.local(2009, 6, 1, 23, 54, 59)) @alice.update_attribute(:updated_on, Time.local(2009, 6, 1, 23, 55, 0)) @carol.update_attribute(:updated_on, Time.local(2009, 6, 1, 23, 55, 1)) @michael.update_attribute(:updated_on, Time.local(2009, 6, 1, 23, 55, 1)) @users = User.synchronize_users 5 @alice_attr, @carol_attr, @michael_attr = @users end it '3件のユーザ同期情報を取得できること' do @users.size.should == 3 end it 'アリスの情報が正しく設定されていること' do @alice_attr.should == ['http://localhost:3000/id/alice', 'alice', 'アリス', true, false] end it 'キャロルの情報が正しく設定されていること' do @carol_attr.should == ['http://localhost:3000/id/carol', 'carol', 'キャロル', false, true] end it "マイケルの情報が正しく設定されていること" do @michael_attr.should == ["http://localhost:3000/id/michael", 'michael', "マイケル", false, false] end after do User.record_timestamps = true end end end end describe User, "#custom" do it "関連するuser_customが存在するユーザの場合、そのuser_customが返る" do user = create_user custom = user.create_user_custom(:theme => "green", :editor_mode => "hiki") user.custom.should == custom end it "関連するuser_customが存在しないユーザの場合、新規のuser_customが取得返る" do user = create_user user.custom.should be_is_a(UserCustom) user.custom.should be_new_record end end describe User, '#participating_groups?' do before do @user = stub_model(User, :id => 99) @group = create_group end describe '指定したユーザがグループ参加者(参加済み)の場合' do before do group_participation = create_group_participation(:user_id => @user.id, :group_id => @group.id) end it 'trueが返ること' do @user.participating_group?(@group).should be_true end end describe '指定したユーザがグループ参加者(参加待ち)の場合' do before do group_participation = create_group_participation(:user_id => @user.id, :group_id => @group.id, :waiting => true) end it 'falseが返ること' do @user.participating_group?(@group).should be_false end end describe '指定したユーザがグループ管理者(参加済み)の場合' do before do group_participation = create_group_participation(:user_id => @user.id, :group_id => @group.id, :waiting => false, :owned => true) end it 'trueが返ること' do @user.participating_group?(@group).should be_true end end describe '指定したユーザがグループ管理者(参加待ち)の場合' do before do group_participation = create_group_participation(:user_id => @user.id, :group_id => @group.id, :waiting => true, :owned => true) end it 'falseが返ること' do @user.participating_group?(@group).should be_false end end describe '指定したユーザがグループ未参加者の場合' do before do group_participation = create_group_participation(:user_id => @user.id + 1, :group_id => @group.id) end it 'falseが返ること' do @user.participating_group?(@group).should be_false end end describe 'Group以外の場合' do it 'ArgumentErrorとなること' do lambda { @user.participating_group?(nil) }.should raise_error(ArgumentError) end end end describe User, 'password_required?' do before do @user = new_user end describe 'パスワードモードの場合' do before do SkipEmbedded::InitialSettings['login_mode'] = 'password' end describe 'パスワードが空の場合' do before do @user.password = '' end describe 'ユーザが利用中の場合' do before do @user.status = 'ACTIVE' end describe 'crypted_passwordが空の場合' do before do @user.crypted_password = '' end it '必要(true)と判定されること' do @user.send(:password_required?).should be_true end end describe 'crypted_passwordが空ではない場合' do before do @user.crypted_password = 'password' end it '必要ではない(false)と判定されること' do @user.send(:password_required?).should be_false end end end describe 'ユーザが利用中ではない場合' do before do @user.status = 'UNUSED' end it '必要ではない(false)と判定されること' do @user.send(:password_required?).should be_false end end end describe 'パスワードが空ではない場合' do before do @user.password = 'Password1' end it '必要(true)と判定されること' do @user.send(:password_required?).should be_true end end end describe 'パスワードモード以外の場合' do before do SkipEmbedded::InitialSettings['login_mode'] = 'rp' end it '必要ではない(false)と判定されること' do @user.send(:password_required?).should be_false end end end describe User, '.find_by_code_or_email_with_key_phrase' do before do @user = stub_model(User) User.stub!(:find_by_code_or_email).and_return(@user) end describe 'ログインキーフレーズが有効な場合' do before do Admin::Setting.should_receive(:enable_login_keyphrase).and_return(true) Admin::Setting.should_receive(:login_keyphrase).and_return('key_phrase') end describe 'ログインキーフレーズが設定値と一致する場合' do before do @key_phrase = 'key_phrase' end it 'ログインIDまたはemailで検索した結果が返ること' do User.send(:find_by_code_or_email_with_key_phrase, 'code_or_email', @key_phrase).should == @user end end describe 'ログインキーフレーズが設定値と一致しない場合' do before do @key_phrase = 'invalid_key_phrase' end it 'nilが返ること' do User.send(:find_by_code_or_email_with_key_phrase, 'code_or_email', @key_phrase).should be_nil end end end describe 'ログインキーフレーズが無効な場合' do before do Admin::Setting.should_receive(:enable_login_keyphrase).and_return(false) end it 'ログインIDまたはemailで検索した結果が返ること' do User.send(:find_by_code_or_email_with_key_phrase, 'code_or_email', @key_phrase).should == @user end end end describe User, '.find_by_code_or_email' do describe 'ログインIDに一致するユーザが見つかる場合' do before do @user = mock_model(User) User.should_receive(:find_by_code).and_return(@user) end it '見つかったユーザが返ること' do User.send(:find_by_code_or_email, 'login_id').should == @user end end describe 'ログインIDに一致するユーザが見つからない場合' do before do @user = mock_model(User) User.should_receive(:find_by_code).and_return(nil) end describe 'メールアドレスに一致するユーザが見つかる場合' do before do User.should_receive(:find_by_email).and_return(@user) end it '見つかったユーザが返ること' do User.send(:find_by_code_or_email, 'skip@example.org').should == @user end end describe 'メールアドレスに一致するユーザが見つからない場合' do before do User.should_receive(:find_by_email).and_return(nil) end it 'nilが返ること' do User.send(:find_by_code_or_email, 'skip@example.org').should be_nil end end end end describe User, '.auth_successed' do before do @user = create_user end it "検索されたユーザが返ること" do User.send(:auth_successed, @user).should == @user end describe 'ユーザがロックされている場合' do before do @user.should_receive(:locked?).and_return(true) end it 'last_authenticated_atが変化しないこと' do lambda do User.send(:auth_successed, @user) end.should_not change(@user, :last_authenticated_at) end it 'ログイン試行回数が変化しないこと' do lambda do User.send(:auth_successed, @user) end.should_not change(@user, :trial_num) end end describe 'ユーザがロックされていない場合' do before do @user.trial_num = 2 end it "last_authenticated_atが現在時刻に設定されること" do time = Time.now Time.stub!(:now).and_return(time) lambda do User.send(:auth_successed, @user) end.should change(@user, :last_authenticated_at).to(time) end it 'ログイン試行回数が0になること' do lambda do User.send(:auth_successed, @user) end.should change(@user, :trial_num).to(0) end end end describe User, '.auth_failed' do before do @user = create_user end it 'nilが返ること' do User.send(:auth_failed, @user).should be_nil end describe 'ユーザがロックされていない場合' do before do @user.should_receive(:locked?).and_return(false) end describe 'ログイン試行回数が最大値未満の場合' do before do @user.trial_num = 2 Admin::Setting.user_lock_trial_limit = 3 end describe 'ユーザロック機能が有効な場合' do before do Admin::Setting.enable_user_lock = 'true' end it 'ログイン試行回数が1増加すること' do lambda do User.send(:auth_failed, @user) end.should change(@user, :trial_num).to(3) end end describe 'ユーザロック機能が無効な場合' do before do Admin::Setting.enable_user_lock = 'false' end it 'ログイン試行回数が変化しないこと' do lambda do User.send(:auth_failed, @user) end.should_not change(@user, :trial_num) end end end describe 'ログイン試行回数が最大値以上の場合' do before do @user.trial_num = 3 Admin::Setting.user_lock_trial_limit = 3 end describe 'ユーザロック機能が有効な場合' do before do Admin::Setting.enable_user_lock = 'true' end it 'ロックされること' do lambda do User.send(:auth_failed, @user) end.should change(@user, :locked).to(true) end it 'ロックした旨のログが出力されること' do @user.should_receive(:to_s_log).with('[User Locked]').and_return('user locked log') @user.logger.should_receive(:info).with('user locked log') User.send(:auth_failed, @user) end end describe 'ユーザロック機能が無効な場合' do before do Admin::Setting.enable_user_lock = 'false' end it 'ロック状態が変化しないこと' do lambda do User.send(:auth_failed, @user) end.should_not change(@user, :locked) end it 'ロックした旨のログが出力されないこと' do @user.stub!(:to_s_log).with('[User Locked]').and_return('user locked log') @user.logger.should_not_receive(:info).with('user locked log') User.send(:auth_failed, @user) end end end end describe 'ユーザがロックされている場合' do before do @user.should_receive(:locked?).and_return(true) end it 'ログイン試行回数が変化しないこと' do lambda do User.send(:auth_failed, @user) end.should_not change(@user, :trial_num) end it 'ロック状態が変化しないこと' do lambda do User.send(:auth_failed, @user) end.should_not change(@user, :locked) end it 'ロックした旨のログが出力されないこと' do @user.stub!(:to_s_log).with('[User Locked]').and_return('user locked log') @user.logger.should_not_receive(:info).with('user locked log') User.send(:auth_failed, @user) end end end def new_user options = {} User.new({ :name => 'ほげ ほげ', :password => 'Password1', :password_confirmation => 'Password1', :email => SkipFaker.email, :section => 'Tester',}.merge(options)) end
openskip/skip
spec/models/user_spec.rb
Ruby
gpl-3.0
52,460
angular.module('starter.controllers') .controller('HistoryCtrl', function($scope) { $scope.history = [ { label: "Today, 10am-11am", min: 60, max: 87}, { label: "Today, 9am-10am", min: 62, max: 76}, { label: "Today, 8am-9am", min: 55, max: 79}, { label: "Yesterday, 10pm-11pm", min: 66, max: 83}, { label: "Yesterday, 6pm-7pm", min: 62, max: 91}, { label: "Yesterday, 5m-6pm", min: 54, max: 82}, { label: "Yesterday, 10am-11pm", min: 62, max: 97}, { label: "Yesterday, 9am-10pm", min: 64, max: 79}, ]; $scope.history.forEach(function(entry) { if (entry.max > 95) { entry.bgCol = "red"; entry.fgCol = "white"; entry.weight = "bold"; } else if( entry.max > 85) { entry.bgCol = "orange"; entry.fgCol = "white"; entry.weight = "bold"; } else { entry.bgCol = "white"; entry.fgCol = "black"; entry.weight = "normal"; } }); });
JBeaudaux/JBeaudaux.github.io
OpenHeart/js/history.js
JavaScript
gpl-3.0
987
const editor = require('./form-editor/form-editor.js') const fields = require('./form-editor/fields.js') const settings = require('./settings') const notices = {} function show (id, text) { notices[id] = text render() } function hide (id) { delete notices[id] render() } function render () { let html = '' for (const key in notices) { html += '<div class="notice notice-warning inline"><p>' + notices[key] + '</p></div>' } let container = document.querySelector('.mc4wp-notices') if (!container) { container = document.createElement('div') container.className = 'mc4wp-notices' const heading = document.querySelector('h1, h2') heading.parentNode.insertBefore(container, heading.nextSibling) } container.innerHTML = html } const groupingsNotice = function () { const text = 'Your form contains deprecated <code>GROUPINGS</code> fields. <br /><br />Please remove these fields from your form and then re-add them through the available field buttons to make sure your data is getting through to Mailchimp correctly.' const formCode = editor.getValue().toLowerCase(); (formCode.indexOf('name="groupings') > -1) ? show('deprecated_groupings', text) : hide('deprecated_groupings') } const requiredFieldsNotice = function () { const requiredFields = fields.getAllWhere('forceRequired', true) const missingFields = requiredFields.filter(function (f) { return !editor.containsField(f.name.toUpperCase()) }) let text = '<strong>Heads up!</strong> Your form is missing list fields that are required in Mailchimp. Either add these fields to your form or mark them as optional in Mailchimp.' text += '<br /><ul class="ul-square" style="margin-bottom: 0;"><li>' + missingFields.map(function (f) { return f.title }).join('</li><li>') + '</li></ul>'; (missingFields.length > 0) ? show('required_fields_missing', text) : hide('required_fields_missing') } const mailchimpListsNotice = function () { const text = '<strong>Heads up!</strong> You have not yet selected a Mailchimp list to subscribe people to. Please select at least one list from the <a href="javascript:void(0)" data-tab="settings" class="tab-link">settings tab</a>.' if (settings.getSelectedLists().length > 0) { hide('no_lists_selected') } else { show('no_lists_selected', text) } } // old groupings groupingsNotice() editor.on('focus', groupingsNotice) editor.on('blur', groupingsNotice) // missing required fields requiredFieldsNotice() editor.on('blur', requiredFieldsNotice) editor.on('focus', requiredFieldsNotice) document.body.addEventListener('change', mailchimpListsNotice)
ibericode/mailchimp-for-wordpress
assets/src/js/admin/notices.js
JavaScript
gpl-3.0
2,625
package hu.rgai.yako.beens; import java.util.*; import android.os.Parcel; import android.os.Parcelable; /** * * @author Tamas Kojedzinszky */ public class MainServiceExtraParams implements Parcelable { public static final Parcelable.Creator<MainServiceExtraParams> CREATOR = new Parcelable.Creator<MainServiceExtraParams>() { public MainServiceExtraParams createFromParcel(Parcel in) { return new MainServiceExtraParams(in); } public MainServiceExtraParams[] newArray(int size) { return new MainServiceExtraParams[size]; } }; private boolean mFromNotifier = false; private int mQueryLimit = -1; private int mQueryOffset = -1; private boolean mLoadMore = false; private List<Account> mAccounts = new LinkedList<>(); private boolean mForceQuery = false; private int mResult = -1; private boolean mMessagesRemovedAtServer = false; private boolean mSplittedMessageSecondPart = false; private boolean mNewMessageArrivedRequest = false; private TreeMap<String, MessageListElement> mSplittedMessages = new TreeMap<>(); public MainServiceExtraParams() {} public MainServiceExtraParams(Parcel in) { mFromNotifier = in.readByte() == 1; mQueryLimit = in.readInt(); mQueryOffset = in.readInt(); mLoadMore = in.readByte() == 1; in.readList(mAccounts,Account.class.getClassLoader()); mForceQuery = in.readByte() == 1; mResult = in.readInt(); mMessagesRemovedAtServer = in.readByte() == 1; mSplittedMessageSecondPart = in.readByte() == 1; mNewMessageArrivedRequest = in.readByte() == 1; int splittedLength = in.readInt(); for (int i = 0; i < splittedLength; i++) { mSplittedMessages.put(in.readString(), (MessageListElement)in.readParcelable(MessageListElement.class.getClassLoader())); } } public int describeContents() { return 0; } public void writeToParcel(Parcel dest, int flags) { dest.writeByte((byte)(mFromNotifier ? 1 : 0)); dest.writeInt(mQueryLimit); dest.writeInt(mQueryOffset); dest.writeByte((byte) (mLoadMore ? 1 : 0)); dest.writeList(mAccounts); dest.writeByte((byte) (mForceQuery ? 1 : 0)); dest.writeInt(mResult); dest.writeByte((byte) (mMessagesRemovedAtServer ? 1 : 0)); dest.writeByte((byte) (mSplittedMessageSecondPart ? 1 : 0)); dest.writeByte((byte) (mNewMessageArrivedRequest ? 1 : 0)); dest.writeInt(mSplittedMessages.size()); for (Map.Entry<String, MessageListElement> e : mSplittedMessages.entrySet()) { dest.writeString(e.getKey()); dest.writeParcelable(e.getValue(), flags); } } public boolean isFromNotifier() { return mFromNotifier; } public void setFromNotifier(boolean mFromNotifier) { this.mFromNotifier = mFromNotifier; } public int getQueryLimit() { return mQueryLimit; } public void setQueryLimit(int mQueryLimit) { this.mQueryLimit = mQueryLimit; } public int getQueryOffset() { return mQueryOffset; } public void setQueryOffset(int mQueryOffset) { this.mQueryOffset = mQueryOffset; } public boolean isLoadMore() { return mLoadMore; } public void setLoadMore(boolean mLoadMore) { this.mLoadMore = mLoadMore; } public boolean isAccountsEmpty() { return mAccounts.isEmpty(); } public boolean accountsContains(Account acc) { return mAccounts.contains(acc); } public List<Account> getAccounts() { return Collections.unmodifiableList(mAccounts) ; } public void addAccount(Account acc) { this.mAccounts.add(acc); } public void setOnNewMessageArrived(boolean newMessageArrivedRequest) { mNewMessageArrivedRequest = newMessageArrivedRequest; } public boolean isNewMessageArrivedRequest() { return mNewMessageArrivedRequest; } public void setAccount(Account account) { mAccounts.clear(); mAccounts.add(account); } public void setAccounts(List<Account> accounts) { this.mAccounts = accounts; } public boolean isForceQuery() { return mForceQuery; } public void setForceQuery(boolean mForceQuery) { this.mForceQuery = mForceQuery; } public int getResult() { return mResult; } public void setResult(int mResult) { this.mResult = mResult; } public boolean isMessagesRemovedAtServer() { return mMessagesRemovedAtServer; } public void setMessagesRemovedAtServer(boolean mMessagesRemovedAtServer) { this.mMessagesRemovedAtServer = mMessagesRemovedAtServer; } public void setSplittedMessageSecondPart(boolean splittedMessageSecondPart) { mSplittedMessageSecondPart = splittedMessageSecondPart; } public void setSplittedMessages(TreeMap<String, MessageListElement> splittedMessages) { mSplittedMessages = splittedMessages; } public TreeMap<String, MessageListElement> getSplittedMessages() { return mSplittedMessages; } public boolean isSplittedMessageSecondPart() { return mSplittedMessageSecondPart; } @Override public String toString() { String ToString = "MainServiceExtraParams{" + "mFromNotifier=" + mFromNotifier + ", mQueryLimit=" + mQueryLimit + ", mQueryOffset=" + mQueryOffset + ", mLoadMore=" + mLoadMore + ", mAccounts="; for (int i = 0; i < mAccounts.size(); i++) { ToString += mAccounts.get(i) + ", "; } ToString += "mForceQuery=" + mForceQuery + ", mResult=" + mResult + '}'; return ToString; } }
k-kojak/yako
src/hu/rgai/yako/beens/MainServiceExtraParams.java
Java
gpl-3.0
5,416
<? // // TorrentTrader v2.x // This file was last updated: 06/03/2009 by TorrentialStorm // // http://www.torrenttrader.org // // require_once("backend/functions.php"); dbconn(); //check permissions if ($site_config["MEMBERSONLY"]){ loggedinonly(); if($CURUSER["view_torrents"]=="no") show_error_msg("Error","You do not have permission to view torrents",1); } function sqlwildcardesc($x){ return str_replace(array("%","_"), array("\\%","\\_"), mysql_real_escape_string($x)); } //GET SEARCH STRING $searchstr = trim(unesc($_GET["search"])); $cleansearchstr = searchfield($searchstr); if (empty($cleansearchstr)) unset($cleansearchstr); $thisurl = "torrents-search.php?"; $addparam = ""; $wherea = array(); $wherecatina = array(); $wherea[] = "banned = 'no'"; $wherecatina = array(); $wherecatin = ""; $res = mysql_query("SELECT id FROM categories"); while($row = mysql_fetch_assoc($res)){ if ($_GET["c$row[id]"]) { $wherecatina[] = $row[id]; $addparam .= "c$row[id]=1&amp;"; $addparam .= "c$row[id]=1&amp;"; $thisurl .= "c$row[id]=1&amp;"; } $wherecatin = implode(", ", $wherecatina); } if ($wherecatin) $wherea[] = "category IN ($wherecatin)"; //include dead if ($_GET["incldead"] == 1) { $addparam .= "incldead=1&amp;"; $thisurl .= "incldead=1&"; }elseif ($_GET["incldead"] == 2){ $wherea[] = "visible = 'no'"; $addparam .= "incldead=2&amp;"; $thisurl .= "incldead=2&"; }else $wherea[] = "visible = 'yes'"; // Include freeleech if ($_GET["freeleech"] == 1) { $addparam .= "freeleech=1&amp;"; $thisurl .= "freeleech=1&amp;"; $wherea[] = "freeleech = '0'"; } elseif ($_GET["freeleech"] == 2) { $addparam .= "freeleech=2&amp;"; $thisurl .= "freeleech=2&amp;"; $wherea[] = "freeleech = '1'"; } //include external if ($_GET["inclexternal"] == 1) { $addparam .= "inclexternal=1&amp;"; $wherea[] = "external = 'no'"; } if ($_GET["inclexternal"] == 2) { $addparam .= "inclexternal=2&amp;"; $wherea[] = "external = 'yes'"; } //cat if ($_GET["cat"]) { $wherea[] = "category = " . sqlesc($_GET["cat"]); $wherecatina[] = sqlesc($_GET["cat"]); $addparam .= "cat=" . urlencode($_GET["cat"]) . "&amp;"; $thisurl .= "cat=".urlencode($_GET["cat"])."&"; } //language if ($_GET["lang"]) { $wherea[] = "torrentlang = " . sqlesc($_GET["lang"]); $addparam .= "lang=" . urlencode($_GET["lang"]) . "&amp;"; $thisurl .= "lang=".urlencode($_GET["lang"])."&"; } //parent cat if ($_GET["parent_cat"]) { $addparam .= "parent_cat=" . urlencode($_GET["parent_cat"]) . "&amp;"; $thisurl .= "parent_cat=".urlencode($_GET["parent_cat"])."&"; } $parent_cat = $_GET["parent_cat"]; $wherebase = $wherea; if (isset($cleansearchstr)) { $wherea[] = "MATCH (torrents.name) AGAINST ('".mysql_real_escape_string($searchstr)."' IN BOOLEAN MODE)"; $addparam .= "search=" . urlencode($searchstr) . "&amp;"; $thisurl .= "search=".urlencode($searchstr)."&"; } //order by if ($_GET['sort'] && $_GET['order']) { $column = ''; $ascdesc = ''; switch($_GET['sort']) { case 'id': $column = "id"; break; case 'name': $column = "name"; break; case 'comments': $column = "comments"; break; case 'size': $column = "size"; break; case 'times_completed': $column = "times_completed"; break; case 'seeders': $column = "seeders"; break; case 'leechers': $column = "leechers"; break; case 'category': $column = "category"; break; default: $column = "id"; break; } switch($_GET['order']) { case 'asc': $ascdesc = "ASC"; break; case 'desc': $ascdesc = "DESC"; break; default: $ascdesc = "DESC"; break; } } else { $_GET["sort"] = "id"; $_GET["order"] = "desc"; $column = "id"; $ascdesc = "DESC"; } $orderby = "ORDER BY torrents." . $column . " " . $ascdesc; $pagerlink = "sort=" . $_GET['sort'] . "&order=" . $_GET['order'] . "&"; if (is_valid_id($_GET["page"])) $thisurl .= "page=$_GET[page]&"; $where = implode(" AND ", $wherea); if ($where != "") $where = "WHERE $where"; if ($parent_cat){ $parent_check = " AND categories.parent_cat='$parent_cat'"; } //GET NUMBER FOUND FOR PAGER $res = mysql_query("SELECT COUNT(*) FROM torrents $where $parent_check") or die(mysql_error()); $row = mysql_fetch_array($res); $count = $row[0]; if (!$count && isset($cleansearchstr)) { $wherea = $wherebase; $searcha = explode(" ", $cleansearchstr); $sc = 0; foreach ($searcha as $searchss) { if (strlen($searchss) <= 1) continue; $sc++; if ($sc > 5) break; $ssa = array(); foreach (array("torrents.name") as $sss) $ssa[] = "$sss LIKE '%" . sqlwildcardesc($searchss) . "%'"; $wherea[] = "(" . implode(" OR ", $ssa) . ")"; } if ($sc) { $where = implode(" AND ", $wherea); if ($where != "") $where = "WHERE $where"; $res = mysql_query("SELECT COUNT(*) FROM torrents $where $parent_check"); $row = mysql_fetch_array($res); $count = $row[0]; } } //Sort by if ($addparam != "") { if ($pagerlink != "") { if ($addparam{strlen($addparam)-1} != ";") { // & = &amp; $addparam = $addparam . "&" . $pagerlink; } else { $addparam = $addparam . $pagerlink; } } } else { $addparam = $pagerlink; } if ($count) { //SEARCH QUERIES! list($pagertop, $pagerbottom, $limit) = pager(20, $count, "torrents-search.php?" . $addparam); $query = "SELECT torrents.id, torrents.anon, torrents.announce, torrents.category, torrents.leechers, torrents.nfo, torrents.seeders, torrents.name, torrents.times_completed, torrents.size, torrents.added, torrents.comments, torrents.numfiles, torrents.filename, torrents.owner, torrents.external, torrents.freeleech, categories.name AS cat_name, categories.parent_cat AS cat_parent, categories.image AS cat_pic, users.username, users.privacy, IF(torrents.numratings < 2, NULL, ROUND(torrents.ratingsum / torrents.numratings, 1)) AS rating FROM torrents LEFT JOIN categories ON category = categories.id LEFT JOIN users ON torrents.owner = users.id $where $parent_check $orderby $limit"; $res = mysql_query($query) or die(mysql_error()); }else{ unset($res); } if (isset($cleansearchstr)) stdhead("Search results for \"$searchstr\""); else stdhead("Browse Torrents"); begin_frame("" . SEARCH_TITLE . ""); // get all parent cats echo "<CENTER><B>".CATEGORIES.":</B> "; $catsquery = mysql_query("SELECT distinct parent_cat FROM categories ORDER BY parent_cat")or die(mysql_error()); echo " - <a href=torrents.php>".SHOWALL."</a>"; while($catsrow = MYSQL_FETCH_ARRAY($catsquery)){ echo " - <a href=torrents.php?parent_cat=".urlencode($catsrow['parent_cat']).">$catsrow[parent_cat]</a>"; } ?> <BR><BR> <form method="get" action="torrents-search.php"> <table class=bottom align="center"> <tr align='right'> <? $i = 0; $cats = mysql_query("SELECT * FROM categories ORDER BY parent_cat, name"); while ($cat = mysql_fetch_assoc($cats)) { $catsperrow = 5; print(($i && $i % $catsperrow == 0) ? "</tr><tr align='right'>" : ""); print("<td style=\"padding-bottom: 2px;padding-left: 2px\"><a class=catlink href=torrents.php?cat={$cat["id"]}>".htmlspecialchars($cat["parent_cat"])." - " . htmlspecialchars($cat["name"]) . "</a><input name=c{$cat["id"]} type=\"checkbox\" " . (in_array($cat["id"], $wherecatina) ? "checked " : "") . "value=1></td>\n"); $i++; } echo "</tr></table>"; //if we are browsing, display all subcats that are in same cat if ($parent_cat){ echo "<BR><BR><b>You are in:</b> <a href=torrents.php?parent_cat=$parent_cat>$parent_cat</a><BR><B>Sub Categories:</B> "; $subcatsquery = mysql_query("SELECT id, name, parent_cat FROM categories WHERE parent_cat='$parent_cat' ORDER BY name")or die(mysql_error()); while($subcatsrow = MYSQL_FETCH_ARRAY($subcatsquery)){ $name = $subcatsrow['name']; echo " - <a href=torrents.php?cat=$subcatsrow[id]>$name</a>"; } } echo "</CENTER><BR><BR>";//some spacing ?> <CENTER> <? print("" . SEARCH . "\n"); ?> <input type="text" name="search" size="40" value="<?= stripslashes(htmlspecialchars($searchstr)) ?>" /> <? print("" . IN . "\n"); ?> <select name="cat"> <option value="0"><? echo "(".ALL." ".TYPES.")";?></option> <? $cats = genrelist(); $catdropdown = ""; foreach ($cats as $cat) { $catdropdown .= "<option value=\"" . $cat["id"] . "\""; if ($cat["id"] == $_GET["cat"]) $catdropdown .= " selected=\"selected\""; $catdropdown .= ">" . htmlspecialchars($cat["parent_cat"]) . ": " . htmlspecialchars($cat["name"]) . "</option>\n"; } ?> <?= $catdropdown ?> </select> <BR><BR> <select name="incldead"> <option value="0"><?php echo "".ACTIVE_TRANSFERS."";?></option> <option value="1" <?php if ($_GET["incldead"] == 1) echo "selected"; ?>><?php echo "".INC_DEAD."";?></option> <option value="2" <?php if ($_GET["incldead"] == 2) echo "selected"; ?>><?php echo "".ONLY_DEAD."";?></option> </select> <select name="freeleech"> <option value="0">Any</option> <option value="1" <?php if ($_GET["freeleech"] == 1) echo "selected"; ?>>Not freeleech</option> <option value="2" <?php if ($_GET["freeleech"] == 2) echo "selected"; ?>>Only freeleech</option> </select> <?if ($site_config["ALLOWEXTERNAL"]){?> <select name="inclexternal"> <option value="0">Local/External</option> <option value="1" <?php if ($_GET["inclexternal"] == 1) echo "selected"; ?>>Local Only</option> <option value="2" <?php if ($_GET["inclexternal"] == 2) echo "selected"; ?>>External Only</option> </select> <? } ?> <select name="lang"> <option value="0"><? echo "(".ALL.")";?></option> <? $lang = langlist(); $langdropdown = ""; foreach ($lang as $lang) { $langdropdown .= "<option value=\"" . $lang["id"] . "\""; if ($lang["id"] == $_GET["lang"]) $langdropdown .= " selected=\"selected\""; $langdropdown .= ">" . htmlspecialchars($lang["name"]) . "</option>\n"; } ?> <?= $langdropdown ?> </select> <input type="submit" value="<? print("" . SEARCH . "\n"); ?>" /> <br> </form> </CENTER><CENTER><? print("" . SEARCH_RULES . "\n"); ?></CENTER><BR> <? //sort /* echo "<div align=right><form action='' name='jump' method='GET'>"; echo "Sort By: <select name='sort' onChange='document.jump.submit();' style=\"font-family: Verdana; font-size: 8pt; border: 1px solid #000000; background-color: #CCCCCC\" size=\"1\">"; echo "<option value='id'" . ($_GET["sort"] == "id" ? "selected" : "") . ">Added</option>"; echo "<option value='name'" . ($_GET["sort"] == "name" ? "selected" : "") . ">Name</option>"; echo "<option value='comments'" . ($_GET["sort"] == "comments" ? "selected" : "") . ">Comments</option>"; echo "<option value='size'" . ($_GET["sort"] == "size" ? "selected" : "") . ">Size</option>"; echo "<option value='times_completed'" . ($_GET["sort"] == "times_completed" ? "selected" : "") . ">Completed</option>"; echo "<option value='seeders'" . ($_GET["sort"] == "seeders" ? "selected" : "") . ">Seeders</option>"; echo "<option value='leechers'" . ($_GET["sort"] == "leechers" ? "selected" : "") . ">Leechers</option>"; echo "</select>&nbsp;"; echo "<select name='order' onChange='document.jump.submit();' style=\"font-family: Verdana; font-size: 8pt; border: 1px solid #000000; background-color: #CCCCCC\" size=\"1\">"; echo "<option selected value='asc'" . ($_GET["order"] == "asc" ? "selected" : "") . ">Ascend</option>"; echo "<option value='desc'" . ($_GET["order"] == "desc" ? "selected" : "") . ">Descend</option>"; echo "</select>"; echo "</form>"; echo "</div>"; ********** OLD CODE *************/ if ($count) { // New code (TorrentialStorm) echo "<div align=right><form id='sort'>".SORT_BY.": <select name='sort' onChange='window.location=\"{$thisurl}sort=\"+this.options[this.selectedIndex].value+\"&order=\"+document.forms[\"sort\"].order.options[document.forms[\"sort\"].order.selectedIndex].value' style=\"font-family: Verdana; font-size: 8pt; border: 1px solid #000000; background-color: #CCCCCC\" size=\"1\">"; echo "<option value='id'" . ($_GET["sort"] == "id" ? "selected" : "") . ">".ADDED."</option>"; echo "<option value='name'" . ($_GET["sort"] == "name" ? "selected" : "") . ">".NAME."</option>"; echo "<option value='comments'" . ($_GET["sort"] == "comments" ? "selected" : "") . ">".COMMENTS."</option>"; echo "<option value='size'" . ($_GET["sort"] == "size" ? "selected" : "") . ">".SIZE."</option>"; echo "<option value='times_completed'" . ($_GET["sort"] == "times_completed" ? "selected" : "") . ">".COMPLETED."</option>"; echo "<option value='seeders'" . ($_GET["sort"] == "seeders" ? "selected" : "") . ">".SEEDS."</option>"; echo "<option value='leechers'" . ($_GET["sort"] == "leechers" ? "selected" : "") . ">".LEECH."</option>"; echo "</select>&nbsp;"; echo "<select name='order' onChange='window.location=\"{$thisurl}order=\"+this.options[this.selectedIndex].value+\"&sort=\"+document.forms[\"sort\"].sort.options[document.forms[\"sort\"].sort.selectedIndex].value' style=\"font-family: Verdana; font-size: 8pt; border: 1px solid #000000; background-color: #CCCCCC\" size=\"1\">"; echo "<option selected value='asc'" . ($_GET["order"] == "asc" ? "selected" : "") . ">".ASCEND."</option>"; echo "<option value='desc'" . ($_GET["order"] == "desc" ? "selected" : "") . ">".DESCEND."</option>"; echo "</select>"; echo "</form></div>"; // End torrenttable($res); print($pagerbottom); }else { show_error_msg("" . NOTHING_FOUND . "", "" . NO_RESULTS . "",0); } if ($CURUSER) mysql_query("UPDATE users SET last_browse=".gmtime()." WHERE id=$CURUSER[id]"); end_frame(); stdfoot(); ?>
BamBam0077/TorrentTrader-2.06
torrents-search.php
PHP
gpl-3.0
13,485
# -*- coding: utf-8 -*- from django.db import models from django.utils.translation import ugettext_lazy as _ from redsolutioncms.models import CMSSettings, BaseSettings, BaseSettingsManager FIELD_TYPES = ( ('BooleanField', _('Checkbox')), ('CharField', _('Character field')), ('Text', _('Text area')), ('EmailField', _('Email field')), ) class FeedbackSettingsManager(BaseSettingsManager): def get_settings(self): if self.get_query_set().count(): return self.get_query_set()[0] else: feedback_settings = self.get_query_set().create() # cms_settings = CMSSettings.objects.get_settings() return feedback_settings class FeedbackSettings(BaseSettings): # use_direct_view = models.BooleanField( # verbose_name=_('Use dedicated view to render feedback page'), # default=True # ) # Temporary hadrcoded use_direct_view = True use_custom_form = models.BooleanField(verbose_name=_('Use custom feedback form'), default=False) objects = FeedbackSettingsManager() class FormField(models.Model): feedback_settings = models.ForeignKey('FeedbackSettings') field_type = models.CharField(verbose_name=_('Type of field'), choices=FIELD_TYPES, max_length=255) field_name = models.CharField(verbose_name=_('Verbose name of field'), max_length=255)
redsolution/django-simple-feedback
feedback/redsolution_setup/models.py
Python
gpl-3.0
1,391
/*============================================================================== * File $Id$ * Project: ProWim * * $LastChangedDate: 2010-07-19 17:01:15 +0200 (Mon, 19 Jul 2010) $ * $LastChangedBy: wardi $ * $HeadURL: https://repository.ebcot.info/wivu/trunk/prowim-server/src/de/ebcot/prowim/datamodel/prowim/ProcessElement.java $ * $LastChangedRevision: 4323 $ *------------------------------------------------------------------------------ * (c) 06.08.2009 Ebcot Business Solutions GmbH. More info: http://www.ebcot.de * All rights reserved. Use is subject to license terms. *============================================================================== * *This file is part of ProWim. ProWim is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ProWim is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with ProWim. If not, see <http://www.gnu.org/licenses/>. Diese Datei ist Teil von ProWim. ProWim ist Freie Software: Sie können es unter den Bedingungen der GNU General Public License, wie von der Free Software Foundation, Version 3 der Lizenz oder (nach Ihrer Option) jeder späteren veröffentlichten Version, weiterverbreiten und/oder modifizieren. ProWim wird in der Hoffnung, dass es nützlich sein wird, aber OHNE JEDE GEWÄHELEISTUNG, bereitgestellt; sogar ohne die implizite Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK. Siehe die GNU General Public License für weitere Details. Sie sollten eine Kopie der GNU General Public License zusammen mit diesem Programm erhalten haben. Wenn nicht, siehe <http://www.gnu.org/licenses/>. */ package org.prowim.datamodel.prowim; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import org.apache.commons.lang.StringEscapeUtils; import org.apache.commons.lang.Validate; import org.prowim.datamodel.collections.StringArray; import org.prowim.utils.JSONConvertible; /** * This is a data object as parent for all process element objects.<br> * A process element is an element of a {@link Process process} * * @author Saad Wardi * @version $Revision: 4323 $ */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ProcessElement", propOrder = { "id", "name", "createTime", "description", "className", "keyWords" }) public class ProcessElement implements JSONConvertible { private String id; private String name; private String createTime; private String description; private String className; private StringArray keyWords = new StringArray(); /** * Creates a ProcessElement. * * @param id {@link ProcessElement#setID(String)} * @param name {@link ProcessElement#setName(String)} * @param createTime {@link ProcessElement#setCreateTime(String)} */ protected ProcessElement(String id, String name, String createTime) { setID(id); setName(name); setCreateTime(createTime); } /** * This non-arg constructor is needed to bind this DataObject in EJB-Context. See the J2EE specification. */ protected ProcessElement() { } /** * ProcessElementement#setID(String)} * * @return the id . not null */ public String getID() { return id; } /** * Sets the ID of the template to a ProcessElement instance. * * @param id the not null ID to set */ private void setID(String id) { Validate.notNull(id); this.id = id; } /** * {@link ProcessElement#setName(String)} * * @return the name . not null */ public String getName() { return name; } /** * Sets the name of the template to a ProcessElement instance. * * @param name the not null name to set */ public void setName(String name) { Validate.notNull(name); this.name = name; } /** * {@link ProcessElement#setCreateTime(String)} * * @return the createTime */ public String getCreateTime() { return createTime; } /** * Sets the name of the template to a ProcessElement instance. * * @param createTime the not null createTime to set. */ private void setCreateTime(String createTime) { Validate.notNull(createTime); this.createTime = createTime; } /** * Gets the value of the description property. * * @return possible object is {@link String}. cann be null if no description is specified. * */ public String getDescription() { return description; } /** * Sets the value of the description property. * * @param value allowed object is {@link String}. null is possible. * */ public void setDescription(String value) { this.description = value; } /** * {@inheritDoc} * * @see java.lang.Object#toString() */ @Override public String toString() { return this.getName(); } /** * * {@inheritDoc} * * @see org.prowim.utils.JSONConvertible#toJSON() */ public String toJSON() { StringBuilder builder = new StringBuilder(); builder.append("{"); builder.append("className:\""); builder.append(StringEscapeUtils.escapeJavaScript(this.getClassName())); builder.append("\","); builder.append("name:\""); builder.append(StringEscapeUtils.escapeJavaScript(this.getName())); builder.append("\","); builder.append("description:\""); builder.append(StringEscapeUtils.escapeJavaScript(this.getDescription())); builder.append("\","); builder.append("id:\""); builder.append(StringEscapeUtils.escapeJavaScript(this.getID())); builder.append("\"}"); return builder.toString(); } /** * Sets the class name of the concrete instance * * @param className the className to set */ public void setClassName(String className) { this.className = className; } /** * Gets the class name of the concrete instance * * @return the className, can be <code>NULL</code> */ public String getClassName() { return className; } /** * Sets a list of key words for element * * @param keyWords the keyWords to set */ public void setKeyWords(StringArray keyWords) { this.keyWords = keyWords; } /** * Get all key words of this element * * @return the keyWords */ public StringArray getKeyWords() { return keyWords; } /** * * Add the given key word to the list of key words. It can not be null. * * @param keyWord a key word for given element. Not null. */ public void addKeyWord(String keyWord) { Validate.notNull(keyWord, "Key word can not be null."); this.keyWords.add(keyWord); } }
prowim/prowim
prowim-data/src/org/prowim/datamodel/prowim/ProcessElement.java
Java
gpl-3.0
7,775
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals """ oauthlib.oauth1.rfc5849 ~~~~~~~~~~~~~~ This module is an implementation of various logic needed for signing and checking OAuth 1.0 RFC 5849 requests. """ import logging log = logging.getLogger("oauthlib") import sys import time try: import urlparse except ImportError: import urllib.parse as urlparse if sys.version_info[0] == 3: bytes_type = bytes else: bytes_type = str from ...common import Request, urlencode, generate_nonce from ...common import generate_timestamp, to_unicode from . import parameters, signature, utils SIGNATURE_HMAC = "HMAC-SHA1" SIGNATURE_RSA = "RSA-SHA1" SIGNATURE_PLAINTEXT = "PLAINTEXT" SIGNATURE_METHODS = (SIGNATURE_HMAC, SIGNATURE_RSA, SIGNATURE_PLAINTEXT) SIGNATURE_TYPE_AUTH_HEADER = 'AUTH_HEADER' SIGNATURE_TYPE_QUERY = 'QUERY' SIGNATURE_TYPE_BODY = 'BODY' CONTENT_TYPE_FORM_URLENCODED = 'application/x-www-form-urlencoded' class Client(object): """A client used to sign OAuth 1.0 RFC 5849 requests""" def __init__(self, client_key, client_secret=None, resource_owner_key=None, resource_owner_secret=None, callback_uri=None, signature_method=SIGNATURE_HMAC, signature_type=SIGNATURE_TYPE_AUTH_HEADER, rsa_key=None, verifier=None, realm=None, encoding='utf-8', decoding=None, nonce=None, timestamp=None): """Create an OAuth 1 client. :param client_key: Client key (consumer key), mandatory. :param resource_owner_key: Resource owner key (oauth token). :param resource_owner_secret: Resource owner secret (oauth token secret). :param callback_uri: Callback used when obtaining request token. :param signature_method: SIGNATURE_HMAC, SIGNATURE_RSA or SIGNATURE_PLAINTEXT. :param signature_type: SIGNATURE_TYPE_AUTH_HEADER (default), SIGNATURE_TYPE_QUERY or SIGNATURE_TYPE_BODY depending on where you want to embed the oauth credentials. :param rsa_key: RSA key used with SIGNATURE_RSA. :param verifier: Verifier used when obtaining an access token. :param realm: Realm (scope) to which access is being requested. :param encoding: If you provide non-unicode input you may use this to have oauthlib automatically convert. :param decoding: If you wish that the returned uri, headers and body from sign be encoded back from unicode, then set decoding to your preferred encoding, i.e. utf-8. :param nonce: Use this nonce instead of generating one. (Mainly for testing) :param timestamp: Use this timestamp instead of using current. (Mainly for testing) """ # Convert to unicode using encoding if given, else assume unicode encode = lambda x: to_unicode(x, encoding) if encoding else x self.client_key = encode(client_key) self.client_secret = encode(client_secret) self.resource_owner_key = encode(resource_owner_key) self.resource_owner_secret = encode(resource_owner_secret) self.signature_method = encode(signature_method) self.signature_type = encode(signature_type) self.callback_uri = encode(callback_uri) self.rsa_key = encode(rsa_key) self.verifier = encode(verifier) self.realm = encode(realm) self.encoding = encode(encoding) self.decoding = encode(decoding) self.nonce = encode(nonce) self.timestamp = encode(timestamp) if self.signature_method == SIGNATURE_RSA and self.rsa_key is None: raise ValueError('rsa_key is required when using RSA signature method.') def get_oauth_signature(self, request): """Get an OAuth signature to be used in signing a request """ if self.signature_method == SIGNATURE_PLAINTEXT: # fast-path return signature.sign_plaintext(self.client_secret, self.resource_owner_secret) uri, headers, body = self._render(request) collected_params = signature.collect_parameters( uri_query=urlparse.urlparse(uri).query, body=body, headers=headers) log.debug("Collected params: {0}".format(collected_params)) normalized_params = signature.normalize_parameters(collected_params) normalized_uri = signature.normalize_base_string_uri(request.uri) log.debug("Normalized params: {0}".format(normalized_params)) log.debug("Normalized URI: {0}".format(normalized_uri)) base_string = signature.construct_base_string(request.http_method, normalized_uri, normalized_params) log.debug("Base signing string: {0}".format(base_string)) if self.signature_method == SIGNATURE_HMAC: sig = signature.sign_hmac_sha1(base_string, self.client_secret, self.resource_owner_secret) elif self.signature_method == SIGNATURE_RSA: sig = signature.sign_rsa_sha1(base_string, self.rsa_key) else: sig = signature.sign_plaintext(self.client_secret, self.resource_owner_secret) log.debug("Signature: {0}".format(sig)) return sig def get_oauth_params(self): """Get the basic OAuth parameters to be used in generating a signature. """ nonce = (generate_nonce() if self.nonce is None else self.nonce) timestamp = (generate_timestamp() if self.timestamp is None else self.timestamp) params = [ ('oauth_nonce', nonce), ('oauth_timestamp', timestamp), ('oauth_version', '1.0'), ('oauth_signature_method', self.signature_method), ('oauth_consumer_key', self.client_key), ] if self.resource_owner_key: params.append(('oauth_token', self.resource_owner_key)) if self.callback_uri: params.append(('oauth_callback', self.callback_uri)) if self.verifier: params.append(('oauth_verifier', self.verifier)) return params def _render(self, request, formencode=False, realm=None): """Render a signed request according to signature type Returns a 3-tuple containing the request URI, headers, and body. If the formencode argument is True and the body contains parameters, it is escaped and returned as a valid formencoded string. """ # TODO what if there are body params on a header-type auth? # TODO what if there are query params on a body-type auth? uri, headers, body = request.uri, request.headers, request.body # TODO: right now these prepare_* methods are very narrow in scope--they # only affect their little thing. In some cases (for example, with # header auth) it might be advantageous to allow these methods to touch # other parts of the request, like the headers—so the prepare_headers # method could also set the Content-Type header to x-www-form-urlencoded # like the spec requires. This would be a fundamental change though, and # I'm not sure how I feel about it. if self.signature_type == SIGNATURE_TYPE_AUTH_HEADER: headers = parameters.prepare_headers(request.oauth_params, request.headers, realm=realm) elif self.signature_type == SIGNATURE_TYPE_BODY and request.decoded_body is not None: body = parameters.prepare_form_encoded_body(request.oauth_params, request.decoded_body) if formencode: body = urlencode(body) headers['Content-Type'] = 'application/x-www-form-urlencoded' elif self.signature_type == SIGNATURE_TYPE_QUERY: uri = parameters.prepare_request_uri_query(request.oauth_params, request.uri) else: raise ValueError('Unknown signature type specified.') return uri, headers, body def sign(self, uri, http_method='GET', body=None, headers=None, realm=None): """Sign a request Signs an HTTP request with the specified parts. Returns a 3-tuple of the signed request's URI, headers, and body. Note that http_method is not returned as it is unaffected by the OAuth signing process. Also worth noting is that duplicate parameters will be included in the signature, regardless of where they are specified (query, body). The body argument may be a dict, a list of 2-tuples, or a formencoded string. The Content-Type header must be 'application/x-www-form-urlencoded' if it is present. If the body argument is not one of the above, it will be returned verbatim as it is unaffected by the OAuth signing process. Attempting to sign a request with non-formencoded data using the OAuth body signature type is invalid and will raise an exception. If the body does contain parameters, it will be returned as a properly- formatted formencoded string. Body may not be included if the http_method is either GET or HEAD as this changes the semantic meaning of the request. All string data MUST be unicode or be encoded with the same encoding scheme supplied to the Client constructor, default utf-8. This includes strings inside body dicts, for example. """ # normalize request data request = Request(uri, http_method, body, headers, encoding=self.encoding) # sanity check content_type = request.headers.get('Content-Type', None) multipart = content_type and content_type.startswith('multipart/') should_have_params = content_type == CONTENT_TYPE_FORM_URLENCODED has_params = request.decoded_body is not None # 3.4.1.3.1. Parameter Sources # [Parameters are collected from the HTTP request entity-body, but only # if [...]: # * The entity-body is single-part. if multipart and has_params: raise ValueError("Headers indicate a multipart body but body contains parameters.") # * The entity-body follows the encoding requirements of the # "application/x-www-form-urlencoded" content-type as defined by # [W3C.REC-html40-19980424]. elif should_have_params and not has_params: raise ValueError("Headers indicate a formencoded body but body was not decodable.") # * The HTTP request entity-header includes the "Content-Type" # header field set to "application/x-www-form-urlencoded". elif not should_have_params and has_params: raise ValueError("Body contains parameters but Content-Type header was not set.") # 3.5.2. Form-Encoded Body # Protocol parameters can be transmitted in the HTTP request entity- # body, but only if the following REQUIRED conditions are met: # o The entity-body is single-part. # o The entity-body follows the encoding requirements of the # "application/x-www-form-urlencoded" content-type as defined by # [W3C.REC-html40-19980424]. # o The HTTP request entity-header includes the "Content-Type" header # field set to "application/x-www-form-urlencoded". elif self.signature_type == SIGNATURE_TYPE_BODY and not ( should_have_params and has_params and not multipart): raise ValueError('Body signatures may only be used with form-urlencoded content') # We amend http://tools.ietf.org/html/rfc5849#section-3.4.1.3.1 # with the clause that parameters from body should only be included # in non GET or HEAD requests. Extracting the request body parameters # and including them in the signature base string would give semantic # meaning to the body, which it should not have according to the # HTTP 1.1 spec. elif http_method.upper() in ('GET', 'HEAD') and has_params: raise ValueError('GET/HEAD requests should not include body.') # generate the basic OAuth parameters request.oauth_params = self.get_oauth_params() # generate the signature request.oauth_params.append(('oauth_signature', self.get_oauth_signature(request))) # render the signed request and return it uri, headers, body = self._render(request, formencode=True, realm=(realm or self.realm)) if self.decoding: log.debug('Encoding URI, headers and body to %s.', self.decoding) uri = uri.encode(self.decoding) body = body.encode(self.decoding) if body else body new_headers = {} for k, v in headers.items(): new_headers[k.encode(self.decoding)] = v.encode(self.decoding) headers = new_headers return uri, headers, body class Server(object): """A server base class used to verify OAuth 1.0 RFC 5849 requests OAuth providers should inherit from Server and implement the methods and properties outlined below. Further details are provided in the documentation for each method and property. Methods used to check the format of input parameters. Common tests include length, character set, membership, range or pattern. These tests are referred to as `whitelisting or blacklisting`_. Whitelisting is better but blacklisting can be usefull to spot malicious activity. The following have methods a default implementation: - check_client_key - check_request_token - check_access_token - check_nonce - check_verifier - check_realm The methods above default to whitelist input parameters, checking that they are alphanumerical and between a minimum and maximum length. Rather than overloading the methods a few properties can be used to configure these methods. * @safe_characters -> (character set) * @client_key_length -> (min, max) * @request_token_length -> (min, max) * @access_token_length -> (min, max) * @nonce_length -> (min, max) * @verifier_length -> (min, max) * @realms -> [list, of, realms] Methods used to validate input parameters. These checks usually hit either persistent or temporary storage such as databases or the filesystem. See each methods documentation for detailed usage. The following methods must be implemented: - validate_client_key - validate_request_token - validate_access_token - validate_timestamp_and_nonce - validate_redirect_uri - validate_requested_realm - validate_realm - validate_verifier Method used to retrieve sensitive information from storage. The following methods must be implemented: - get_client_secret - get_request_token_secret - get_access_token_secret - get_rsa_key To prevent timing attacks it is necessary to not exit early even if the client key or resource owner key is invalid. Instead dummy values should be used during the remaining verification process. It is very important that the dummy client and token are valid input parameters to the methods get_client_secret, get_rsa_key and get_(access/request)_token_secret and that the running time of those methods when given a dummy value remain equivalent to the running time when given a valid client/resource owner. The following properties must be implemented: * @dummy_client * @dummy_request_token * @dummy_access_token Example implementations have been provided, note that the database used is a simple dictionary and serves only an illustrative purpose. Use whichever database suits your project and how to access it is entirely up to you. The methods are introduced in an order which should make understanding their use more straightforward and as such it could be worth reading what follows in chronological order. .. _`whitelisting or blacklisting`: http://www.schneier.com/blog/archives/2011/01/whitelisting_vs.html """ def __init__(self): pass @property def allowed_signature_methods(self): return SIGNATURE_METHODS @property def safe_characters(self): return set(utils.UNICODE_ASCII_CHARACTER_SET) @property def client_key_length(self): return 20, 30 @property def request_token_length(self): return 20, 30 @property def access_token_length(self): return 20, 30 @property def timestamp_lifetime(self): return 600 @property def nonce_length(self): return 20, 30 @property def verifier_length(self): return 20, 30 @property def realms(self): return [] @property def enforce_ssl(self): return True def check_client_key(self, client_key): """Check that the client key only contains safe characters and is no shorter than lower and no longer than upper. """ lower, upper = self.client_key_length return (set(client_key) <= self.safe_characters and lower <= len(client_key) <= upper) def check_request_token(self, request_token): """Checks that the request token contains only safe characters and is no shorter than lower and no longer than upper. """ lower, upper = self.request_token_length return (set(request_token) <= self.safe_characters and lower <= len(request_token) <= upper) def check_access_token(self, request_token): """Checks that the token contains only safe characters and is no shorter than lower and no longer than upper. """ lower, upper = self.access_token_length return (set(request_token) <= self.safe_characters and lower <= len(request_token) <= upper) def check_nonce(self, nonce): """Checks that the nonce only contains only safe characters and is no shorter than lower and no longer than upper. """ lower, upper = self.nonce_length return (set(nonce) <= self.safe_characters and lower <= len(nonce) <= upper) def check_verifier(self, verifier): """Checks that the verifier contains only safe characters and is no shorter than lower and no longer than upper. """ lower, upper = self.verifier_length return (set(verifier) <= self.safe_characters and lower <= len(verifier) <= upper) def check_realm(self, realm): """Check that the realm is one of a set allowed realms. """ return realm in self.realms def get_client_secret(self, client_key): """Retrieves the client secret associated with the client key. This method must allow the use of a dummy client_key value. Fetching the secret using the dummy key must take the same amount of time as fetching a secret for a valid client:: # Unlikely to be near constant time as it uses two database # lookups for a valid client, and only one for an invalid. from your_datastore import ClientSecret if ClientSecret.has(client_key): return ClientSecret.get(client_key) else: return 'dummy' # Aim to mimic number of latency inducing operations no matter # whether the client is valid or not. from your_datastore import ClientSecret return ClientSecret.get(client_key, 'dummy') Note that the returned key must be in plaintext. """ raise NotImplementedError("Subclasses must implement this function.") @property def dummy_client(self): """Dummy client used when an invalid client key is supplied. The dummy client should be associated with either a client secret, a rsa key or both depending on which signature methods are supported. Providers should make sure that get_client_secret(dummy_client) get_rsa_key(dummy_client) return a valid secret or key for the dummy client. """ raise NotImplementedError("Subclasses must implement this function.") def get_request_token_secret(self, client_key, request_token): """Retrieves the shared secret associated with the request token. This method must allow the use of a dummy values and the running time must be roughly equivalent to that of the running time of valid values:: # Unlikely to be near constant time as it uses two database # lookups for a valid client, and only one for an invalid. from your_datastore import RequestTokenSecret if RequestTokenSecret.has(client_key): return RequestTokenSecret.get((client_key, request_token)) else: return 'dummy' # Aim to mimic number of latency inducing operations no matter # whether the client is valid or not. from your_datastore import RequestTokenSecret return ClientSecret.get((client_key, request_token), 'dummy') Note that the returned key must be in plaintext. """ raise NotImplementedError("Subclasses must implement this function.") def get_access_token_secret(self, client_key, access_token): """Retrieves the shared secret associated with the access token. This method must allow the use of a dummy values and the running time must be roughly equivalent to that of the running time of valid values:: # Unlikely to be near constant time as it uses two database # lookups for a valid client, and only one for an invalid. from your_datastore import AccessTokenSecret if AccessTokenSecret.has(client_key): return AccessTokenSecret.get((client_key, request_token)) else: return 'dummy' # Aim to mimic number of latency inducing operations no matter # whether the client is valid or not. from your_datastore import AccessTokenSecret return ClientSecret.get((client_key, request_token), 'dummy') Note that the returned key must be in plaintext. """ raise NotImplementedError("Subclasses must implement this function.") @property def dummy_request_token(self): """Dummy request token used when an invalid token was supplied. The dummy request token should be associated with a request token secret such that get_request_token_secret(.., dummy_request_token) returns a valid secret. """ raise NotImplementedError("Subclasses must implement this function.") @property def dummy_access_token(self): """Dummy access token used when an invalid token was supplied. The dummy access token should be associated with an access token secret such that get_access_token_secret(.., dummy_access_token) returns a valid secret. """ raise NotImplementedError("Subclasses must implement this function.") def get_rsa_key(self, client_key): """Retrieves a previously stored client provided RSA key. This method must allow the use of a dummy client_key value. Fetching the rsa key using the dummy key must take the same amount of time as fetching a key for a valid client. The dummy key must also be of the same bit length as client keys. Note that the key must be returned in plaintext. """ raise NotImplementedError("Subclasses must implement this function.") def _get_signature_type_and_params(self, request): """Extracts parameters from query, headers and body. Signature type is set to the source in which parameters were found. """ # Per RFC5849, only the Authorization header may contain the 'realm' optional parameter. header_params = signature.collect_parameters(headers=request.headers, exclude_oauth_signature=False, with_realm=True) body_params = signature.collect_parameters(body=request.body, exclude_oauth_signature=False) query_params = signature.collect_parameters(uri_query=request.uri_query, exclude_oauth_signature=False) params = [] params.extend(header_params) params.extend(body_params) params.extend(query_params) signature_types_with_oauth_params = list(filter(lambda s: s[2], ( (SIGNATURE_TYPE_AUTH_HEADER, params, utils.filter_oauth_params(header_params)), (SIGNATURE_TYPE_BODY, params, utils.filter_oauth_params(body_params)), (SIGNATURE_TYPE_QUERY, params, utils.filter_oauth_params(query_params)) ))) if len(signature_types_with_oauth_params) > 1: raise ValueError('oauth_ params must come from only 1 signature type but were found in %s' % ', '.join( [s[0] for s in signature_types_with_oauth_params])) try: signature_type, params, oauth_params = signature_types_with_oauth_params[0] except IndexError: raise ValueError('oauth_ params are missing. Could not determine signature type.') return signature_type, params, oauth_params def validate_client_key(self, client_key): """Validates that supplied client key is a registered and valid client. Note that if the dummy client is supplied it should validate in same or nearly the same amount of time as a valid one. Ensure latency inducing tasks are mimiced even for dummy clients. For example, use:: from your_datastore import Client try: return Client.exists(client_key, access_token) except DoesNotExist: return False Rather than:: from your_datastore import Client if access_token == self.dummy_access_token: return False else: return Client.exists(client_key, access_token) """ raise NotImplementedError("Subclasses must implement this function.") def validate_request_token(self, client_key, request_token): """Validates that supplied request token is registered and valid. Note that if the dummy request_token is supplied it should validate in the same nearly the same amount of time as a valid one. Ensure latency inducing tasks are mimiced even for dummy clients. For example, use:: from your_datastore import RequestToken try: return RequestToken.exists(client_key, access_token) except DoesNotExist: return False Rather than:: from your_datastore import RequestToken if access_token == self.dummy_access_token: return False else: return RequestToken.exists(client_key, access_token) """ raise NotImplementedError("Subclasses must implement this function.") def validate_access_token(self, client_key, access_token): """Validates that supplied access token is registered and valid. Note that if the dummy access token is supplied it should validate in the same or nearly the same amount of time as a valid one. Ensure latency inducing tasks are mimiced even for dummy clients. For example, use:: from your_datastore import AccessToken try: return AccessToken.exists(client_key, access_token) except DoesNotExist: return False Rather than:: from your_datastore import AccessToken if access_token == self.dummy_access_token: return False else: return AccessToken.exists(client_key, access_token) """ raise NotImplementedError("Subclasses must implement this function.") def validate_timestamp_and_nonce(self, client_key, timestamp, nonce, request_token=None, access_token=None): """Validates that the nonce has not been used before. Per `Section 3.3`_ of the spec. "A nonce is a random string, uniquely generated by the client to allow the server to verify that a request has never been made before and helps prevent replay attacks when requests are made over a non-secure channel. The nonce value MUST be unique across all requests with the same timestamp, client credentials, and token combinations." .. _`Section 3.3`: http://tools.ietf.org/html/rfc5849#section-3.3 One of the first validation checks that will be made is for the validity of the nonce and timestamp, which are associated with a client key and possibly a token. If invalid then immediately fail the request by returning False. If the nonce/timestamp pair has been used before and you may just have detected a replay attack. Therefore it is an essential part of OAuth security that you not allow nonce/timestamp reuse. Note that this validation check is done before checking the validity of the client and token.:: nonces_and_timestamps_database = [ (u'foo', 1234567890, u'rannoMstrInghere', u'bar') ] def validate_timestamp_and_nonce(self, client_key, timestamp, nonce, request_token=None, access_token=None): return ((client_key, timestamp, nonce, request_token or access_token) in self.nonces_and_timestamps_database) """ raise NotImplementedError("Subclasses must implement this function.") def validate_redirect_uri(self, client_key, redirect_uri): """Validates the client supplied redirection URI. It is highly recommended that OAuth providers require their clients to register all redirection URIs prior to using them in requests and register them as absolute URIs. See `CWE-601`_ for more information about open redirection attacks. By requiring registration of all redirection URIs it should be straightforward for the provider to verify whether the supplied redirect_uri is valid or not. Alternatively per `Section 2.1`_ of the spec: "If the client is unable to receive callbacks or a callback URI has been established via other means, the parameter value MUST be set to "oob" (case sensitive), to indicate an out-of-band configuration." .. _`CWE-601`: http://cwe.mitre.org/top25/index.html#CWE-601 .. _`Section 2.1`: https://tools.ietf.org/html/rfc5849#section-2.1 """ raise NotImplementedError("Subclasses must implement this function.") def validate_requested_realm(self, client_key, realm): """Validates that the client may request access to the realm. This method is invoked when obtaining a request token and should tie a realm to the request token and after user authorization this realm restriction should transfer to the access token. """ raise NotImplementedError("Subclasses must implement this function.") def validate_realm(self, client_key, access_token, uri=None, required_realm=None): """Validates access to the request realm. How providers choose to use the realm parameter is outside the OAuth specification but it is commonly used to restrict access to a subset of protected resources such as "photos". required_realm is a convenience parameter which can be used to provide a per view method pre-defined list of allowed realms. """ raise NotImplementedError("Subclasses must implement this function.") def validate_verifier(self, client_key, request_token, verifier): """Validates a verification code. OAuth providers issue a verification code to clients after the resource owner authorizes access. This code is used by the client to obtain token credentials and the provider must verify that the verifier is valid and associated with the client as well as the resource owner. Verifier validation should be done in near constant time (to avoid verifier enumeration). To achieve this we need a constant time string comparison which is provided by OAuthLib in ``oauthlib.common.safe_string_equals``:: from your_datastore import Verifier correct_verifier = Verifier.get(client_key, request_token) from oauthlib.common import safe_string_equals return safe_string_equals(verifier, correct_verifier) """ raise NotImplementedError("Subclasses must implement this function.") def verify_request_token_request(self, uri, http_method='GET', body=None, headers=None): """Verify the initial request in the OAuth workflow. During this step the client obtains a request token for use during resource owner authorization (which is outside the scope of oauthlib). """ return self.verify_request(uri, http_method=http_method, body=body, headers=headers, require_resource_owner=False, require_realm=True, require_callback=True) def verify_access_token_request(self, uri, http_method='GET', body=None, headers=None): """Verify the second request in the OAuth workflow. During this step the client obtains the access token for use when accessing protected resources. """ return self.verify_request(uri, http_method=http_method, body=body, headers=headers, require_verifier=True) def verify_request(self, uri, http_method='GET', body=None, headers=None, require_resource_owner=True, require_verifier=False, require_realm=False, required_realm=None, require_callback=False): """Verifies a request ensuring that the following is true: Per `section 3.2`_ of the spec. - all mandated OAuth parameters are supplied - parameters are only supplied in one source which may be the URI query, the Authorization header or the body - all parameters are checked and validated, see comments and the methods and properties of this class for further details. - the supplied signature is verified against a recalculated one A ValueError will be raised if any parameter is missing, supplied twice or invalid. A HTTP 400 Response should be returned upon catching an exception. A HTTP 401 Response should be returned if verify_request returns False. `Timing attacks`_ are prevented through the use of dummy credentials to create near constant time verification even if an invalid credential is used. Early exit on invalid credentials would enable attackers to perform `enumeration attacks`_. Near constant time string comparison is used to prevent secret key guessing. Note that timing attacks can only be prevented through near constant time execution, not by adding a random delay which would only require more samples to be gathered. .. _`section 3.2`: http://tools.ietf.org/html/rfc5849#section-3.2 .. _`Timing attacks`: http://rdist.root.org/2010/07/19/exploiting-remote-timing-attacks/ .. _`enumeration attacks`: http://www.sans.edu/research/security-laboratory/article/attacks-browsing """ # Only include body data from x-www-form-urlencoded requests headers = headers or {} if ("Content-Type" in headers and headers["Content-Type"] == CONTENT_TYPE_FORM_URLENCODED): request = Request(uri, http_method, body, headers) else: request = Request(uri, http_method, '', headers) if self.enforce_ssl and not request.uri.lower().startswith("https://"): raise ValueError("Insecure transport, only HTTPS is allowed.") signature_type, params, oauth_params = self._get_signature_type_and_params(request) # The server SHOULD return a 400 (Bad Request) status code when # receiving a request with duplicated protocol parameters. if len(dict(oauth_params)) != len(oauth_params): raise ValueError("Duplicate OAuth entries.") oauth_params = dict(oauth_params) request.signature = oauth_params.get('oauth_signature') request.client_key = oauth_params.get('oauth_consumer_key') request.resource_owner_key = oauth_params.get('oauth_token') request.nonce = oauth_params.get('oauth_nonce') request.timestamp = oauth_params.get('oauth_timestamp') request.callback_uri = oauth_params.get('oauth_callback') request.verifier = oauth_params.get('oauth_verifier') request.signature_method = oauth_params.get('oauth_signature_method') request.realm = dict(params).get('realm') # The server SHOULD return a 400 (Bad Request) status code when # receiving a request with missing parameters. if not all((request.signature, request.client_key, request.nonce, request.timestamp, request.signature_method)): raise ValueError("Missing OAuth parameters.") # OAuth does not mandate a particular signature method, as each # implementation can have its own unique requirements. Servers are # free to implement and document their own custom methods. # Recommending any particular method is beyond the scope of this # specification. Implementers should review the Security # Considerations section (`Section 4`_) before deciding on which # method to support. # .. _`Section 4`: http://tools.ietf.org/html/rfc5849#section-4 if not request.signature_method in self.allowed_signature_methods: raise ValueError("Invalid signature method.") # Servers receiving an authenticated request MUST validate it by: # If the "oauth_version" parameter is present, ensuring its value is # "1.0". if ('oauth_version' in request.oauth_params and request.oauth_params['oauth_version'] != '1.0'): raise ValueError("Invalid OAuth version.") # The timestamp value MUST be a positive integer. Unless otherwise # specified by the server's documentation, the timestamp is expressed # in the number of seconds since January 1, 1970 00:00:00 GMT. if len(request.timestamp) != 10: raise ValueError("Invalid timestamp size") try: ts = int(request.timestamp) except ValueError: raise ValueError("Timestamp must be an integer") else: # To avoid the need to retain an infinite number of nonce values for # future checks, servers MAY choose to restrict the time period after # which a request with an old timestamp is rejected. if time.time() - ts > self.timestamp_lifetime: raise ValueError("Request too old, over 10 minutes.") # Provider specific validation of parameters, used to enforce # restrictions such as character set and length. if not self.check_client_key(request.client_key): raise ValueError("Invalid client key.") if not request.resource_owner_key and require_resource_owner: raise ValueError("Missing resource owner.") if (require_resource_owner and not require_verifier and not self.check_access_token(request.resource_owner_key)): raise ValueError("Invalid resource owner key.") if (require_resource_owner and require_verifier and not self.check_request_token(request.resource_owner_key)): raise ValueError("Invalid resource owner key.") if not self.check_nonce(request.nonce): raise ValueError("Invalid nonce.") if request.realm and not self.check_realm(request.realm): raise ValueError("Invalid realm. Allowed are %s" % self.realms) if not request.verifier and require_verifier: raise ValueError("Missing verifier.") if require_verifier and not self.check_verifier(request.verifier): raise ValueError("Invalid verifier.") if require_callback and not request.callback_uri: raise ValueError("Missing callback URI.") # Servers receiving an authenticated request MUST validate it by: # If using the "HMAC-SHA1" or "RSA-SHA1" signature methods, ensuring # that the combination of nonce/timestamp/token (if present) # received from the client has not been used before in a previous # request (the server MAY reject requests with stale timestamps as # described in `Section 3.3`_). # .._`Section 3.3`: http://tools.ietf.org/html/rfc5849#section-3.3 # # We check this before validating client and resource owner for # increased security and performance, both gained by doing less work. if require_verifier: token = {"request_token": request.resource_owner_key} else: token = {"access_token": request.resource_owner_key} if not self.validate_timestamp_and_nonce(request.client_key, request.timestamp, request.nonce, **token): return False, request # The server SHOULD return a 401 (Unauthorized) status code when # receiving a request with invalid client credentials. # Note: This is postponed in order to avoid timing attacks, instead # a dummy client is assigned and used to maintain near constant # time request verification. # # Note that early exit would enable client enumeration valid_client = self.validate_client_key(request.client_key) if not valid_client: request.client_key = self.dummy_client # Callback is normally never required, except for requests for # a Temporary Credential as described in `Section 2.1`_ # .._`Section 2.1`: http://tools.ietf.org/html/rfc5849#section-2.1 if require_callback: valid_redirect = self.validate_redirect_uri(request.client_key, request.callback_uri) else: valid_redirect = True # The server SHOULD return a 401 (Unauthorized) status code when # receiving a request with invalid or expired token. # Note: This is postponed in order to avoid timing attacks, instead # a dummy token is assigned and used to maintain near constant # time request verification. # # Note that early exit would enable resource owner enumeration if request.resource_owner_key: if require_verifier: valid_resource_owner = self.validate_request_token( request.client_key, request.resource_owner_key) if not valid_resource_owner: request.resource_owner_key = self.dummy_request_token else: valid_resource_owner = self.validate_access_token( request.client_key, request.resource_owner_key) if not valid_resource_owner: request.resource_owner_key = self.dummy_access_token else: valid_resource_owner = True # Note that `realm`_ is only used in authorization headers and how # it should be interepreted is not included in the OAuth spec. # However they could be seen as a scope or realm to which the # client has access and as such every client should be checked # to ensure it is authorized access to that scope or realm. # .. _`realm`: http://tools.ietf.org/html/rfc2617#section-1.2 # # Note that early exit would enable client realm access enumeration. # # The require_realm indicates this is the first step in the OAuth # workflow where a client requests access to a specific realm. # This first step (obtaining request token) need not require a realm # and can then be identified by checking the require_resource_owner # flag and abscence of realm. # # Clients obtaining an access token will not supply a realm and it will # not be checked. Instead the previously requested realm should be # transferred from the request token to the access token. # # Access to protected resources will always validate the realm but note # that the realm is now tied to the access token and not provided by # the client. if ((require_realm and not request.resource_owner_key) or (not require_resource_owner and not request.realm)): valid_realm = self.validate_requested_realm(request.client_key, request.realm) elif require_verifier: valid_realm = True else: valid_realm = self.validate_realm(request.client_key, request.resource_owner_key, uri=request.uri, required_realm=required_realm) # The server MUST verify (Section 3.2) the validity of the request, # ensure that the resource owner has authorized the provisioning of # token credentials to the client, and ensure that the temporary # credentials have not expired or been used before. The server MUST # also verify the verification code received from the client. # .. _`Section 3.2`: http://tools.ietf.org/html/rfc5849#section-3.2 # # Note that early exit would enable resource owner authorization # verifier enumertion. if request.verifier: valid_verifier = self.validate_verifier(request.client_key, request.resource_owner_key, request.verifier) else: valid_verifier = True # Parameters to Client depend on signature method which may vary # for each request. Note that HMAC-SHA1 and PLAINTEXT share parameters request.params = filter(lambda x: x[0] not in ("oauth_signature", "realm"), params) # ---- RSA Signature verification ---- if request.signature_method == SIGNATURE_RSA: # The server verifies the signature per `[RFC3447] section 8.2.2`_ # .. _`[RFC3447] section 8.2.2`: http://tools.ietf.org/html/rfc3447#section-8.2.1 rsa_key = self.get_rsa_key(request.client_key) valid_signature = signature.verify_rsa_sha1(request, rsa_key) # ---- HMAC or Plaintext Signature verification ---- else: # Servers receiving an authenticated request MUST validate it by: # Recalculating the request signature independently as described in # `Section 3.4`_ and comparing it to the value received from the # client via the "oauth_signature" parameter. # .. _`Section 3.4`: http://tools.ietf.org/html/rfc5849#section-3.4 client_secret = self.get_client_secret(request.client_key) resource_owner_secret = None if require_resource_owner: if require_verifier: resource_owner_secret = self.get_request_token_secret( request.client_key, request.resource_owner_key) else: resource_owner_secret = self.get_access_token_secret( request.client_key, request.resource_owner_key) if request.signature_method == SIGNATURE_HMAC: valid_signature = signature.verify_hmac_sha1(request, client_secret, resource_owner_secret) else: valid_signature = signature.verify_plaintext(request, client_secret, resource_owner_secret) # We delay checking validity until the very end, using dummy values for # calculations and fetching secrets/keys to ensure the flow of every # request remains almost identical regardless of whether valid values # have been supplied. This ensures near constant time execution and # prevents malicious users from guessing sensitive information v = all((valid_client, valid_resource_owner, valid_realm, valid_redirect, valid_verifier, valid_signature)) if not v: log.info("[Failure] OAuthLib request verification failed.") log.info("Valid client:\t%s" % valid_client) log.info("Valid token:\t%s\t(Required: %s" % (valid_resource_owner, require_resource_owner)) log.info("Valid realm:\t%s\t(Required: %s)" % (valid_realm, require_realm)) log.info("Valid callback:\t%s" % valid_redirect) log.info("Valid verifier:\t%s\t(Required: %s)" % (valid_verifier, require_verifier)) log.info("Valid signature:\t%s" % valid_signature) return v, request
raqqun/tweetcommander
packages/oauthlib/oauth1/rfc5849/__init__.py
Python
gpl-3.0
49,724
/* * Copyright 2008 Michal Turek * * This file is part of Graphal library. * http://graphal.sourceforge.net/ * * Graphal library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, version 3 of the License. * * Graphal library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Graphal library. If not, see <http://www.gnu.org/licenses/>. */ /**************************************************************************** * * * This file was generated by gen_operators.pl script. * * Don't update it manually! * * * ****************************************************************************/ #include "generated/nodebinarydiv.h" #include "value.h" ///////////////////////////////////////////////////////////////////////////// //// NodeBinaryDiv::NodeBinaryDiv(Node* left, Node* right) : NodeBinary(left, right) { } NodeBinaryDiv::~NodeBinaryDiv(void) { } ///////////////////////////////////////////////////////////////////////////// //// CountPtr<Value> NodeBinaryDiv::execute(void) { return m_left->execute()->div(*(m_right->execute())); } void NodeBinaryDiv::dump(ostream& os, uint indent) const { dumpIndent(os, indent); os << "<NodeBinaryDiv>" << endl; m_left->dump(os, indent+1); m_right->dump(os, indent+1); dumpIndent(os, indent); os << "</NodeBinaryDiv>" << endl; } ostream& operator<<(ostream& os, const NodeBinaryDiv& node) { node.dump(os, 0); return os; }
mixalturek/graphal
libgraphal/generated/nodebinarydiv.cpp
C++
gpl-3.0
2,018
// Copyright (c) 2015 Contributors as noted in the AUTHORS file. // This file is part of form_factors. // // form_factors is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // form_factors is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with form_factors. If not, see <http://www.gnu.org/licenses/>. #include "TaskParser.h" TaskParser::TaskParser(onEndCb onEnd, onEndFrameCb onFrameEnd) : newFrame_re("^\\s{0,}newfrm\\s{1,}frame_(\\d+)$", regex_constants::icase), step_re("^\\s{0,}step\\s{1,}([\\d\\.]+)$"), tmp_re("^\\s{0,}tmprt\\s{1,}([\\d\\.]+)$", regex_constants::icase), comment_re("^\\s{0,}#.{0,}$", regex_constants::icase), curState(RUNNING) { assert(onEnd); assert(onFrameEnd); this->onEnd = onEnd; this->onFrameEnd = onFrameEnd; reset(); } void TaskParser::reset() { curFrame = 0; curState = RUNNING; curStep = 0; totalFrames = 0; } int TaskParser::onLine(string line) { // Check for comments first if (curState != ERROR && !line.empty() && regex_match(line, comment_re)) { return 0; } smatch match; switch (curState) { case (ERROR) : return -1; case (FINISHED) : return 0; case(RUNNING): if (line.empty()) { return 0; } else { if (regex_search(line, match, newFrame_re) && match.size() > 1) { curFrame = stoi(match.str(1), NULL); curState = FRAME; curStep = 0.0f; faceTemps.clear(); return 0; } else { return 0; } } case (FRAME): if (line.empty()) { curState = RUNNING; ++totalFrames; onFrameEnd(curFrame, totalFrames, curStep, faceTemps); return 0; } else if (regex_search(line, match, tmp_re) && match.size() > 1) { faceTemps.push_back(stof(match.str(1), NULL)); return 0; } else if (regex_search(line, match, step_re) && match.size() > 1) { curStep = stof(match.str(1), NULL); return 0; } default: return -1; } return -1; }
kroburg/form_factors
runner/TaskParser.cpp
C++
gpl-3.0
2,648
/* pMMF is an open source software library for efficiently computing the MMF factorization of large matrices. Copyright (C) 2015 Risi Kondor, Nedelina Teneva, Pramod Mudrakarta This file is part of pMMF. pMMF is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _DenseMatrixFileASCII #define _DenseMatrixFileASCII #include "DenseMatrixFile.hpp" class DenseMatrixFile::ASCII: public DenseMatrixFile { public: ASCII(const char* filename) { ifs.open(filename); if (ifs.fail()) { cout << "Failed to open " << filename << "." << endl; return; } char buffer[1024]; int linelength = 0; do { ifs.get(buffer, 1024); linelength += strlen(buffer); } while (strlen(buffer) > 0); cout << "Line length=" << linelength << endl; ifs.close(); ifs.open(filename); // why does ifs.seekg(0) not work? float b; ncols = 0; while (ifs.good() && ifs.tellg() < linelength) { ifs >> b; ncols++; } nrows = 0; while (ifs.good()) { for (int i = 0; i < ncols; i++) ifs >> b; nrows++; } cout << nrows << " " << ncols << endl; ifs.close(); ifs.open(filename); } DenseMatrixFile::iterator begin() { ifs.seekg(0); return DenseMatrixFile::iterator(*this); } void get(DenseMatrixFile::iterator& it) { if (!ifs.good()) { it.endflag = true; return; } it.endflag = false; ifs >> it.value; } DenseMatrixFile& operator>>(FIELD& dest) { if (ifs.good()) ifs >> dest; return *this; } }; // note: there is a potential problem when the file marker moves to eof, because seekg cannot reset it to beginning #endif
risi-kondor/pMMF
filetypes/DenseMatrixFileASCII.hpp
C++
gpl-3.0
2,198
/* * Copyright (C) 2008 J?lio Vilmar Gesser. * * This file is part of Java 1.5 parser and Abstract Syntax Tree. * * Java 1.5 parser and Abstract Syntax Tree is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Java 1.5 parser and Abstract Syntax Tree is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Java 1.5 parser and Abstract Syntax Tree. If not, see <http://www.gnu.org/licenses/>. */ /* * Created on 05/10/2006 */ package japa.parser; import japa.parser.ast.CompilationUnit; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; /** * <p>This class was generated automatically by javacc, do not edit.</p> * <p>Parse Java 1.5 source code and creates Abstract Syntax Tree classes.</p> * <p><b>Note:</b> To use this parser asynchronously, disable de parser cache * by calling the method {@link setCacheParser} with <code>false</code> * as argument.</p> * * @author J?lio Vilmar Gesser */ public final class JavaParser { private static ASTParser parser; private static boolean cacheParser = true; private JavaParser() { // hide the constructor } /** * Changes the way that the parser acts when starts to parse. If the * parser cache is enabled, only one insance of this object will be * used in every call to parse methods. * If this parser is intend to be used asynchonously, the cache must * be disabled setting this flag to <code>false</code>. * By default, the cache is enabled. * @param value <code>false</code> to disable the parser instance cache. */ public static void setCacheParser(boolean value) { cacheParser = value; if (!value) { parser = null; } } /** * Parses the Java code contained in the {@link InputStream} and returns * a {@link CompilationUnit} that represents it. * @param in {@link InputStream} containing Java source code * @param encoding encoding of the source code * @return CompilationUnit representing the Java source code * @throws ParseException if the source code has parser errors */ public static CompilationUnit parse(InputStream in, String encoding) throws ParseException { if (cacheParser) { if (parser == null) { parser = new ASTParser(in, encoding); } else { parser.reset(in, encoding); } return parser.CompilationUnit(); } return new ASTParser(in, encoding).CompilationUnit(); } /** * Parses the Java code contained in the {@link InputStream} and returns * a {@link CompilationUnit} that represents it. * @param in {@link InputStream} containing Java source code * @return CompilationUnit representing the Java source code * @throws ParseException if the source code has parser errors */ public static CompilationUnit parse(InputStream in) throws ParseException { return parse(in, null); } /** * Parses the Java code contained in a {@link File} and returns * a {@link CompilationUnit} that represents it. * @param file {@link File} containing Java source code * @param encoding encoding of the source code * @return CompilationUnit representing the Java source code * @throws ParseException if the source code has parser errors * @throws IOException */ public static CompilationUnit parse(File file, String encoding) throws ParseException, IOException { FileInputStream in = new FileInputStream(file); try { return parse(in, encoding); } finally { in.close(); } } /** * Parses the Java code contained in a {@link File} and returns * a {@link CompilationUnit} that represents it. * @param file {@link File} containing Java source code * @return CompilationUnit representing the Java source code * @throws ParseException if the source code has parser errors * @throws IOException */ public static CompilationUnit parse(File file) throws ParseException, IOException { return parse(file, null); } }
codesearch-github/codesearch
src/custom-libs/Codesearch-JavaParser/src/main/java/japa/parser/JavaParser.java
Java
gpl-3.0
4,813
/*------------------------------------------------------------------------ * * copyright : (C) 2008 by Benjamin Mueller * email : news@fork.ch * website : http://sourceforge.net/projects/adhocrailway * version : $Id: MemoryRoutePersistence.java 154 2008-03-28 14:30:54Z fork_ch $ * *----------------------------------------------------------------------*/ /*------------------------------------------------------------------------ * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * *----------------------------------------------------------------------*/ package ch.fork.adhocrailway.persistence.xml.impl; import java.util.SortedSet; import java.util.TreeSet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ch.fork.adhocrailway.model.turnouts.Route; import ch.fork.adhocrailway.model.turnouts.RouteGroup; import ch.fork.adhocrailway.model.turnouts.RouteItem; import ch.fork.adhocrailway.services.RouteService; import ch.fork.adhocrailway.services.RouteServiceListener; public class XMLRouteService implements RouteService { private static final Logger LOGGER = LoggerFactory.getLogger(XMLRouteService.class); private final SortedSet<Route> routes = new TreeSet<Route>(); private final SortedSet<RouteGroup> routeGroups = new TreeSet<RouteGroup>(); private RouteServiceListener listener; public XMLRouteService() { LOGGER.info("XMLRoutePersistence loaded"); } @Override public void addRoute(final Route route) { routes.add(route); listener.routeAdded(route); } @Override public void removeRoute(final Route route) { routes.remove(route); listener.routeRemoved(route); } @Override public void updateRoute(final Route route) { routes.remove(route); routes.add(route); listener.routeUpdated(route); } @Override public SortedSet<RouteGroup> getAllRouteGroups() { return routeGroups; } @Override public void addRouteGroup(final RouteGroup routeGroup) { routeGroups.add(routeGroup); listener.routeGroupAdded(routeGroup); } @Override public void removeRouteGroup(final RouteGroup routeGroup) { routeGroups.remove(routeGroup); listener.routeGroupRemoved(routeGroup); } @Override public void updateRouteGroup(final RouteGroup routeGroup) { routeGroups.remove(routeGroup); routeGroups.add(routeGroup); listener.routeGroupUpdated(routeGroup); } @Override public void addRouteItem(final RouteItem item) { } @Override public void removeRouteItem(final RouteItem item) { } @Override public void updateRouteItem(final RouteItem item) { } @Override public void clear() { routes.clear(); routeGroups.clear(); } @Override public void init(final RouteServiceListener listener) { this.listener = listener; } @Override public void disconnect() { } public void loadRouteGroupsFromXML(final SortedSet<RouteGroup> groups) { routeGroups.clear(); routes.clear(); if (groups != null) { for (final RouteGroup routeGroup : groups) { routeGroup.init(); routeGroups.add(routeGroup); if (routeGroup.getRoutes() == null || routeGroup.getRoutes().isEmpty()) { routeGroup.setRoutes(new TreeSet<Route>()); } for (final Route route : routeGroup.getRoutes()) { route.init(); routes.add(route); route.setRouteGroup(routeGroup); } } } listener.routesUpdated(routeGroups); } }
forkch/adhoc-railway
ch.fork.adhocrailway.persistence.xml/src/main/java/ch/fork/adhocrailway/persistence/xml/impl/XMLRouteService.java
Java
gpl-3.0
4,013
/* Gerador de nomes @author Maickon Rangel @copyright Help RPG - 2016 */ function download_para_pdf(){ var doc = new jsPDF(); var specialElementHandlers = { '#editor': function (element, renderer) { return true; } }; doc.fromHTML($('#content').html(), 15, 15, { 'width': 170, 'elementHandlers': specialElementHandlers }); doc.save('sample-file.pdf'); } function rand_nomes(){ var selecionado = $("#select").val(); if(!$('#disable_mode_draw').is(':checked')) { var intervalo = window.setInterval(function(){ var raca = $.ajax({ type: 'post', dataType: 'html', url: JS_SERVICE_NAME_PATH + '/' + selecionado + '/9', data: {select: selecionado}, success: function(result){ var json = (eval("(" + result + ")")); var attr = [ 'nome-1', 'nome-2', 'nome-3', 'nome-4', 'nome-5', 'nome-6', 'nome-7', 'nome-8', 'nome-9' ]; for(var i=0; i<attr.length; i++){ $( "#"+attr[i] ).empty(); $( "#"+attr[i] ).append(json[i]); } } }); }, speed); window.setTimeout(function() { clearInterval(intervalo); }, time); } else if ($('#disable_mode_draw').is(':checked')){ var raca = $.ajax({ type: 'post', dataType: 'html', url: JS_SERVICE_NAME_PATH + '/' + selecionado + '/9', data: {select: selecionado}, success: function(result){ var json = (eval("(" + result + ")")); var attr = [ 'nome-1', 'nome-2', 'nome-3', 'nome-4', 'nome-5', 'nome-6', 'nome-7', 'nome-8', 'nome-9' ]; for(var i=0; i<attr.length; i++){ $( "#"+attr[i] ).empty(); $( "#"+attr[i] ).append(json[i]); } } }); } }
maickon/Help-RPG-4.0
app/assets/js/nomes/nomes.js
JavaScript
gpl-3.0
2,470
#ifndef XTRAS_TYPEMATH_HPP_ #define XTRAS_TYPEMATH_HPP_ #include <type_traits> #include <functional> namespace xtras { namespace typemath { template<auto V> using make_integral_constant = std::integral_constant<decltype(V), V>; template<typename Op, typename T1, typename T2> using binary_op = make_integral_constant<Op{}(T1::value, T2::value)>; template<typename Op, typename T1> using unary_op = make_integral_constant<Op{}(T1::value)>; template<typename T1, typename T2> using plus = binary_op<std::plus<>, T1, T2>; template<typename T1, typename T2> using minus = binary_op<std::minus<>, T1, T2>; template<typename T1, typename T2> using multiplies = binary_op<std::multiplies<>, T1, T2>; template<typename T1, typename T2> using divides = binary_op<std::divides<>, T1, T2>; template<typename T1, typename T2> using modulus = binary_op<std::modulus<>, T1, T2>; template<typename T1> using negate = unary_op<std::negate<>, T1>; template<typename T1, typename T2> using equal_to = binary_op<std::equal_to<>, T1, T2>; template<typename T1, typename T2> using not_equal_to = binary_op<std::not_equal_to<>, T1, T2>; template<typename T1, typename T2> using greater = binary_op<std::greater<>, T1, T2>; template<typename T1, typename T2> using greater_equal = binary_op<std::greater_equal<>, T1, T2>; template<typename T1, typename T2> using less = binary_op<std::less<>, T1, T2>; template<typename T1, typename T2> using less_equal = binary_op<std::less_equal<>, T1, T2>; template<typename T> using logical_not = unary_op<std::logical_not<>, T>; template<typename T1, typename T2> using logical_or = binary_op<std::logical_or<>, T1, T2>; template<typename T1, typename T2> using logical_and = binary_op<std::logical_and<>, T1, T2>; template<typename T> using bit_not = unary_op<std::bit_not<>, T>; template<typename T1, typename T2> using bit_or = binary_op<std::bit_or<>, T1, T2>; template<typename T1, typename T2> using bit_and = binary_op<std::bit_and<>, T1, T2>; template<typename T1, typename T2> using bit_xor = binary_op<std::bit_xor<>, T1, T2>; } // namespace typemath } // namespace xtras #endif // XTRAS_TYPEMATH_HPP_
witosx/rafalw
src/xtras/typemath.hpp
C++
gpl-3.0
2,158
/* ppddl-planner - client for IPPC'08 Copyright (C) 2008 Florent Teichteil-Koenigsbuch and Guillaume Infantes and Ugur Kuter This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "symbolic_lao.h" SymbolicLAO::SymbolicLAO(const Problem& pb, double epsilon, double discount_factor, unsigned int plan_length, heuristic_t heuristic_type, determinization_t determinization_type, deterministic_planner_t deterministic_planner_type) try : BaseAlgorithm(pb, epsilon, discount_factor), SymbolicHeuristicAlgorithm(pb, epsilon, discount_factor, plan_length, heuristic_type, determinization_type, deterministic_planner_type) { policy_deterministic_transitions_ = dd_node_ptr(Cudd_ReadLogicZero(dd_node_ptr::get_cudd_manager())); forward_reachable_states_ = dd_node_ptr(Cudd_ReadLogicZero(dd_node_ptr::get_cudd_manager())); backward_reachable_states_ = dd_node_ptr(Cudd_ReadLogicZero(dd_node_ptr::get_cudd_manager())); states_frontier_ = dd_node_ptr(Cudd_ReadLogicZero(dd_node_ptr::get_cudd_manager())); mdp_->connect_bdd(policy_deterministic_transitions_); mdp_->connect_bdd(forward_reachable_states_); mdp_->connect_bdd(backward_reachable_states_); mdp_->connect_bdd(states_frontier_); } catch (BaseException& error) { error.push_function_backtrace("SymbolicLAO::SymbolicLAO"); throw; } SymbolicLAO::~SymbolicLAO() { mdp_->disconnect_bdd(policy_deterministic_transitions_); mdp_->disconnect_bdd(forward_reachable_states_); mdp_->disconnect_bdd(backward_reachable_states_); mdp_->disconnect_bdd(states_frontier_); } void SymbolicLAO::solve_initialize(const PddlState& st) { SymbolicHeuristicAlgorithm::solve_initialize(st); forward_reachable_states_.copy(initial_state_); states_frontier_.copy(initial_state_); policy_deterministic_transitions_ = dd_node_ptr(Cudd_ReadLogicZero(dd_node_ptr::get_cudd_manager())); } void SymbolicLAO::solve_progress() { compute_backward_reachability(); optimize(backward_reachable_states_); compute_forward_reachability(); } bool SymbolicLAO::has_converged() { return (states_frontier_.get() == Cudd_ReadLogicZero(dd_node_ptr::get_cudd_manager())); } void SymbolicLAO::compute_backward_reachability() { backward_reachable_states_.copy(states_frontier_); dd_node_ptr backward_frontier; backward_frontier.copy(states_frontier_); while (backward_frontier.get() != Cudd_ReadLogicZero(dd_node_ptr::get_cudd_manager())) { dd_node_ptr previous_states(Cudd_bddPermute(dd_node_ptr::get_cudd_manager(), backward_frontier.get(), mdp_->get_unprimed_to_primed_permutation())); previous_states = dd_node_ptr(Cudd_bddAnd(dd_node_ptr::get_cudd_manager(), policy_deterministic_transitions_.get(), previous_states.get())); previous_states = dd_node_ptr(Cudd_bddExistAbstract(dd_node_ptr::get_cudd_manager(), previous_states.get(), mdp_->get_primed_variables_bdd_cube().get())); backward_frontier = dd_node_ptr(Cudd_bddAnd(dd_node_ptr::get_cudd_manager(), backward_reachable_states_.get(), previous_states.get())); backward_frontier = dd_node_ptr(Cudd_bddXor(dd_node_ptr::get_cudd_manager(), backward_frontier.get(), previous_states.get())); backward_reachable_states_ = dd_node_ptr(Cudd_bddOr(dd_node_ptr::get_cudd_manager(), backward_reachable_states_.get(), backward_frontier.get())); } } void SymbolicLAO::compute_forward_reachability() { forward_reachable_states_.copy(initial_state_); dd_node_ptr forward_frontier; forward_frontier.copy(initial_state_); states_frontier_ = dd_node_ptr(Cudd_ReadLogicZero(dd_node_ptr::get_cudd_manager())); policy_deterministic_transitions_ = compute_policy_deterministic_transitions(explored_states_); while (forward_frontier.get() != Cudd_ReadLogicZero(dd_node_ptr::get_cudd_manager())) { dd_node_ptr next_states(Cudd_bddAnd(dd_node_ptr::get_cudd_manager(), forward_frontier.get(), policy_deterministic_transitions_.get())); next_states = dd_node_ptr(Cudd_bddExistAbstract(dd_node_ptr::get_cudd_manager(), next_states.get(), mdp_->get_unprimed_variables_bdd_cube().get())); next_states = dd_node_ptr(Cudd_bddPermute(dd_node_ptr::get_cudd_manager(), next_states.get(), mdp_->get_primed_to_unprimed_permutation())); forward_frontier = dd_node_ptr(Cudd_bddAnd(dd_node_ptr::get_cudd_manager(), next_states.get(), forward_reachable_states_.get())); forward_frontier = dd_node_ptr(Cudd_bddXor(dd_node_ptr::get_cudd_manager(), next_states.get(), forward_frontier.get())); dd_node_ptr new_states_frontier = forward_frontier; forward_reachable_states_ = dd_node_ptr(Cudd_bddOr(dd_node_ptr::get_cudd_manager(), forward_reachable_states_.get(), new_states_frontier.get())); forward_frontier = dd_node_ptr(Cudd_bddAnd(dd_node_ptr::get_cudd_manager(), new_states_frontier.get(), tip_states_.get())); states_frontier_ = dd_node_ptr(Cudd_bddOr(dd_node_ptr::get_cudd_manager(), states_frontier_.get(), forward_frontier.get())); forward_frontier = dd_node_ptr(Cudd_bddXor(dd_node_ptr::get_cudd_manager(), new_states_frontier.get(), forward_frontier.get())); } initialize(states_frontier_); }
fteicht/ppddl-planner
src/algorithms/symbolic_lao.cc
C++
gpl-3.0
5,674
define(['forum/accountheader'], function(header) { var AccountSettings = {}; AccountSettings.init = function() { header.init(); $('#submitBtn').on('click', function() { var settings = { showemail: $('#showemailCheckBox').is(':checked') ? 1 : 0 }; socket.emit('user.saveSettings', settings, function(err) { if (err) { return app.alertError('There was an error saving settings!'); } app.alertSuccess('Settings saved!'); }); return false; }); }; return AccountSettings; });
changyou/NadBB
public/src/forum/accountsettings.js
JavaScript
gpl-3.0
522
<?php /** * @version $Id$ * @copyright Center for History and New Media, 2007-2010 * @license http://www.gnu.org/licenses/gpl-3.0.txt * @package Omeka **/ /** * * * @package Omeka * @copyright Center for History and New Media, 2007-2010 **/ class Omeka_File_Derivative_Image_Creator_CreatorTest extends PHPUnit_Framework_TestCase { public function setUp() { try { $this->convertDir = Zend_Registry::get('test_config')->paths->imagemagick; } catch (Zend_Exception $e) { $this->convertDir = dirname(`which convert`); } $this->invalidFile = '/foo/bar/baz.html'; $this->validFilePath = dirname(__FILE__) . '/_files/valid-image.jpg'; $this->validMimeType = 'image/jpeg'; $this->fullsizeImgType = 'fullsize'; $this->derivativeFilename = 'valid-image_deriv.jpg'; // If we set up a test log, then log the ImageMagick commands instead // of executing via the commandline. $this->logWriter = new Zend_Log_Writer_Mock; $this->testLog = new Zend_Log($this->logWriter); } public function testConstructor() { $creator = new Omeka_File_Derivative_Image_Creator($this->convertDir); $this->assertEquals("{$this->convertDir}/convert", $creator->getConvertPath()); } public function testCreateWithoutProvidingDerivativeFilename() { try { $creator = new Omeka_File_Derivative_Image_Creator($this->convertDir); $creator->create($this->validFilePath, '', $this->validMimeType); } catch (InvalidArgumentException $e) { $this->assertContains("Invalid derivative filename", $e->getMessage()); return; } $this->fail("create() should have failed when a derivative filename was not provided."); } public function testCreateWithInvalidConvertPath() { try { $creator = new Omeka_File_Derivative_Image_Creator('/foo/bar'); } catch (Omeka_File_Derivative_Exception $e) { $this->assertContains("invalid directory", $e->getMessage()); return; } $this->fail("Instantiating with a valid convert path failed to throw an exception."); } public function testCreate() { $creator = new Omeka_File_Derivative_Image_Creator($this->convertDir); // Should do nothing. $creator->create($this->validFilePath, $this->derivativeFilename, $this->validMimeType); } public function testCreateWithInvalidOriginalFile() { $creator = new Omeka_File_Derivative_Image_Creator($this->convertDir); try { $creator->create($this->invalidFile, $this->derivativeFilename, $this->validMimeType); } catch (Exception $e) { $this->assertContains("does not exist", $e->getMessage()); return; } $this->fail("Failed to throw an exception when given an invalid original file."); } public function testAddDerivativeWithInvalidDerivativeType() { $creator = new Omeka_File_Derivative_Image_Creator($this->convertDir); try { $creator->addDerivative("/foo/bar/baz", 20); } catch (Exception $e) { $this->assertContains("Invalid derivative type", $e->getMessage()); return; } $this->fail("Failed to throw exception when given invalid type name for image derivatives."); } public function testCreateWithDerivativeImgSize() { $creator = new Omeka_File_Derivative_Image_Creator($this->convertDir); $creator->addDerivative($this->fullsizeImgType, 10); $creator->create($this->validFilePath, $this->derivativeFilename, $this->validMimeType); $newFilePath = dirname($this->validFilePath) . '/' . $this->fullsizeImgType . '_' . $this->derivativeFilename; $this->assertTrue(file_exists($newFilePath)); unlink($newFilePath); } public function testCreateWithDerivativeCommandArgs() { $creator = new Omeka_File_Derivative_Image_Creator($this->convertDir); } }
sipes23/Omeka
application/tests/unit/libraries/Omeka/File/Derivative/Image/CreatorTest.php
PHP
gpl-3.0
4,163
/** * Copyright (C) 2001-2016 by RapidMiner and the contributors * * Complete list of developers available at our web site: * * http://rapidminer.com * * This program is free software: you can redistribute it and/or modify it under the terms of the * GNU Affero General Public License as published by the Free Software Foundation, either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. * If not, see http://www.gnu.org/licenses/. */ package com.rapidminer.example.test; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Random; import com.rapidminer.example.Attribute; import com.rapidminer.example.Attributes; import com.rapidminer.example.ExampleSet; import com.rapidminer.example.table.AttributeFactory; import com.rapidminer.example.table.DataRow; import com.rapidminer.example.table.DataRowFactory; import com.rapidminer.example.table.DataRowReader; import com.rapidminer.example.table.DoubleArrayDataRow; import com.rapidminer.example.table.ListDataRowReader; import com.rapidminer.example.table.MemoryExampleTable; import com.rapidminer.tools.Ontology; /** * Provides factory methods for text fixtures. * * @author Simon Fischer, Ingo Mierswa */ public class ExampleTestTools { /** Returns a DataRowReader returning the given values. */ public static DataRowReader createDataRowReader(DataRowFactory factory, Attribute[] attributes, String[][] values) { List<DataRow> dataRows = new LinkedList<DataRow>(); for (int i = 0; i < values.length; i++) { dataRows.add(factory.create(values[i], attributes)); } return new ListDataRowReader(dataRows.iterator()); } /** Returns a DataRowReader returning the given values. */ public static DataRowReader createDataRowReader(double[][] values) { List<DataRow> dataRows = new LinkedList<DataRow>(); for (int i = 0; i < values.length; i++) { dataRows.add(new DoubleArrayDataRow(values[i])); } return new ListDataRowReader(dataRows.iterator()); } /** * Returns a DataRowReader returning random values (generated with fixed * random seed). */ public static DataRowReader createDataRowReader(int size, Attribute[] attributes) { Random random = new Random(0); List<DataRow> dataRows = new LinkedList<DataRow>(); for (int i = 0; i < size; i++) { double[] data = new double[attributes.length]; for (int j = 0; j < data.length; j++) { if (attributes[j].isNominal()) { data[j] = random.nextInt(attributes[j].getMapping().getValues().size()); } if (attributes[j].getValueType() == Ontology.INTEGER) { data[j] = random.nextInt(200) - 100; } else { data[j] = 20.0 * random.nextDouble() - 10.0; } } dataRows.add(new DoubleArrayDataRow(data)); } return new ListDataRowReader(dataRows.iterator()); } public static MemoryExampleTable createMemoryExampleTable(int size) { Attribute[] attributes = createFourAttributes(); return new MemoryExampleTable(Arrays.asList(attributes), createDataRowReader(size, attributes)); } public static Attribute attributeDogCatMouse() { Attribute a = AttributeFactory.createAttribute("animal", Ontology.NOMINAL); a.getMapping().mapString("dog"); a.getMapping().mapString("cat"); a.getMapping().mapString("mouse"); return a; } public static Attribute attributeYesNo() { Attribute a = AttributeFactory.createAttribute("decision", Ontology.NOMINAL); a.getMapping().mapString("no"); a.getMapping().mapString("yes"); return a; } public static Attribute attributeInt() { Attribute a = AttributeFactory.createAttribute("integer", Ontology.INTEGER); return a; } public static Attribute attributeReal() { Attribute a = AttributeFactory.createAttribute("real", Ontology.REAL); return a; } public static Attribute attributeReal(int index) { Attribute a = AttributeFactory.createAttribute("real" + index, Ontology.REAL); return a; } /** * Creates four attributes: "animal" (dog/cat/mouse), "decision" (yes/no), * "int", and "real". */ public static Attribute[] createFourAttributes() { Attribute[] attributes = new Attribute[4]; attributes[0] = ExampleTestTools.attributeDogCatMouse(); attributes[1] = ExampleTestTools.attributeYesNo(); attributes[2] = ExampleTestTools.attributeInt(); attributes[3] = ExampleTestTools.attributeReal(); for (int i = 0; i < attributes.length; i++) attributes[i].setTableIndex(i); return attributes; } public static Attribute createPredictedLabel(ExampleSet exampleSet) { Attribute predictedLabel = AttributeFactory.createAttribute(exampleSet.getAttributes().getLabel(), Attributes.PREDICTION_NAME); exampleSet.getExampleTable().addAttribute(predictedLabel); exampleSet.getAttributes().setPredictedLabel(predictedLabel); return predictedLabel; } }
transwarpio/rapidminer
rapidMiner/rapidminer-studio-core/src/test/java/com/rapidminer/example/test/ExampleTestTools.java
Java
gpl-3.0
5,152
// Decompiled with JetBrains decompiler // Type: System.CodeDom.Compiler.CodeParser // Assembly: System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 // MVID: 5ABD58FD-DF31-44FD-A492-63F2B47CC9AF // Assembly location: C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.dll using System.CodeDom; using System.IO; using System.Runtime; using System.Security.Permissions; namespace System.CodeDom.Compiler { /// <summary> /// Provides an empty implementation of the <see cref="T:System.CodeDom.Compiler.ICodeParser"/> interface. /// </summary> [PermissionSet(SecurityAction.InheritanceDemand, Name = "FullTrust")] [PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")] public abstract class CodeParser : ICodeParser { /// <summary> /// Initializes a new instance of the <see cref="T:System.CodeDom.Compiler.CodeParser"/> class. /// </summary> [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] protected CodeParser() { } /// <summary> /// Compiles the specified text stream into a <see cref="T:System.CodeDom.CodeCompileUnit"/>. /// </summary> /// /// <returns> /// A <see cref="T:System.CodeDom.CodeCompileUnit"/> containing the code model produced from parsing the code. /// </returns> /// <param name="codeStream">A <see cref="T:System.IO.TextReader"/> that is used to read the code to be parsed. </param> public abstract CodeCompileUnit Parse(TextReader codeStream); } }
mater06/LEGOChimaOnlineReloaded
LoCO Client Files/Decompressed Client/Extracted DLL/System/System/CodeDom/Compiler/CodeParser.cs
C#
gpl-3.0
1,547
"""Feat components.""" from component_objects import Component, Element class FeatAddModal(Component): """Definition of feat add modal component.""" modal_div_id = 'addFeat' name_id = 'featAddNameInput' description_id = 'featAddDescriptionTextarea' tracked_id = 'featAddTrackedCheckbox' max_id = 'featAddMaxInput' short_rest_id = 'featAddShortRestInput' long_rest_id = 'featAddLongRestInput' add_id = 'featAddAddButton' modal_div = Element(id_=modal_div_id) name = Element(id_=name_id) description = Element(id_=description_id) tracked = Element(id_=tracked_id) max_ = Element(id_=max_id) short_rest = Element(id_=short_rest_id) long_rest = Element(id_=long_rest_id) add = Element(id_=add_id) class FeatEditModal(Component): """Definition of feat edit modal component.""" modal_div_id = 'viewWeapon' name_id = 'featEditNameInput' description_id = 'featEditDescriptionTextarea' tracked_id = 'featEditTrackedCheckbox' max_id = 'featEditMaxInput' short_rest_id = 'featEditShortRestInput' long_rest_id = 'featEditLongRestInput' done_id = 'featEditDoneButton' modal_div = Element(id_=modal_div_id) name = Element(id_=name_id) description = Element(id_=description_id) tracked = Element(id_=tracked_id) max_ = Element(id_=max_id) short_rest = Element(id_=short_rest_id) long_rest = Element(id_=long_rest_id) done = Element(id_=done_id) class FeatModalTabs(Component): """Definition of feat modal tabs component.""" preview_id = 'featModalPreview' edit_id = 'featModalEdit' preview = Element(id_=preview_id) edit = Element(id_=edit_id) class FeatsTable(Component): """Definition of feats edit modal componenet.""" add_id = 'featAddIcon' table_id = 'featTable' add = Element(id_=add_id) table = Element(id_=table_id)
adventurerscodex/uat
components/core/character/feats.py
Python
gpl-3.0
1,902
#include "prizelistmodel.h" #include <QStringList> prizelistmodel::prizelistmodel(QObject *parent) : QAbstractListModel(parent) { content = new QStringList; } QVariant prizelistmodel::data(const QModelIndex &index, int role) const { if( !index.isValid() || index.row() > content->size() || (role != Qt::DisplayRole && role != Qt::EditRole) ) return QVariant(); if( index.row() == content->size() ) return QString(); else return content->at(index.row()); } bool prizelistmodel::setData(const QModelIndex &index, const QVariant &value, int role) { if( index.row() > content->size() || value.type() != QVariant::String || role != Qt::EditRole ) return false; bool ok = true; if( index.row() == content->size() ) ok = insertRows(index.row(),1,QModelIndex(),value.toString()); else (*content)[index.row()] = value.toString(); if( ok ) emit dataChanged(index,index); return ok; } int prizelistmodel::rowCount(const QModelIndex &) const { return content->size()+1; } Qt::ItemFlags prizelistmodel::flags(const QModelIndex &) const { return Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsEnabled; } QVariant prizelistmodel::headerData(int section, Qt::Orientation orientation, int role) const { if( role != Qt::DisplayRole ) return QVariant(); if( orientation == Qt::Horizontal ) return tr("Preis"); else //Qt::Vertical return section+1; } bool prizelistmodel::insertRows(int row, int count, const QModelIndex &parent, const QString &value) { if( row > content->size() || count == 0 ) return false; if( row < 0 ) row = 0; beginInsertRows(parent,row+1,row+count); for(int num = 0; num < count; num++) content->insert(row+1,value); endInsertRows(); return true; } bool prizelistmodel::removeRows(int row, int count, const QModelIndex &parent) { if( row < 0 || row >= content->size() ) return false; beginRemoveRows(parent,row,row+count-1); for(int num = 0; num < count; num++) content->removeAt(row); endRemoveRows(); return true; } void prizelistmodel::clear() { beginResetModel(); content->clear(); endResetModel(); } void prizelistmodel::newData() { beginResetModel(); endResetModel(); } bool prizelistmodel::moveRowDown(int row) { if( row < 0 || row >= content->size() ) //don't move the "pseudo-row" return false; if( row == content->size()-1 ) //we can't move anything below the pseudo-row, instead we insert a blank row above return insertRows(row-1,1,QModelIndex()); content->swap(row,row+1); emit dataChanged(createIndex(row,0),createIndex(row+1,0)); return true; } bool prizelistmodel::moveRowUp(int row) { if( row < 1 || row >= content->size() ) //don't move hightest row return false; content->swap(row-1,row); emit dataChanged(createIndex(row-1,0),createIndex(row,0)); return true; } bool prizelistmodel::duplicateRow(int row) { if( row < 0 || row >= content->size() ) return false; beginInsertRows(QModelIndex(),row+1,row+1); content->insert(row+1,content->at(row)); endInsertRows(); return true; }
flesniak/duckracer2
prizelistmodel.cpp
C++
gpl-3.0
3,254
/* * QuestManager: An RPG plugin for the Bukkit API. * Copyright (C) 2015-2016 Github Contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.skyisland.questmanager.effects; import org.bukkit.Effect; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; /** * Effect signaling to the player that the entity they just interacted with was correct. * This EFFECT was made with the 'slay' requirement in mind, where it'll display effects when you kill * the right kind of enemy. * */ public class EntityConfirmEffect extends QuestEffect { private static final Effect EFFECT = Effect.STEP_SOUND; @SuppressWarnings("deprecation") private static final int BLOCK_TYPE = Material.EMERALD_BLOCK.getId(); /** * The number of particals */ private int magnitude; /** * * @param magnitude The number of particals, roughly */ public EntityConfirmEffect(int magnitude) { this.magnitude = magnitude; } @SuppressWarnings("deprecation") @Override public void play(Entity player, Location effectLocation) { if (!(player instanceof Player)) { return; } for (int i = 0; i < magnitude; i++) ((Player) player ) .playEffect(effectLocation, EFFECT, BLOCK_TYPE); } }
Dove-Bren/QuestManager
src/main/java/com/skyisland/questmanager/effects/EntityConfirmEffect.java
Java
gpl-3.0
1,904
/*====================================================================== maker :jiaxing.shen date :2014.12.10 email :55954781@qq.com ======================================================================*/ #include "m_include.h" #include "m_nvic.h" #include "m_eep.h" #include "stm32746g_discovery.h" #include "stm32f7xx_hal_flash.h" // //====================================================================== // 写入 //====================================================================== void c_eep::wirte(uint8 *source, uint32 tarAddr, uint16 len) { uint32_t FirstSector = 0, NbOfSectors = 0; uint32_t Address = 0, SECTORError = 0; __IO uint32_t data32 = 0 , MemoryProgramStatus = 0; FLASH_EraseInitTypeDef EraseInitStruct; // //------------------------------------ // 0. 关闭系统中断 nvic.globalDisable(); // //------------------------------------ // 1. 开启内部高速时钟 // RCC->CR |= ((uint32_t)RCC_CR_HSION); // while((RCC->CR & RCC_CR_HSIRDY) == 0); // //------------------------------------ // 2. 解锁 HAL_FLASH_Unlock(); // //------------------------------------ // 3. 擦除并写入数据 /* Get the 1st sector to erase */ FirstSector = GetSector(tarAddr); /* Get the number of sector to erase from 1st sector*/ NbOfSectors = 1; /* Fill EraseInit structure*/ EraseInitStruct.TypeErase = FLASH_TYPEERASE_SECTORS; EraseInitStruct.VoltageRange = FLASH_VOLTAGE_RANGE_3; EraseInitStruct.Sector = FirstSector; EraseInitStruct.NbSectors = NbOfSectors; if (HAL_FLASHEx_Erase(&EraseInitStruct, &SECTORError) != HAL_OK) { while (1) { /* Make LED1 blink (100ms on, 2s off) to indicate error in Erase operation */ BSP_LED_On(LED1); HAL_Delay(100); BSP_LED_Off(LED1); HAL_Delay(2000); } } Address = tarAddr; //while (Address < tarAddr) for(int i=0; i<len; i++) { if (HAL_FLASH_Program(FLASH_TYPEPROGRAM_BYTE, Address, *source) == HAL_OK) { Address = Address + 1; source++; } else { /* Error occurred while writing data in Flash memory. User can add here some code to deal with this error */ while (1) { /* Make LED1 blink (100ms on, 2s off) to indicate error in Write operation */ BSP_LED_On(LED1); HAL_Delay(100); BSP_LED_Off(LED1); HAL_Delay(2000); } } } // EraseSector(tarAddr); // ProgramPage(tarAddr, len, source); // //------------------------------------ // 4. 锁定 HAL_FLASH_Lock(); // //------------------------------------ // 5. 关闭内部高速时钟 //RCC->CR &= ~((uint32_t)RCC_CR_HSION); // while(RCC->CR & RCC_CR_HSIRDY); // //------------------------------------ // 6. 开启中断 nvic.globalEnable(); } // //====================================================================== // 初始化EEP 功能 //====================================================================== /* * Initialize Flash Programming Functions * Parameter: adr: Device Base Address * clk: Clock Frequency (Hz) * fnc: Function Code (1 - Erase, 2 - Program, 3 - Verify) * Return Value: 0 - OK, 1 - Failed */ int c_eep::Init () { HAL_FLASH_Lock(); } // //====================================================================== // 结束解锁 //====================================================================== /* * De-Initialize Flash Programming Functions * Parameter: fnc: Function Code (1 - Erase, 2 - Program, 3 - Verify) * Return Value: 0 - OK, 1 - Failed */ int c_eep::UnInit () { HAL_FLASH_Unlock(); } // //====================================================================== // 扇区擦除 //====================================================================== /* * Erase Sector in Flash Memory * Parameter: adr: Sector Address * Return Value: 0 - OK, 1 - Failed */ int c_eep::EraseSector (unsigned long adr) { FLASH_Erase_Sector(adr,FLASH_VOLTAGE_RANGE_1);//? } // //====================================================================== // 页编程 //====================================================================== /* * Program Page in Flash Memory * Parameter: adr: Page Start Address * sz: Page Size * buf: Page Data * Return Value: 0 - OK, 1 - Failed */ int c_eep::ProgramPage (unsigned long adr, unsigned long sz, unsigned char *buf) { } /** * @brief Gets the sector of a given address * @param None * @retval The sector of a given address */ int c_eep::GetSector(uint32_t Address) { uint32_t sector = 0; if((Address < ADDR_FLASH_SECTOR_1) && (Address >= ADDR_FLASH_SECTOR_0)) { sector = FLASH_SECTOR_0; } else if((Address < ADDR_FLASH_SECTOR_2) && (Address >= ADDR_FLASH_SECTOR_1)) { sector = FLASH_SECTOR_1; } else if((Address < ADDR_FLASH_SECTOR_3) && (Address >= ADDR_FLASH_SECTOR_2)) { sector = FLASH_SECTOR_2; } else if((Address < ADDR_FLASH_SECTOR_4) && (Address >= ADDR_FLASH_SECTOR_3)) { sector = FLASH_SECTOR_3; } else if((Address < ADDR_FLASH_SECTOR_5) && (Address >= ADDR_FLASH_SECTOR_4)) { sector = FLASH_SECTOR_4; } else if((Address < ADDR_FLASH_SECTOR_6) && (Address >= ADDR_FLASH_SECTOR_5)) { sector = FLASH_SECTOR_5; } else if((Address < ADDR_FLASH_SECTOR_7) && (Address >= ADDR_FLASH_SECTOR_6)) { sector = FLASH_SECTOR_6; } else /* (Address < FLASH_END_ADDR) && (Address >= ADDR_FLASH_SECTOR_7) */ { sector = FLASH_SECTOR_7; } return sector; } // //====================================================================== c_eep eep; // //======================================================================
jackeyjiang/meizi_f7disc
GUIDemo/emwin_task/smarthome/fdm/m_eep.cpp
C++
gpl-3.0
6,013
package sc.ndt.editor.fast.ui.mpe.outline; import java.util.ArrayList; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IStatusLineManager; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.viewers.CheckStateChangedEvent; import org.eclipse.jface.viewers.CheckboxTreeViewer; import org.eclipse.jface.viewers.ColumnLabelProvider; import org.eclipse.jface.viewers.ICheckStateListener; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.TreeViewerColumn; import org.eclipse.swt.SWT; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.TreeColumn; import org.eclipse.ui.IActionBars; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.forms.editor.FormEditor; import org.eclipse.ui.part.IPageSite; import org.eclipse.ui.part.Page; import org.eclipse.ui.part.PageBook; import org.eclipse.ui.views.contentoutline.IContentOutlinePage; import org.eclipse.xtext.resource.XtextResource; import org.eclipse.xtext.util.concurrent.IUnitOfWork; import sc.ndt.commons.model.OutBlock; import sc.ndt.commons.model.OutCh; import sc.ndt.commons.model.OutList; import sc.ndt.commons.model.providers.outlist.OutListCheckStateProvider; import sc.ndt.commons.model.providers.outlist.OutListContentProvider; import sc.ndt.commons.model.providers.outlist.OutListLabelProvider; import sc.ndt.commons.model.providers.outlist.OutListToolTipSupport; import sc.ndt.commons.model.providers.outlist.OutListViewerComparator; import sc.ndt.commons.ui.views.EmptyOutlinePage; import sc.ndt.editor.fast.fastfst.ModelFastfst; import sc.ndt.editor.fast.ui.mpe.ui.FstFormPage; import sc.ndt.editor.fast.ui.mpe.ui.FstMultiPageEditor; public class OutListContentOutline extends Page implements IContentOutlinePage, ISelectionProvider/*, ISelectionChangedListener*/ { private PageBook pagebook; private ISelection selection; private ArrayList listeners; private /*ISortable*/IContentOutlinePage currentPage; private /*ISortable*/IContentOutlinePage emptyPage; private IActionBars actionBars; private boolean sortingOn; private CheckboxTreeViewer checkboxTreeViewer; private FstMultiPageEditor editor; private OutList outList; public OutListContentOutline(FormEditor formEditor) { this.editor = (FstMultiPageEditor)formEditor; // OutList outList = editor.outList; } public void init(IPageSite pageSite) { super.init(pageSite); pageSite.setSelectionProvider(this); //pageSite.getPage().addSelectionListener(this); } public void addSelectionChangedListener(ISelectionChangedListener listener) { //listeners.add(listener); } public void createControl(Composite parent) { //pagebook = new PageBook(parent, SWT.NONE); checkboxTreeViewer = new CheckboxTreeViewer(parent, SWT.MULTI); Tree treeTower = checkboxTreeViewer.getTree(); treeTower.setHeaderVisible(true); treeTower.setLinesVisible(true); GridData gd_treeTower = new GridData(SWT.FILL, SWT.TOP, true, false, 1, 1); gd_treeTower.heightHint = 400; treeTower.setLayoutData(gd_treeTower); TreeViewerColumn column_1 = new TreeViewerColumn(checkboxTreeViewer,SWT.NONE); TreeColumn treeColumn = column_1.getColumn(); treeColumn.setResizable(false); column_1.getColumn().setWidth(220); column_1.getColumn().setText("Output Channel"); column_1.setLabelProvider(new OutListLabelProvider()); TreeViewerColumn column_2 = new TreeViewerColumn(checkboxTreeViewer,SWT.NONE); TreeColumn treeColumn_1 = column_2.getColumn(); treeColumn_1.setResizable(false); column_2.getColumn().setWidth(60); column_2.getColumn().setText("Unit"); column_2.setLabelProvider(new ColumnLabelProvider() { public String getText(Object element) { if (element instanceof OutCh) return ((OutCh) element).unit; return ""; } }); checkboxTreeViewer.setContentProvider(new OutListContentProvider()); checkboxTreeViewer.setCheckStateProvider(new OutListCheckStateProvider()); checkboxTreeViewer.setComparator(new OutListViewerComparator()); checkboxTreeViewer.setInput(outList.getAllOutBlocks()); OutListToolTipSupport.enableFor(checkboxTreeViewer); // see // http://www.java2s.com/Code/Java/SWT-JFace-Eclipse/DemonstratesCheckboxTreeViewer.htm checkboxTreeViewer.addCheckStateListener(new ICheckStateListener() { public void checkStateChanged(CheckStateChangedEvent event) { if (event.getChecked()) { checkboxTreeViewer.setSubtreeChecked(event.getElement(), true); Object o = event.getElement(); if (o instanceof OutCh) { outList.get(((OutCh) o).name).setAvailable(true); } else if (o instanceof OutBlock) outList.setBlockSelected((OutBlock) o, true); } else if (!event.getChecked()) { checkboxTreeViewer.setSubtreeChecked(event.getElement(), false); Object o = event.getElement(); if (o instanceof OutCh) outList.get(((OutCh) o).name).setAvailable(false); else if (o instanceof OutBlock) outList.setBlockSelected((OutBlock) o, false); } // TODO write to xtext model editor.getXtextEditor("fst").getDocument().modify(new IUnitOfWork.Void<XtextResource>() { @Override public void process(XtextResource resource) throws Exception { ModelFastfst m = (ModelFastfst) resource.getContents().get(0); if (m != null && m.getOutList() != null) m.getOutList().setValue(outList.getAllSelectedByBlock()); else throw new IllegalStateException("Uh uh, no content"); }; }); checkboxTreeViewer.refresh(); } }); } public void dispose() { if (pagebook != null && !pagebook.isDisposed()) pagebook.dispose(); if (emptyPage != null) { emptyPage.dispose(); emptyPage = null; } pagebook = null; listeners = null; } public Control getControl() { return checkboxTreeViewer.getControl(); } public ISelection getSelection() { return selection; } public void makeContributions(IMenuManager menuManager, IToolBarManager toolBarManager, IStatusLineManager statusLineManager) { } public void removeSelectionChangedListener(ISelectionChangedListener listener) { //listeners.remove(listener); } public void selectionChanged(SelectionChangedEvent event) { setSelection(event.getSelection()); } public void setActionBars(IActionBars actionBars) { this.actionBars = actionBars; registerToolbarActions(actionBars); //if (currentPage != null) // setPageActive(currentPage); } public IActionBars getActionBars() { return actionBars; } public void setFocus() { if (currentPage != null) currentPage.setFocus(); } private /*ISortable*/IContentOutlinePage getEmptyPage() { if (emptyPage == null) emptyPage = new EmptyOutlinePage(); return emptyPage; } /*public void setPageActive(IContentOutlinePage page) { if (page == null) { page = getEmptyPage(); } if (currentPage != null) { currentPage.removeSelectionChangedListener(this); } //page.init(getSite()); //page.sort(sortingOn); page.addSelectionChangedListener(this); this.currentPage = page; if (pagebook == null) { // still not being made return; } Control control = page.getControl(); if (control == null || control.isDisposed()) { // first time page.createControl(pagebook); page.setActionBars(getActionBars()); control = page.getControl(); } pagebook.showPage(control); this.currentPage = page; }*/ /** * Set the selection. */ public void setSelection(ISelection selection) { this.selection = selection; if (listeners == null) return; SelectionChangedEvent e = new SelectionChangedEvent(this, selection); for (int i = 0; i < listeners.size(); i++) { ((ISelectionChangedListener) listeners.get(i)).selectionChanged(e); } } private void registerToolbarActions(IActionBars actionBars) { IToolBarManager toolBarManager = actionBars.getToolBarManager(); if (toolBarManager != null) { //toolBarManager.add(new ToggleLinkWithEditorAction(editor)); toolBarManager.add(new SortingAction()); } } class SortingAction extends Action { public SortingAction() { super(); /* TODO PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IHelpContextIds.OUTLINE_SORT_ACTION); setText(PDEUIMessages.PDEMultiPageContentOutline_SortingAction_label); setImageDescriptor(PDEPluginImages.DESC_ALPHAB_SORT_CO); setDisabledImageDescriptor(PDEPluginImages.DESC_ALPHAB_SORT_CO_DISABLED); setToolTipText(PDEUIMessages.PDEMultiPageContentOutline_SortingAction_tooltip); setDescription(PDEUIMessages.PDEMultiPageContentOutline_SortingAction_description); setChecked(sortingOn); */ } public void run() { setChecked(isChecked()); valueChanged(isChecked()); } private void valueChanged(final boolean on) { sortingOn = on; //if (currentPage != null) // currentPage.sort(on); //PDEPlugin.getDefault().getPreferenceStore().setValue("PDEMultiPageContentOutline.SortingAction.isChecked", on); //$NON-NLS-1$ } } }
cooked/NDT
sc.ndt.editor.fast.fst.ui/src/sc/ndt/editor/fast/ui/mpe/outline/OutListContentOutline.java
Java
gpl-3.0
9,419